How to check if one field matches another in Django Form - django

I'm trying to have my form check if the email field matches the verify_email field in my Django form but it is not working.
My forms.py file:
class SignupForm(ModelForm):
class Meta:
model = FormSubmission
fields ='__all__'
widgets = {'botcatcher': forms.HiddenInput()}
def clean(self):
cleaned_data = super().clean()
email = self.cleaned_data.get('email')
vmail = self.cleaned_data.get('verify_email')
if email != vmail:
raise forms.ValidationError(_("Emails must
match"), code="invalid")
return cleaned_data
My model.py file:
class FormSubmission(models.Model):
first_name = models.CharField(max_length = 30)
last_name = models.CharField(max_length = 30)
email = models.EmailField(unique= False)
verify_email = models.EmailField(unique = False)
text = models.CharField(max_length=250)
botcatcher = models.CharField(max_length= 1, blank=True,
validators=[validators.MaxLengthValidator(0)])
def __str__(self):
return "%s %s"% (self.first_name, self.last_name)

It was my indentation for the def clean function.

Related

django form commit=false after how to save many to many field data

Model.py
class Branch(models.Model): # Branch Master
status_type = (
("a",'Active'),
("d",'Deactive'),
)
name = models.CharField(max_length=100, unique=True)
suffix = models.CharField(max_length=8, unique=True)
Remark = models.CharField(max_length=200, null=True, blank=True)
created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=1, choices = status_type, default = 'a')
def __str__(self):
return self.name
class Vendor(models.Model):
status_type = (
("a",'Active'),
("d",'Deactive'),
)
branch = models.ManyToManyField(Branch)
company = models.CharField(max_length=200)
name = models.CharField(max_length=200)
phone = models.CharField(max_length=11, unique = True)
email = models.EmailField(max_length=254, unique = True)
gst = models.CharField(max_length=15, unique = True)
pan_no = models.CharField(max_length=10, unique = True)
add_1 = models.CharField(max_length=50, null=True, blank = True)
add_2 = models.CharField(max_length=50, null=True, blank = True)
add_3 = models.CharField(max_length=50, null=True, blank = True)
Remark = models.CharField(max_length=200, null=True, blank=True)
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=1, choices = status_type, default = 'a')
def __str__(self):
return self.company
form.py
i want save like created_by field
class VendorForm(ModelForm):
class Meta:
model = Vendor
fields = 'all'
exclude = ['created_by', 'branch']
widgets = {
'company':forms.TextInput(attrs={'class':'form-control'}),
'name':forms.TextInput(attrs={'class':'form-control'}),
'phone':forms.TextInput(attrs={'class':'form-control'}),
'email':forms.EmailInput(attrs={'class':'form-control'}),
'gst':forms.TextInput(attrs={'class':'form-control'}),
'pan_no':forms.TextInput(attrs={'class':'form-control'}),
'add_1':forms.TextInput(attrs={'class':'form-control'}),
'add_2':forms.TextInput(attrs={'class':'form-control'}),
'add_3':forms.TextInput(attrs={'class':'form-control'}),
'Remark':forms.Textarea(attrs={'class':'form-control','rows':'2'}),
'status':forms.Select(attrs={'class':'form-control'}),
}
Views.py
I have pass branch in session.
I want to save with branch which is many to many field
def Add_Vendor(request): # for vendor add
msg = ""
msg_type = ""
branch_id = request.session['branch_id']
branch_data = Branch.objects.get(id = branch_id)
form = ""
if request.method == "POST":
try:
form = VendorForm(request.POST)
if form.is_valid:
vendor_add = form.save(commit=False)
vendor_add.created_by = request.user
vendor_add.instance.branch = branch_data.id
vendor_add.save()
form.save_m2m() # for m to m field save
msg_type = "success"
msg = "Vendor Added."
form = VendorForm(initial={'branch':branch_id})
except:
msg_type = "error"
msg = str(form.errors)
print(msg)
else:
form = VendorForm(initial={'branch':branch_id})
context = {
'form':form,
'branch_data':branch_data,
'msg_type':msg_type,
'msg':msg,
'btn_type':'fa fa-regular fa-plus',
'form_title':'Vendor Form',
'tree_main_title':'Vendor',
'v_url':'vendor_page',
'tree_title':'Add Form',
}
return render(request, 'base/vendor_master/form_vendor.html',context)
I would advise not to work with commit=False in the first place:
def Add_Vendor(request): # for vendor add
branch_id = request.session['branch_id']
branch_data = get_object_or_404(Branch, pk=branch_id)
if request.method == 'POST':
form = VendorForm(request.POST, request.FILES)
if form.is_valid():
form.instance.created_by = request.user
form.instance.branch = branch_data.id
vendor_add = form.save()
vendor_add.branch.add(branch_data)
return redirect('name-of-some-view')
else:
form = VendorForm()
context = {
'form': form,
'branch_data': branch_data,
'btn_type': 'fa fa-regular fa-plus',
'form_title': 'Vendor Form',
'tree_main_title': 'Vendor',
'v_url': 'vendor_page',
'tree_title': 'Add Form',
}
return render(request, 'base/vendor_master/form_vendor.html', context)
You can simplify your form by automatically adding form-control to each widget:
class VendorForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
attrs = field.widget.attrs
attrs['class'] = attrs.get('class', '') + ' form-control'
class Meta:
model = Vendor
exclude = ['created_by', 'branch']
Note: In case of a successful POST request, you should make a redirect
[Django-doc]
to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.
Note: You can set a field editable=False [Django-doc]. Then the field does not show up in the ModelForms and ModelAdmins by default. In this case for example with created_by.
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.
Note: Please do not pass messages manually to the template. Django has the messages framework [Django-doc], which allows to add messages to the request, which will then be delivered the next time a template renders these messages. This makes delivering multiple messages convenient, as well as setting different log levels to the messages.

