Inline formset is not validating when fields are empty - django

Inline formset is valid when all the fields are empty but when i fill any one field and submit the formset becomes invalid ?
forms.py
class ContactPersonForm(forms.ModelForm):
phone_number = PhoneNumberField(error_messages={'required': 'Please enter your phone number'}, widget=forms.TextInput(attrs={'placeholder': _('Mobile Number')}))
mobile_number = PhoneNumberField(error_messages={'required': 'Please enter your phone number'}, widget=forms.TextInput(attrs={'placeholder': _('Mobile Number')}))
class Meta:
model = ContactPerson
exclude = ('client',)
widgets = {
'first_name': forms.TextInput(attrs={'placeholder': _('First Name')}),
'last_name': forms.TextInput(attrs={'placeholder': _('Last Name')}),
'email': forms.EmailInput(attrs={'placeholder': _('Email')}),
'phone_number': forms.TextInput(attrs={'placeholder': _('Phone Number')}),
'mobile_number': forms.TextInput(attrs={'placeholder': _('Mobile Number')}),
'skype_name': forms.TextInput(attrs={'placeholder': _('Skype Name / Number')}),
'designation': forms.TextInput(attrs={'placeholder': _('Designation')}),
'department': forms.TextInput(attrs={'placeholder': _('Department')}),
}
ContactPersonFormSet = inlineformset_factory(Client, ContactPerson, form=ContactPersonForm, extra=1)
models.py
class ContactPerson(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE)
salutation = models.CharField(max_length=4, choices=SALUTATIONS)
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
email = models.EmailField()
phone_number = models.CharField(max_length=20)
mobile_number = models.CharField(max_length=20)
skype_name = models.CharField(_('Skype Name / Number'), max_length=128)
designation = models.CharField(max_length=128)
department = models.CharField(max_length=128, null=True)

You may add a custom FormSet by inheriting BaseInlineFormSet and make use of the property has_changed()
class ContactPersonFormSet(forms.BaseInlineFormSet):
def clean(self):
if self.has_changed() == False:
raise forms.ValidationError('Please add at least one contact person.')
and then specify it in your fomset_facotry, like
ContactPersonFormSet = inlineformset_factory(Client, ContactPerson, form=ContactPersonForm, formset=ContactPersonFormSet, extra=1)

Related

TypeError at /dashboard/profiles/create/ path_and_rename() missing 2 required positional arguments: 'instance' and 'filename'

I am trying to save information from the form created out of the Django model. I am really not much experienced as this is my second project.
Here is my view
def profile_create_view(request):
form = ProfileCreateForm(request.POST or None)
if form.is_valid():
form.save
form = ProfileCreateForm()
context = {
'form':form
}
return render(request, 'users/profile', context)
my form is here
class ProfileCreateForm(forms.ModelForm):
class Meta:
model = Profile
fields = [
'avatar',
'user_type',
'first_name',
'last_name',
'gender',
'email',
'phonenumber',
'birth_date',]
and then my model is here
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to = '', default = path_and_rename, blank=True)
provider = 'provider'
requester = 'requester'
user_types = [
(provider, 'provider'),
(requester, 'requester'),
]
user_type = models.CharField(max_length=155, choices=user_types, default=requester)
first_name = models.CharField(max_length=255, default='')
last_name = models.CharField(max_length=255, default='')
GENDER_MALE = 'Male'
GENDER_FEMALE = 'Female'
OTHER = 'Other'
GENDER_CHOICES = [
(GENDER_MALE, 'Male'),
(GENDER_FEMALE, 'Female'),
(OTHER, 'Other'),
]
gender = models.CharField(max_length=15, choices=GENDER_CHOICES, blank=True)
email = models.EmailField(default='none#email.com')
phonenumber = models.CharField(max_length=15, default='')
birth_date = models.DateField(default='1975-12-12')
Strange things happen in the view function, you have to rebuild it like this.
def profile_create_view(request):
if request.method == "POST":
form = ProfileCreateForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return redirect('/')
else:
form = form(instance=request.user)
return render(request, 'manage_authors.html', {'form': form})
sorry, I had forgotten I solved it by changing the model on avatar from
'avatar = models.ImageField(upload_to = '', default = path_and_rename, blank=True)'
to
avatar = models.ImageField(upload_to = 'uploads/', default='uploads/default.jpg')

