Form is not displaying ValidationError - django

It is not showing any validation error but reloading the empty form till the all form fields behavior validation.
views.py
def Leave_management(request):
if request.user.is_superuser:
form = LeaveForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('leave_list')
else:
form = LeaveForm()
return render(request, 'leave_management.html', {'form': form})
if not request.user.is_superuser and not request.user.is_anonymous:
form = LeaveForm(request.POST or None)
form.fields['status'].disabled = True
if form.is_valid():
form.save()
return redirect('leave_list')
else:
form = LeaveForm()
return render(request, 'leave_management.html', {'form': form})
template
<hr><h1>Leave Application</h1><hr>
<form method="post">
{% csrf_token %}
{{form|crispy}}
<input type="submit" value="submit" >
</form>

The culprit is the fact that you create a new LeaveForm:
def Leave_management(request):
if request.user.is_superuser:
form = LeaveForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('leave_list')
else:
form = LeaveForm()
return render(request, 'leave_management.html', {'form': form})
if not request.user.is_superuser and not request.user.is_anonymous:
form = LeaveForm(request.POST or None)
form.fields['status'].disabled = True
if form.is_valid():
form.save()
return redirect('leave_list')
else:
form = LeaveForm()
return render(request, 'leave_management.html', {'form': form})
So you created a new form that of course does not know anything about the values you have send through it.
But furthermore the request.POST or None pattern is not a good idea either: it will result in the fact that if you have a form that does not per se needs data, then the POST request can never get done properly, since then the form sees a None, and assumes that you construct the form for the first time.
The idea is to feed the request.POST to the form in case this is a post request, like:
def leave_management(request):
if request.method == 'POST':
form = LeaveForm(request.POST)
else:
form = LeaveForm()
if not request.user.is_superuser and not request.user.is_anonymous:
form.fields['status'].disabled = True
if form.is_valid():
form.save()
return redirect('leave_list')
else:
return render(request, 'leave_management.html', {'form': form})
Furthermore we here deduplicate the codepaths. Whether the user is a super user has indeed some impact, but there is no reason to write the remainder of the procedure all in two separate codepaths. We can make an if statement that does the job, and then let the codepaths join again.
Furthemore we thus always construct one form (in the first if statement). Furthermore the name of view functions (like all functions) typically only use lowercase.

Related

Form validation in function views

Is there any difference between the 2 parts of code?
def test(request):
if request.method == 'POST':
form = TestForm(request.POST)
if form.is_valid():
form.save()
title = form.cleaned_data.get('title') #<<--
print(title)
return redirect('blog-home')
else:
form = TestForm()
return render(request, 'blog/test.html', {'form': form})
def test(request):
if request.method == 'POST':
form = TestForm(request.POST)
if form.is_valid():
form.save()
title = request.POST.get('title') # <<--
print(title)
return redirect('blog-home')
else:
form = TestForm()
return render(request, 'blog/test.html', {'form': form})
Since both cases is part of form.is_valid() condition I believe it should be same right?
No, it does not necessary produce same result as cleaned_data documentation states
Each field in a Form class is responsible not only for validating
data, but also for “cleaning” it – normalizing it to a consistent
format. This is a nice feature, because it allows data for a
particular field to be input in a variety of ways, always resulting in
consistent output.

my django registration form doesn´t validate the data

def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid() is True:
form.save()
#log the user in
return redirect('/account')
else:
form = UserCreationForm()
args = {'form': form}
return render(request, 'accounts/reg_form.html', args)
If i try to log in it seems that it doesn't think the data is valid and i don´t know why. It just cleans the registration fields and shows the registrationsite again. I´m using Django 2.1

Saved model is None

So i have a model that i'm trying to save using a form which submits successfully, but in the Admin the object value None. I know the problem is in the views but i can't figure it out. Here's my code:
Views.py
def profilecreate(request):
if request.method == 'GET':
form = ProfileForm()
else:
form = ProfileForm(request.POST)
if form.is_valid():
description = form.cleaned_data['description']
caption= form.cleaned_data['caption']
photo = form.cleaned_data['photo']
profile = Profile.objects.create(description=description, caption=caption, photo=photo)
return HttpResponseRedirect(reverse('profile-id', kwargs={'profile_id': profile.id}))
return render(request, 'profile_form.html', {'form': form})
Someone please assist
Second view attempt
def profilecreate(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = ProfileForm(request.POST)
# check whether it's valid:
if form.is_valid():
photo = form.cleaned_data['photo']
description = form.cleaned_data['description']
caption = form.cleaned_data['caption']
form.save(commit=True)
return HttpResponseRedirect('/')
# if a GET (or any other method) we'll create a blank form
else:
form = ProfileForm()
return render(request, 'profile_form.html', {'form': form})

Setting value of a form field in Django

I'm attempting to modify a field after the user has submitted the form. I've found several pieces of code online, but none seem to work. Below is my attempt in views.py. Any guidance would be greatly appreciated.
def newlisting(request):
if request.method == "POST":
form = ListingsForm(request.POST)
if form.is_valid():
form.cleaned_data['condition'] = 1 #form.condition = 1 also fails
form.save()
return redirect('/listings/')
else:
form = ListingsForm()
return render(request, 'newlisting/newlisting.html', {'form':form})
you can do like:
def newlisting(request):
if request.method == "POST":
form = ListingsForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.condition = 1
obj.save()
return redirect('/listings/')
else:
form = ListingsForm()
return render(request, 'newlisting/newlisting.html', {'form':form})

django modelformset_factory(User) provides two formsets

I have tried to use modelformset_factory(User) to create a form to add (and in next step edit) a user.
I'm confused, why it creates a form with my current user and an empty one for a new one?
Any Idea how i could remove the one with the current?
Here is my view.py code:
#login_required
def update_or_edit_user_profile(request, UserID = None, template_name='userprofile_form.html'):
#check when a userid is provided if its the personal or if the user is allowed to edit the profile
if UserID != None:
if (request.user.has_perm('change_user_profile') or request.user.pk == UserID):
pass
else:
raise PermissionDenied
# when user is allowed to continue:
UserFormSet = modelformset_factory(User)
if request.method == 'POST':
userformset = UserFormSet(request.POST, request.FILES)
if userformset.is_valid():
newUser=userformset.save()
else:
userformset = UserFormSet()
return render_to_response(template_name, {
"userformset": userformset,
})
and my template:
<form action="" method="post">{% csrf_token %}
{{ userformset.as_p }}
<input type="submit" value="Send message" />
</form>
You're confusing forms with formsets. A formset is a collection of forms, so Django is giving you exactly what you asked for. If you only want a single form, then that's what you should use:
class UserForm(forms.ModelForm):
class Meta:
model = User
def update_or_edit_user_profile...
user = User.objects.get(pk=UserID)
if request.method == 'POST':
form = UserForm(request.POST, instance=user)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
form = UserForm(instance=User)
return render(request, template_name, {'form': form})