I have a modelform in which I want to set required attribute to True for email validation
field:-email
class RegisterMyBuisinessForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.form_method = 'post'
self.helper.form_action = '/registermybuisness/'
Field('email', type='email')
self.helper.add_input(Submit('submit', 'Submit',css_class="btn c-theme-btn c-btn-square c-btn-bold c-btn-uppercase"))
super(RegisterMyBuisinessForm, self).__init__(*args, **kwargs)
class Meta:
model = RegistermyBusiness
fields = ['name','email', 'org_name', 'contact','business_description','store_address','message','store_landmark','business_type','city']
I tried
self.fields['email'].required=True
this resulted in class RegisterMyBuisinessForm doesnot have fields error
You can alter self.fields['email'] in the __init__ method. You need to call super() first.
class RegisterMyBuisinessForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
...
super(RegisterMyBuisinessForm, self).__init__(*args, **kwargs)
self.fields['email'].required = True
...
Related
ModelForm:
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(ChapterCreateForm, self).__init__(*args, **kwargs)
Not working
I wanna add self.field other. But it not working.
This is my code:
class ChapterCreateForm(ModelForm):
class Meta:
model = Chapter
exclude = ('user', 'book',)
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(ChapterCreateForm, self).__init__(*args, **kwargs)
def clean_title(self):
title = self.cleaned_data['title']
if Chapter.objects.filter(user=self.user, title=title).exists():
raise forms.ValidationError('THIS CHAPTER ALREADY WRITTEN')
return title
But this form it's working:
class BookCreateForm(ModelForm):
class Meta:
model = Book
exclude = ('user',)
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(BookCreateForm, self).__init__(*args, **kwargs)
def clean_title(self):
title = self.cleaned_data['title']
if Book.objects.filter(title=title).exists():
if Book.objects.filter(user=self.user, title=title).exists():
raise forms.ValidationError('YOU WROTE THIS BOOK ')
raise forms.ValidationError('THIS BOOK ALREADY WRITTEN')
return title
Please help me. Thanks so much
You need to pass user in the form kwargs by overriding get_form_kwargs in the class UserCreateChapterView as below:
class UserCreateChapterView(UserPassesTestMixin, CreateView):
...
...
def get_form_kwargs(self):
kwargs = super(UserCreateChapterView, self).get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs
Now you can use kwargs.pop('user') in the __init__ method of ChapterCreateForm and it should work.
Hope it helps!
I have a form which I would like to filter based on information passed by another form, but without validating it just yet:
forms.py:
class SampleRunSearchForm(forms.ModelForm):
class Meta:
model = SampleRun
fields = ('id',)
def __init__(self, sr_obj, *args, **kwargs):
super(SampleRunSearchForm, self).__init__(*args, **kwargs)
self.fields['id'] = forms.ChoiceField(required=True,
label='Sample:',
widget=forms.CheckboxSelectMultiple,
choices=((s.id, s) for s in sr_obj)
)
self.helper = FormHelper()
self.helper.layout = Layout(
Field('id', css_class='sample-run-display',),
Submit('submit', 'Report samples', css_class='upload-btn')
)
self.helper.form_method = 'POST'
views.py:
class SearchSampleRun(View):
samplerunform = SampleRunSearchForm
template_name = 'results/samplerun_search_form.html'
def get(self, request, *args, **kwargs):
self.run_obj = get_object_or_404(Run, id=kwargs['run_id'])
self.choice = kwargs['choice']
self.sample_run_obj = self.obtainCorrectSamples()
samplerunform = self.samplerunform(sr_obj=self.sample_run_obj)
context = {'samplerunform': samplerunform}
return render(request, self.template_name, context)
def post(self, request, *args, **kwargs):
samplerunform = self.samplerunform(request.POST)
if samplerunform.is_valid():
HttpResponseRedirect(...somewhere to display information)
context = {}
return render(request, self.template_name, context)
The initial form (not shown) takes a charfield and redirects to my SearchSampleRun view with **kwargs. I want to filter my SampleRunSearchForm based on these kwargs and display a list of check boxes - filtered model object from the SampleRun model. This works, but when i click these buttons, and submit the form, it initialised again, and sr_obj is None, so the form field produces an error.
I have tried using:
sr_obj = kwargs.pop('sr_obj', None)
In my init() method, but these must be a way to dynamically filter a form queryset in order to display a subset of values, before validating, with a view to validating when this form is submitted?
Just add validation to the __init__ method and override id fields only if sr_objis not empty:
def __init__(self, sr_obj, *args, **kwargs):
super(SampleRunSearchForm, self).__init__(*args, **kwargs)
if sr_obj:
self.fields['id'] = forms.ChoiceField(required=True,
label='Sample:',
widget=forms.CheckboxSelectMultiple,
choices=((s.id, s) for s in sr_obj)
)
self.helper = FormHelper()
self.helper.layout = Layout(
Field('id', css_class='sample-run-display',),
Submit('submit', 'Report samples', css_class='upload-btn')
)
self.helper.form_method = 'POST'
Why is this form not validating? It is not even calling the clean() method.
forms.py:
class SingleSampleForm(forms.Form):
sample_id = forms.CharField(label='Sample ID:')
class Meta:
fields = ('sample_id',)
def __init__(self, *args, **kwargs):
super(SingleSampleForm, self).__init__()
self.helper = FormHelper()
self.helper.layout = Layout(
Field('sample_id',
css_class="search-form-label",),
Submit('submit', 'Search sample', css_class='upload-btn')
)
self.helper.form_method = 'POST'
def clean(self):
print('CLEAN')
sample_id = self.cleaned_data['sample_id']
if sample_id:
return sample_id
raise ValidationError('This field is required')
views.py:
class SampleView(View):
sample_form = SingleSampleForm
def get(self, request, *args, **kwargs):
sample_form = self.sample_form()
self.context = {'sample_form': sample_form,}
return render(request,
'results/single_sample_search.html',
self.context)
def post(self, request, *args, **kwargs):
self.sample_form = self.sample_form(request.POST)
if self.sample_form.is_valid():
print('Valid')
else:
print('not valid')
self.context = {
'sample_form': self.sample_form,
}
return render(request,
'results/single_sample_search.html',
self.context)
I don't understand why it is not even calling the clean() method. I have another form which is almost identical which validates. When I do print dir(self.sample_form) after I have passed the request.POST dict it states that validation=unknown. Why is this? How do I check the reason it is not validating?
You need to pass *args and **kwargs when you call super():
def __init__(self, *args, **kwargs):
super(SingleSampleForm, self).__init__(*args, **kwargs)
At the moment, calling __init__ without any *args or **kwargs is equivalent to calling with data=None. The form is unbound, so will never be valid.
class PaymentSelectForm(forms.Form):
date_from = forms.DateField()
date_to = forms.DateField()
website = ModelChoiceField()
paymentmethod = forms.ChoiceField(choices=PAYCODE_CHOICES)
def __init__(self, *args, **kwargs):
super(PaymentSelectForm, self).__init__(*args, **kwargs)
applyClassConfig2FormControl(self)
self.fields['website'].queryset=Website.objects.all()
I have errors: TypeError: __init__() missing 1 required positional argument: 'queryset'. How can I use Queryset in __init__ Form?
Unless there is some information you are currently hiding, you better declare the queryset in the declaration of the ModelChoiceField:
class PaymentSelectForm(forms.Form):
date_from = forms.DateField()
date_to = forms.DateField()
website = ModelChoiceField(queryset=Website.objects.all())
paymentmethod = forms.ChoiceField(choices=PAYCODE_CHOICES)
def __init__(self, *args, **kwargs):
super(PaymentSelectForm, self).__init__(*args, **kwargs)
applyClassConfig2FormControl(self)
In case the queryset is dynamic (this is not the case here), you can set it to None initially, and then overwrite it in the __init__ function:
class PaymentSelectForm(forms.Form):
date_from = forms.DateField()
date_to = forms.DateField()
website = ModelChoiceField(queryset=None)
paymentmethod = forms.ChoiceField(choices=PAYCODE_CHOICES)
def __init__(self, *args, **kwargs):
super(PaymentSelectForm, self).__init__(*args, **kwargs)
applyClassConfig2FormControl(self)
self.fields['website'].queryset=Website.objects.all()
But this is usually the case if for instance the queryset depends on parameters that are passed to the form, or it depends on other tables (and it can not be written into an SQL query elegantly).
Use widget.choices
def __init__(self, *args, **kwargs):
super(PaymentSelectForm, self).__init__(*args, **kwargs)
applyClassConfig2FormControl(self)
self.fields['website'].widget.choices=(
(choice.pk, choice) for choice in Website.objects.all()
)
I'm using django-crispy-forms I want to add an attribute http-prefix to the outputted domain field, for example like this...
<input type="text" name="domain" http-prefix>
How is this possible? I can see crispy-forms has the ability to add css to a field self.helper.field_class, but I cannot see where to add an attribute to a field like my example above just http-prefix.
My Form:
class SchemeForm(NgModelFormMixin, forms.ModelForm):
def __init__(self, *args, **kwargs):
super(SchemeForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-lg-3'
self.helper.field_class = 'col-lg-8'
self.helper.layout = Layout(
'name',
'domain',
'slug',
class Meta:
model = Scheme
fields = ('name', 'domain', 'slug')
Simply update the attribute by setting the value to empty string:
def __init__(self, *args, **kwargs):
super(SchemeForm, self).__init__(*args, **kwargs)
#...
self.fields['domain'].widget.attrs['http-prefix'] = ''