attribute error in django. django.db.models has no attribute

I am trying to write the code so that a user in the system can view complaint registered by others on this page but not their own complaints. This is the code, but I don't understand what's wrong:
views.py:
class OtherPeoplesComplaints(TemplateView):
model = Complaint
form_class = ComplaintForm
template_name = 'userComplaints.html'
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context["complaints"] = models.Complaint.objects.exclude(
profile__user = self.request.user
)
models.py:
class Complaint(models.Model):
user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True)
id = models.AutoField(blank=False, primary_key=True)
reportnumber = models.CharField(max_length=500 ,null = True, blank= False)
eventdate = models.DateField(null=True, blank=False)
event_type = models.CharField(max_length=300, null=True, blank=True)
device_problem = models.CharField(max_length=300, null=True, blank=True)
manufacturer = models.CharField(max_length=300, null=True, blank=True)
product_code = models.CharField(max_length=300, null=True, blank=True)
brand_name = models.CharField(max_length = 300, null=True, blank=True)
exemption = models.CharField(max_length=300, null=True, blank=True)
patient_problem = models.CharField(max_length=500, null=True, blank=True)
event_text = models.TextField(null=True, blank= True)
document = models.FileField(upload_to='static/documents', blank=True, null=True)
def __str__(self):
return self.reportnumber
forms.py:
class DateInput(forms.DateInput):
input_type = 'date'
class ComplaintForm(ModelForm):
class Meta:
model = Complaint
fields = '__all__'
widgets = {
'reportnumber': forms.TextInput(attrs={'placeholder': 'Report number'}),
'event_type': forms.TextInput(attrs={'placeholder': 'Event type'}),
'eventdate': DateInput(),
'device_problem': forms.TextInput(attrs={'placeholder': 'Device Problem'}),
'event_text': forms.Textarea(attrs={'style': 'height: 130px;width:760px'}),
'manufacturer': forms.TextInput(attrs={'placeholder': 'Enter Manufacturer Name'}),
'product_code': forms.TextInput(attrs={'placeholder': 'Enter Product Code'}),
'brand_name': forms.TextInput(attrs={'placeholder': 'Enter Brand Name'}),
'exemption': forms.TextInput(attrs={'placeholder': 'Enter Exemption'}),
'patient_problem': forms.TextInput(attrs={'placeholder': 'Enter Patient Problem'}),
}
def clean(self):
cleaned_data = super(ComplaintForm, self).clean()
reportnumber = cleaned_data.get('reportnumber')
event_text = cleaned_data.get('event_text')
if not reportnumber and not event_text:
raise forms.ValidationError('You have to write something!')
return cleaned_data
In this view
class OtherPeoplesComplaints(TemplateView):
model = Complaint
form_class = ComplaintForm
template_name = 'userComplaints.html'
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context["complaints"] = models.Complaint.objects.exclude(
profile__user = self.request.user
)
you are using this query :
context["complaints"] = models.Complaint.objects.exclude(profile__user = self.request.user)
change it to :
context["complaints"] = self.model.objects.exclude(user = self.request.user)
Explanation :
Your model is Complaint which you can access using self.model as you have defined the class variable here :
class OtherPeoplesComplaints(TemplateView):
model = Complaint
and
You want to access complaint of other users except your own, so this update in your query :
exclude(user = self.request.user)

RelatedObjectDoesNotExist at /updateprofile User has no profile