How can i create custom validation in django model forms

I want to create a custom form validation in Django forms. I am able to do it normal Django forms but unable to do it in model forms.
my Django form code is
class Post_Article(forms.Form):
title = forms.CharField(label = 'Title',max_length = 100)
abstract = forms.CharField(widget = forms.Textarea, max_length = 300)
body = forms.CharField(widget = forms.Textarea)
image = forms.ImageField(required = False)
hash_tags = forms.CharField(max_length = 50,required = False)
def no_of_hash_tags(self):
cleaned_data = super().no_of_hash_tags()
tags = cleaned_data.get('hash_tags')
if tags:
tags = split(str(tags))
if len(tags) > 5:
raise forms.ValiadationError('Maximum 5 tags are allowed')
the Django model is
class PostsArticle(models.Model):
title = models.CharField(max_length=255)
pub_date = models.DateTimeField(default= timezone.now)
abstract = models.TextField()
body = models.TextField()
image = models.ImageField(upload_to=('images/'),blank=True)
user = models.ForeignKey(User , on_delete = models.CASCADE)
hash_tags = models.CharField(max_length = 50,blank= True)
def _str_(self):
return self.title
def get_absolute_url(self):
return reverse('home')
def summary(self):
return self.absract[:200]
def pub_date_pretty(self):
return self.pub_date.strftime('%b %e %Y')
def link_tags(self):
cleaned_data = super().link_tags
tags = cleaned_data.get['hash_tags']
for tag in tags:
hashing(tag,"PostsArticle")
After some discussion on stack overflow I updates my Django forms to
class Post_Article(forms.ModelForm):
title = forms.CharField(label = 'Title',max_length = 100)
abstract = forms.CharField(widget = forms.Textarea, max_length = 300)
body = forms.CharField(widget = forms.Textarea)
image = forms.ImageField(required = False)
hash_tags = forms.CharField(max_length = 50,required = False)
class Meta:
model = PostsArticle
fields=("title", "abstract", "body", "image", "hash_tags")
def clean(self)
:
cleaned_data=super(Post_Article, self).clean()
tags = cleaned_data.get("hash_tags")
if tags:
tags = split(str(tags))
if len(tags) > 5:
raise forms.ValidationError('Maximum 5 tags are allowed')
return cleaned_data
Now I am unable to get how can I use it with my current class used in views.py
class FeedUpdateView(LoginRequiredMixin, UserPassesTestMixin , UpdateView):
model = FeedPosts
fields= ['body', 'image']
template_name= 'post/edit_Feed.html'
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
Posts = self.get_object()
if self.request.user == Posts.user:
return True
return False
I want to use my Django forms code instead of creating view from my model directly. I want to do it because I want to have some custom validation of a field as given in my forms code
kindly help how can I add form validation to my model
Cleaning a specific field attribute, you would have to call clean_<field_name>.
class Post_ArticleForm(ModelForm):
class Meta:
model = PostsArticle
fields = ['abstract', 'title', 'body', 'image', 'hash_tags']
def clean_hash_tags(self):
cleaned_data = super().clean_hash_tags()
tags = self.cleaned_data.get('hash_tags')
if tags:
tags = split(str(tags))
if len(tags) > 5:
raise forms.ValiadationError('Maximum 5 tags are allowed')
return cleaned_data
You need to override clean method for your ModelForm.
Example:
class Post_Article(forms.ModelForm):
...
hash_tags = forms.CharField(max_length = 50,required = False)
...
class Meta:
model = PostsArticle
fields=("title", "abstract", "body", "image", "hash_tags",)
def clean(self):
cleaned_data=super(Post_Article, self).clean()
tags = cleaned_data.get("hash_tags")
if tags:
tags = split(str(tags))
if len(tags) > 5:
raise forms.ValidationError('Maximum 5 tags are allowed')
return cleaned_data
the clean funtion is not getting invoked
Django forms is
class Post_Article(forms.ModelForm):
title = forms.CharField(label = 'Title',max_length = 100)
abstract = forms.CharField(widget = forms.Textarea, max_length = 300)
body = forms.CharField(widget = forms.Textarea)
image = forms.ImageField(required = False)
hash_tags = forms.CharField(max_length = 50,required = False)
class Meta:
model = PostsArticle
fields=("title", "abstract", "body", "image", "hash_tags")
def clean(self):
print(hello)
cleaned_data=super(Post_Article, self).clean()
tags = cleaned_data.get("hash_tags")
if tags:
tags = split(str(tags))
if len(tags) > 5:
raise forms.ValidationError('Maximum 5 tags are allowed')
return cleaned_data
the clean funtion is not getting invoked
the formview for the same is
class PostCreateView(LoginRequiredMixin,FormView):
form_class = Post_Article
template_name= 'post/post.html'
success_url = '/'
def form_valid(self, form):
form.instance.user = self.request.user
print(form.instance.user)
return super().form_valid(form)
the formview is in the views.py

