I have a profile updation form , i have passed the data and instance to the form but the validation fails The scenarios are as follows .
This form is for profile updation , but the validation fails without showing any errors.
class ProfileEditForm(forms.ModelForm):
class Meta:
model = Profile
def clean(self):
return self.cleaned_data
the view is as follows
> The form.is_valid always returns False.
def user_profile(request, params={}):
if request.user.is_staff==False:
profile = Profile.objects.get(user=request.user)
if request.method == 'POST':
profile_form = ProfileEditForm(request.POST, instance=profile)
print profile_form.is_bound
print profile_form.is_valid()
if profile_form.is_valid():
profile = profile_form.save()
else:
pass
else:
profile_form = ProfileEditForm( instance=profile)
profile_form = ProfileEditForm( instance=profile)
params['profile_form'] = profile_form
return render_to_response('vec/profile.html', params, context_instance=RequestContext(request))
else:
return render(request, 'base.html')
The following are the outputs :
print profile_form.is_bound - returns True and
print profile_form.is_valid() returns False .Also no erros in {{ profile_form.errors }} {{ profile_form.non_field_errors }}
Appreciate your reply...
Thanks in advance ...
You are resetting profile_form before sending it to template, due to which no errors are shown.
See comments below
def user_profile(request, params={}):
if request.user.is_staff==False:
profile = Profile.objects.get(user=request.user)
if request.method == 'POST':
profile_form = ProfileEditForm(request.POST, instance=profile)
print profile_form.is_bound
print profile_form.is_valid()
if profile_form.is_valid():
profile = profile_form.save()
else:
pass
else:
profile_form = ProfileEditForm( instance=profile)
# don't do this, you already have profile_form
#profile_form = ProfileEditForm( instance=profile)
params['profile_form'] = profile_form
return render_to_response('vec/profile.html', params, context_instance=RequestContext(request))
else:
return render(request, 'base.html')
I figured out ...
I just included the fields in the form definition
fields = ('','',)
Thanks.
Related
here's my code
i can't update my data if i used type "file"
My form can't be updated, I try print(form.error) but "this field requirement" appears, even though the form is filled out
views.py :
#login_required
def data_karyawan_edit(request, id):
karyawan = Karyawan.objects.get(id=id)
ar_divisi = Divisi.objects.all()
if request.method == 'POST':
form = KaryawanForm(request.POST, request.FILES, instance=karyawan)
print(form.errors)
if form.is_valid():
form.save()
messages.success(request, "Berhasil disimpan")
return redirect('data_karyawan')
else:
form = KaryawanForm()
return render(request, "data_karyawan/edit.html", {'karyawan': karyawan, 'ar_divisi': ar_divisi})
basically, i'm trying to form.as_p to list the values but its not working. Its not really that its not working, but it only works (it only appears in my template) after i press submit. I believe I have placed the context in the wrong place or the wrong indentation but im not sure where i should shift context['form'] = form to. I tried to shift it but it says that lcoal variable referenced before assignment. Could someone advise?
The reason why I put it below else is because i want to display the errors if there are errors
def create_blog_view(request):
context = {}
user = request.user
if request.method == 'POST':
form = CreateBlogPostForm(request.POST or None, request.FILES or None)
if form.is_valid():
obj= form.save(commit = False)
author = Account.objects.filter(email=user.email).first()
obj.author = author
obj.save()
return redirect('HomeFeed:main')
else:
context['form'] = form
return render(request, "HomeFeed/create_blog.html", context)
def create_blog_view(request):
context = {}
user = request.user
form = CreateBlogPostForm()
if request.method == 'POST':
form = CreateBlogPostForm(request.POST or None, request.FILES or None)
if form.is_valid():
obj= form.save(commit = False)
author = Account.objects.filter(email=user.email).first()
obj.author = author
obj.save()
return redirect('HomeFeed:main')
else:
context['form'] = form
context['form'] = form
return render(request, "HomeFeed/create_blog.html", context)
Before your if statement, you need to add:
form = CreateBlogPostForm()
context['form'] = form
This will initialise a blank form and add it to your context.
Currently, you are only adding 'form' to your context, if the form has been submitted (/ a POST request has been sent to the view) and the form has validation errors.
To avoid repeated code, better still would be something like this:
def create_blog_view(request):
user = request.user
form = CreateBlogPostForm()
if request.method == 'POST':
form = CreateBlogPostForm(request.POST, request.FILES)
if form.is_valid():
obj= form.save(commit = False)
author = Account.objects.filter(email=user.email).first()
obj.author = author
obj.save()
return redirect('HomeFeed:main')
context['form'] = form
return render(request, "HomeFeed/create_blog.html", context)
I know this question have been asked alot and most of the time its due to render or HttpResponse in the views.py, i double checked mine but the code looks good to me, dont know where the problem is.
This is a views.py file for a very basic django form but i can't get it to work
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data = request.POST)
profile_form = UserProfileInfoForm(data = request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_from.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit = False)
profile.user = user
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
registered = True
else:
return (user_form.errors,profile_form.errors)
else:
user_form = UserForm()
profile_form = UserProfileInfoForm()
return render(request,'basic_app/register.html',{'user_form': user_form,
'profile_form':profile_form,
'registered':registered})
You can not return (user_form.errors, profile_form.errors), since that is not a HttpResponse object. What response should the server return in that case.
Usually in case the form is invalid, the server will rerender the content. The form will, if you render it properly display the errors.
Note that in case the POST request was successful, you usually should redirect to implement the Post/Redirect/Get pattern [wiki]. You furthermore probably want to use a UserCreationForm [Django-doc]. This will set the password of the user in the correct way (with .set_password(..)), and run a password validator if you configured this.
You thus can rewrite your view as follows, but you probably should replace UserForm with UserCreationForm:
from django.shortcuts import redirect
def register(request):
if request.method == 'POST':
user_form = UserForm(data=request.POST)
profile_form = UserProfileInfoForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_from.save(commit=False)
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'profile_pic' in request.FILES:
profile.profile_pic = request.FILES['profile_pic']
profile.save()
return redirect('name-of-view')
else:
user_form = UserForm()
profile_form = UserProfileInfoForm()
return render(
request,
'basic_app/register.html',
{'user_form': user_form, 'profile_form':profile_form })
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})
I have a user model for which I'm trying to make a view that manages both create/update form rendering/post.
Here is the view that I did for now
def user_edit(request, user_id=None):
obj = {}
status = 200
if user_id:
user = get_object_or_404(User, pk=user_id)
else:
user = User()
user_form = UserForm(instance=user, prefix='user')
if request.method == 'POST':
user_form = UserForm(request.POST, instance=user, prefix='user')
if user_form.is_valid():
user_form.save()
else:
status = 406
obj['user_form'] = user_form
return render(request, 'user/edit.html', obj, status=status)
This works fine, but as you can see, my user_form is initialized 2 times. In order to make this more DRY, at POST time I'd like to update the form definition instead of redefining it. Something like:
if request.method == 'POST':
user_form.data = request.POST
user_form.prefix = 'user'
But I can't make this work. So 2 questions:
Does my view seem valid ?
How can I avoid the form re-definition ?
I would just restructure a couple of lines this way:
def user_edit(request, user_id=None):
status = 200
if user_id:
user = get_object_or_404(User, pk=user_id)
else:
user = User()
user_form = UserForm(request.POST or None, instance=user, prefix='user')
if request.method == 'POST':
if user_form.is_valid():
user_form.save()
else:
status = 406
return render(request, 'user/edit.html', {'form': user_form}, status=status)
Sometimes, it makes sense to duplicate may be 1 line of code to keep it readable.
You should use if condition like this to initialize form only once:
def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render(request, 'contact.html', {
'form': form,
})
Taken from documentation of django. If you are new to Python, it may seem strange to define a variable in if..else statement, but it is pretty common and valid way in Python.