i have one model userprofile which is connected to User by onetoone relationship. i am trying to create combined form for both user and userprofile form but it is showing onetoonedescripter has no attribute _meta.
views.py
'''
def UpdateProfile(request):
if request.method =='POST':
EUF_form = EditUserForm(request.POST, instance=request.user )
EPF_form = EditProfileForm(request.POST, instance=request.user.Profile )
if EUF_form.is_valid() and EPF_form.i_valid():
EUF_form.save()
EPF_form.save()
return HttpResponse("Profile updated succesfully.")
return render(request, 'profile_page.html')
else:
EUF_form = EditUserForm(instance=request.user)
EPF_form = EditProfileForm(instance=request.user.profile)
return render(request, 'edit_profile.html', {'EUF_form':EUF_form, 'EPF_form':EPF_form})
'''
models.py
'''
class Profile(models.Model):
user = models.OneToOneField(User, on_delete= models.CASCADE)
mobile = models.CharField(max_length=20, blank=True)
bio = models.CharField(max_length=300, default='')
avatar = models.ImageField(upload_to='avatars', blank=True)
birthday = models.DateField(blank=True, default='1990-12-01')
website = models.CharField(blank=True, max_length=256)
gender = models.CharField(blank=True, max_length=20, choices=[('M','Male'), ('F','Female'),('O','Other')])
def __str__(self):
return self.user.username
'''
forms.py
'''
class EditUserForm(ModelForm):
first_name = forms.CharField(widget=forms.TextInput(
attrs={'class': 'form-control','type':'text','name': 'first_name'}),
label="First Name")
last_name = forms.CharField(widget=forms.TextInput(
attrs={'class': 'form-control','type':'text','name': 'last_name'}),
label="Last Name")
username = forms.CharField(widget=forms.TextInput(
attrs={'class': 'form-control','type':'text','name': 'username'}),
label="Username")
email = forms.EmailField(widget=forms.TextInput(
attrs={'class': 'form-control','type':'text','name': 'email'}),
label="Email")
class Meta:
model = User
fields = ['first_name','last_name','username','email']
class EditProfileForm(ModelForm):
mobile = forms.CharField(widget=forms.TextInput(
attrs={'class': 'form-control','type':'tel','name': 'mobile'}),
label="Phone number")
bio = forms.CharField(widget=forms.Textarea,
label="Bio")
birthday = forms.DateField(widget=forms.DateInput(
attrs={'class': 'form-control','type':'date','name': 'birthday'}),
label="Username")
website = forms.URLField(widget=forms.URLInput(
attrs={'class': 'form-control','type':'url','name': 'website'}),
label="website")
gender = forms.ChoiceField(choices=[('M','Male'), ('F','Female'),('O','Other')],
widget=forms.Select ,
label="gender")
class Meta:
model = Profile
fields = ['mobile','bio','birthday','website','gender']
'''

If Else in Djnago Views