django clean_data.get is None

I want to make some fields of thwe form required based on the "is_seller" dropdown list . but seller = cleaned_data.get("is_seller") returns None !
these are my codes :
models.py
class UserProfileInfo(models.Model):
user=models.OneToOneField(User,related_name='profile')
companyname=models.CharField(blank=True,null=True, ],max_length=128,verbose_name=_('companyname'))
phone_regex = RegexValidator(regex=r'^\d{11,11}$', message=_(u"Phone number must be 11 digit."))
cellphone = models.CharField(validators=[phone_regex], max_length=17,verbose_name=_('cellphone'))
tel = models.CharField(blank=True,null=True,validators=[phone_regex], max_length=17,verbose_name=_('tel'))
state=models.CharField( max_length=128,verbose_name=_('state'))
city=models.CharField( max_length=128,verbose_name=_('city'))
address=models.CharField(blank=True,null=True, max_length=264,verbose_name=_('address'))
is_seller=models.CharField(blank=True,null=True, max_length=2,verbose_name=_('seller'))
def __str__ (self):
return self.user.username
class Meta:
verbose_name=_('UserProfileInfo')
verbose_name_plural=_('UserProfileInfos')
forms.py :
class UserProfileInfoForm(forms.ModelForm):
CHOICES = (('0','buyer'),
('1','seller'),
('2','both'))
is_seller = forms.CharField(widget=forms.Select(choices=CHOICES),label=_('title'))
companyname=forms.CharField(required=False,widget=forms.TextInput(attrs={'class':'form-control' ,'style': 'width:60%', 'white-space':'nowrap'}),label=_('companyname'))
cellphone = forms.CharField( widget=forms.TextInput(attrs={'class':'form-control' ,'style': 'width:60%'}),label=_('cellphone'))
tel = forms.CharField( widget=forms.TextInput(attrs={'class':'form-control' ,'style': 'width:60%'}),label=_('tel'))
state=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control' ,'style': 'width:60%'}),label=_('state'))
city=forms.CharField( widget=forms.TextInput(attrs={'class':'form-control' ,'style': 'width:60%'}),label=_('city'))
address=forms.CharField(required=False, widget=forms.TextInput(attrs={'class':'form-control' ,'style': 'width:100%'}),label=_('address'))
class Meta():
model=UserProfileInfo
fields=('companyname','tel','cellphone','state','city','address','is_seller')
def clean_companyname(self):
cleaned_data = super(UserProfileInfoForm, self).clean()
seller = cleaned_data.get("is_seller")
print(">>>>>>>>>>>>>>>>>>"+ str(seller))
companyname = self.cleaned_data.get('companyname')
if seller!=0 and companyname=="":
raise forms.ValidationError(u"Required.")
return cleaned_data
This should be in the general clean() method, not clean_companyname().

