모델 양식의 Django 필수 필드
두 개의 필드가 필요하지 않을 때 필요에 따라 나오는 양식이 있습니다. 다음은 models.py의 양식입니다.
class CircuitForm(ModelForm):
class Meta:
model = Circuit
exclude = ('lastPaged',)
def __init__(self, *args, **kwargs):
super(CircuitForm, self).__init__(*args, **kwargs)
self.fields['begin'].widget = widgets.AdminSplitDateTime()
self.fields['end'].widget = widgets.AdminSplitDateTime()
실제 회로 모델에서 필드는 다음과 같이 정의됩니다.
begin = models.DateTimeField('Start Time', null=True, blank=True)
end = models.DateTimeField('Stop Time', null=True, blank=True)
이에 대한 내 views.py는 다음과 같습니다.
def addCircuitForm(request):
if request.method == 'POST':
form = CircuitForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/sla/all')
form = CircuitForm()
return render_to_response('sla/add.html', {'form': form})
두 필드가 필요하지 않게하려면 어떻게해야합니까?
모델 내의 필드에 대한 빈 설정을 수정하지 않으려면 (관리 사이트에서 일반 유효성 검사가 중단됨) Form 클래스에서 다음을 수행 할 수 있습니다.
def __init__(self, *args, **kwargs):
super(CircuitForm, self).__init__(*args, **kwargs)
for key in self.fields:
self.fields[key].required = False
재정의 된 생성자는 기능에 해를 끼치 지 않습니다.
모델 필드에 공백 = True가 있으면 양식 필드에서 required가 False로 설정됩니다. 그렇지 않으면 required = True
여기에 그렇게 말합니다 : http://docs.djangoproject.com/en/dev/topics/forms/modelforms/
모든 것을 올바르게하고있는 것 같습니다. 의 값을 확인할 수 있습니다 self.fields['end'].required
.
DataGreed의 답변을 확장하여 다음 과 같이 클래스에 fields_required
변수 를 지정할 수있는 Mixin을 만들었습니다 Meta
.
class MyForm(RequiredFieldsMixin, ModelForm):
class Meta:
model = MyModel
fields = ['field1', 'field2']
fields_required = ['field1']
여기있어:
class RequiredFieldsMixin():
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
fields_required = getattr(self.Meta, 'fields_required', None)
if fields_required:
for key in self.fields:
if key not in fields_required:
self.fields[key].required = False
대답은 아니지만 Google을 통해 이것을 찾는 다른 사람에게는 데이터가 하나 더 있습니다. 이것은 DateField가있는 모델 양식에서 나에게 발생합니다. False로 설정해야하고 모델에는 "null = True, blank = True"가 있으며 clean () 메서드 중에 보면 양식의 필드에 required = False가 표시되지만 여전히 유효한 날짜가 필요하다고 말합니다. 체재. 특별한 위젯을 사용하지 않고 명시 적으로 input_formats = [ '% Y- % m- % d', '% m / % d / % Y', '를 설정 한 경우에도 "유효한 날짜 입력"메시지가 표시됩니다. 양식 필드의 % m / % d / % y ',' '].
EDIT: Don't know if it'll help anyone else, but I solved the problem I was having. Our form has some default text in the field (in this case, the word "to" to indicate the field is the end date; the field is called "end_time"). I was specifically looking for the word "to" in the form's clean() method (I'd also tried the clean_end_time() method, but it never got called) and setting the value of the clean_data variable to None as suggested in this Django ticket. However, none of that mattered as (I guess) the model's validation had already puked on the invalid date format of "to" without giving me a chance to intercept it.
This is a bug when using the widgets:
workaround: Using Django time/date widgets in custom form
or ticket 12303
From the model field documentation,
If you have a model as shown below,
class Article(models.Model):
headline = models.CharField(
max_length=200,
null=True,
blank=True,
help_text='Use puns liberally',
)
content = models.TextField()
You can change the headline's form validation to required=True
instead of blank=False
as that of the model as defining the field as shown below.
class ArticleForm(ModelForm):
headline = MyFormField(
max_length=200,
required=False,
help_text='Use puns liberally',
)
class Meta:
model = Article
fields = ['headline', 'content']
So answering the question,
class CircuitForm(ModelForm):
begin = forms.DateTimeField(required=False)
end = forms.DateTimeField(required=False)
class Meta:
model = Circuit
exclude = ('lastPaged',)
this makes begin
and end
to required=False
참고URL : https://stackoverflow.com/questions/1134667/django-required-field-in-model-form
'Program Tip' 카테고리의 다른 글
선택한 열에 대한 테이블의 NA 값을 바꾸는 방법 (0) | 2020.10.29 |
---|---|
Angular ng-options에서 값을 연결할 수 있습니까? (0) | 2020.10.29 |
Haskell의 map 함수에 해당하는 C #은 무엇입니까? (0) | 2020.10.29 |
Java에서 유형을 메소드 매개 변수로 전달하는 방법 (0) | 2020.10.29 |
XAML에서 테두리에 대한 MouseOver 이벤트 / 트리거를 설정하는 방법은 무엇입니까? (0) | 2020.10.29 |