I'm making a LMS.
Where a User applies for a leave and the admin accepts or rejects it.
Right now I am stuck in a problem where I want the user to apply for a leave through the Django form by selecting a leave type (casual, sick, half pay etc), if the admin accepts it then the default values in the database changes or gets deducted from the Employee model and when the counter reaches 0 an error is generated that you don't have any leaves,contact the admin.
I'm unable to understand how to make the logic for it.
I tried Applying if else statement in the views and even in the models.
views.py
The function name is "Reject" as I am trying to make changes to the accept function.
def reject_leave(request, id):
# employee_item = Employee.objects.get(id=id)
all_item = Leave.objects.get(id=id)
all = Employee.objects.get(id=id)
context = {'all': all,'all_item': all_item}
'''
if the leave_type (choice field of the leaves from the django form) equals to a leave type like Annual leave
The the program deducts 1 or the amount entered from the total value of Annual leave from the Model Employee
'''
*Sorry for the poor writing I'm not experienced in Django*
***This code is saying that in an illogical way.***
if leave_type.id is "Annual_leave":
Annual_leave - 1
else:
subject = "Leave Rejected" # email subject
email_from = "settings.EMAIL_HOST_USER" # email from
to_email = ['someemail#something.com'] # email to
with open(...) as f:
msgbody = f.read()
msg = EmailMultiAlternatives(
subject=subject, body=msgbody, from_email=email_from, to=to_email)
html_template = get_template(...).render()
msg.attach_alternative(html_template, "text/html")
msg.send()
return render(request, 'projectfiles/rejectemail.html',context)
forms.py
class Leave_Form(forms.ModelForm):
to_date = forms.DateField(
widget=forms.DateInput(format=('%m/%d/%y'),
attrs={'class': 'form-control',
'placeholder': ' Month/Date/Year'}))
from_date = forms.DateField(
widget=forms.DateInput(format=('%m/%d/%y'),
attrs={'class': 'form-control',
'placeholder':' Month/Date/Year'}))
class Meta:
model = Leave
fields = ['leave_Type', 'description',
'from_date', 'to_date', 'leave_qty']
exclude = ['employee_leaves', 'submit_date']
leave_type_choice = (
("Annual_leave", "Annual leave"),
("Sick_leave", "Sick leave"),
("Casual_leave", "Casual leave"),
("Emergency_leave", "Emergency leave"),
("Half_pay","Half Pay")
)
widgets = {
'leave_Type': forms.Select(choices = leave_type_choice, attrs={'class': 'form-control'}),
'description': forms.Textarea(
attrs={'class': 'form-control','placeholder': 'Enter description here', 'rows': 3, 'cols': 21})}
models.py
class Employee(models.Model):
employee_name = models.OneToOneField(User, on_delete = models.CASCADE)
employee_designation = models.CharField(max_length = 20)
employee_department = models.CharField(max_length = 35)
Annual_leave = models.PositiveSmallIntegerField(default=10)
Sick_leave = models.PositiveSmallIntegerField(default=3)
Casual_leave = models.PositiveSmallIntegerField(default=3)
Half_pay = models.PositiveSmallIntegerField(default=4)
Emergency_leave = models.PositiveSmallIntegerField(default=3)
allowed = models.BooleanField(default=False)
def __str__(self):
return self.employee_name.username
class Meta:
verbose_name_plural = "Employee"
class Leave(models.Model):
employee_leaves = models.ForeignKey(Employee, on_delete=models.CASCADE)
leave_Type = models.CharField(max_length=25)
leave_qty = models.PositiveSmallIntegerField(default=0)
description = models.CharField(max_length=75, blank=True, null=True)
submit_date = models.DateTimeField(auto_now_add=True)
from_date = models.DateField(auto_now=False, auto_now_add=False)
to_date = models.DateField(auto_now=False, auto_now_add=False)
class Meta:
verbose_name_plural = "Leave"
def __str__(self):
return self.leave_Type + " by " + str(self.employee_leaves)
When the Admin accepts (or in this case rejects) a leave.
e.g.
Sick leave I want 1 or entered amount of leaves to be deducted from the total of the allocated sick leaves.
def reject_leave(request, id): # overwriting built-in id is not a good idea
all_item = Leave.objects.get(id=id) # This is a single item, not all items
all = Employee.objects.get(id=id) # this again is a single item, not all items
context = {'all': all, 'all_item': all_item}
if leave_type.id is "Annual_leave":
# What is leave_type?
Annual_leave - 1
# What is Annual_leave? What does -1 supposed to do?
# Maybe you meant
# employee = Employee.objects.get(id=id)
# leave = employee.employee_leaves_set.last()
# if leave.leave_Type == 'Annual_leave':
# employee.Annual_leave -= 1
# employee.save()
else:
subject = "Leave Rejected"
email_from = "settings.EMAIL_HOST_USER"
to_email = ['talhamurtaza#clickmail.info']
with open('...') as f:
msgbody = f.read()
msg = EmailMultiAlternatives(
subject=subject, body=msgbody, from_email=email_from, to=to_email)
html_template = get_template(
"...").render()
msg.attach_alternative(html_template, "text/html")
msg.send()
return render(request, 'projectfiles/rejectemail.html', context)
There is so many things wrong with this that I can confidently say you haven't taken a python tutorial, read pep-8 nor taken a django tutorial. So please start from the first one and work your way up.