how to store modelform data to database

I have searched 20-30 posts and I did not find anything useful. I am to store data to database by selecting values from HTML file or form in view. Please tell me how I can achieve this. what code I am missing. Thanks in advance for Help.
view.py
def blog_list(request):
form = AttendanceForm()
if request.method == "POST":
form1 = AttendanceForm(request.POST)
if form1.is_valid:
form1.save()
return render(request, 'blog/blog_list.html',{
'form1':form1,
})
return render(request, 'blog/blog_list.html',{
'form':form,
})
my forms.py
class AttendanceForm(forms.ModelForm):
action = forms.ModelChoiceField(queryset=Action.objects.all(), empty_label="-----------", required=True)
employee = forms.ModelChoiceField(queryset=Employee.objects.all(), empty_label="-----------", required=True)
class Meta:
model = Action
fields = ['employee','action']
my model.py
class Action(models.Model):
action_name = models.CharField(max_length = 100)
def __str__(self):
return self.action_name
class Employee(models.Model):
employee_id = models.AutoField(primary_key = True)
employee_name = models.CharField(max_length = 100)
def __str__(self):
return self.employee_name
class Attendance(models.Model):
u = models.ForeignKey(Employee)
action = models.ForeignKey(Action)
action_time = models.DateTimeField(default=timezone.now())
In Python you need to call methods by using parentheses.
if form.is_valid():
form.save()
It is working fine after these changes in Model:
class Action(models.Model):
action_name = models.CharField(max_length = 100)
def __str__(self):
return self.action_name
class Employee(models.Model):
employee_id = models.AutoField(primary_key = True)
employee_name = models.CharField(max_length = 100)
def __str__(self):
return self.employee_name
class Attendance(models.Model):
employee = models.ForeignKey(Employee)
action = models.ForeignKey(Action)
action_time = models.DateTimeField(default=timezone.now())

Two Django models with foreign keys in one view

I'm starting with Django. I have 3 models, a parent class "Cliente" and two child classes, "Persona" and "Empresa".
models.py
class Cliente(models.Model):
idcliente = models.AutoField(unique=True, primary_key=True)
direccion = models.CharField(max_length=45L, blank=True)
telefono = models.CharField(max_length=45L, blank=True)
email = models.CharField(max_length=45L, blank=True)
def __unicode__(self):
return u'Id: %s' % (self.idcliente)
class Meta:
db_table = 'cliente'
class Empresa(models.Model):
idcliente = models.ForeignKey('Cliente', db_column='idcliente', primary_key=True)
cuit = models.CharField(max_length=45L)
nombre = models.CharField(max_length=60L)
numero_ingresos_brutos = models.CharField(max_length=45L, blank=True)
razon_social = models.CharField(max_length=45L, blank=True)
def __unicode__(self):
return u'CUIT: %s - Nombre: %s' % (self.cuit, self.nombre)
class Meta:
db_table = 'empresa'
class Persona(models.Model):
idcliente = models.ForeignKey('Cliente', db_column='idcliente', primary_key=True)
representante_de = models.ForeignKey('Empresa', null=True, db_column='representante_de', blank=True, related_name='representa_a')
nombre = models.CharField(max_length=45L)
apellido = models.CharField(max_length=45L)
def __unicode__(self):
return u'Id: %s - Nombre completo: %s %s' % (self.idcliente, self.nombre, self.apellido)
class Meta:
db_table = 'persona'
I want to manage a class and its parent in the same view. I want to add, edit and delete "Cliente" and "Persona"/"Cliente" in the same form. Can you help me?
There is a good example in the Documentation Here.
I wrote this based on the documentation, so it is untested.
def manage_books(request, client_id):
client = Cliente.objects.get(pk=client_id)
EmpresaInlineFormSet = inlineformset_factory(Cliente, Empresa)
if request.method == "POST":
formset = EmpresaInlineFormSet(request.POST, request.FILES, instance=author)
if formset.is_valid():
formset.save()
# Do something. Should generally end with a redirect. For example:
return HttpResponseRedirect(client.get_absolute_url())
else:
formset = EmpresaInlineFormSet(instance=client)
return render_to_response("manage_empresa.html", {
"formset": formset,
})