TypeError an invalid keyword argument for this function

I am new to Python trying to make forms field and have a problem.
My forms shows correctly at html but when I am trying to submit data and save it to a database, but I have an error:
TypeError at /srdb/
'send_date' is an invalid keyword argument for this function
Here is my code:
models.py
class Srdb(models.Model):
send_date = models.DateField()
send_weight = models.IntegerField(default=0, validators=[MaxValueValidator(10000), MinValueValidator(100)])
track_code = models.CharField(default=None, blank=False, max_length=20)
send_index = models.IntegerField(default=None, blank=False,
validators=[MaxValueValidator(999999), MinValueValidator(100000)])
sender_fullname = models.CharField(default=None, blank=False, max_length=150)
sender_dob = models.DateField()
sender_adress = models.CharField(default=None, blank=False, max_length=400)
receiver_index = models.IntegerField(default=None, blank=False,
validators=[MaxValueValidator(999999), MinValueValidator(100000)])
receiver_fullname = models.CharField(default=None, blank=False, max_length=150)
receiver_adress = models.CharField(default=None, blank=False, max_length=400)
sender = models.ForeignKey(Dostavshik, on_delete=models.CASCADE, default=None, blank=False)
def __str__(self):
return str(self.id)
forms.py
class SrdbForm(forms.Form):
send_date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), label='Дата Отправки')
send_weight = forms.IntegerField(initial=0, validators=[MaxValueValidator(10000), MinValueValidator(100)],
label='Отправленный Вес (граммы)')
track_code = forms.CharField(max_length=20,
widget=forms.TextInput(attrs={'placeholder': 'Код Отслеживания Посылки'}),
label='Трек Код')
send_index = forms.IntegerField(validators=[MaxValueValidator(999999), MinValueValidator(100000)],
widget=forms.TextInput(attrs={'placeholder': 'Индекс Почты Отправления'}),
label='Индекc Отправления')
sender_fullname = forms.CharField(max_length=150,
widget=forms.TextInput(attrs={'placeholder': 'Отправитель'}),
label='ФИО отправителя')
sender_dob = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), label='Дата Рождения Отправителя')
sender_adress = forms.CharField(max_length=200,
widget=forms.TextInput(attrs={'placeholder': 'Полный Адрес Отправителя'}),
label='Адрес отправителя')
# Получатель
receiver_index = forms.IntegerField(validators=[MaxValueValidator(999999), MinValueValidator(100000)],
widget=forms.TextInput(attrs={'placeholder': 'Индекс Почты Получения'}),
label='Индекс Получателя')
receiver_fullname = forms.CharField(max_length=100,
widget=forms.TextInput(attrs={'placeholder': 'Получатель'}),
label='ФИО Получателя')
receiver_adress = forms.CharField(max_length=200,
widget=forms.TextInput(attrs={'placeholder': 'Полный Адрес Получателя'}),
label='Адрес Проживания Получателя')
sender = forms.ModelChoiceField(queryset=Dostavshik.objects.all(),
label='Отправил Доставщик')
views.py
def srdb(request):
form_srdb = SrdbForm()
if request.method == 'POST':
form_srdb = SrdbForm(request.POST)
if form_srdb.is_valid():
Srdb.objects.create(**form_srdb.cleaned_data)
messages.success(request, 'Данные Успешно Сохранены')
context = {
'form_srdb': form_srdb
}
template = 'srdb.html'
return render(request, template, context)
After submit always have this error:
TypeError at /srdb/
'send_date' is an invalid keyword argument for this function