Django-reviews: cannot set content-type - django

I'm using django-reviews (http://code.google.com/p/django-reviews/) and having trouble setting the content-type for a review. Simple example:
def check_review(request):
if request.method == 'POST':
reviewed_item = get_object_or_404(MyModel, pk=request.POST['object_pk'])
review_form = ReviewForm(target_object=reviewed_item, data=request.POST)
review_form.content_type = ContentType.objects.get_for_model(MyModel)
However the form's 'content_type' field has no value and the form has
the error "(Hidden field content_type) This field is required." I've
tried to set the content_type multiple ways with no luck. Any ideas?

To clarify, I'm going with the assumption you see the form displayed, you fill it in the values and try to submit. At this point, you see form validation error indicating you need the hidden field filled in. Is that correct?
If so, you need to set the content_type on the form before submitting. Normally I do something like this:
def check_review(request):
if request.method == 'POST':
reviewed_item = get_object_or_404(MyModel, pk=request.POST['object_pk'])
review_form = ReviewForm(target_object=reviewed_item, data=request.POST)
if review_form.is_valid():
# do some processing here
else:
# We're just getting an unbound form
reviewed_item = get_object_or_404(MyModel, pk=request.POST['object_pk'])
review_form = ReviewForm(target_object=reviewed_item, data=request.POST)
review_form.content_type = ContentType.objects.get_for_model(MyModel)
# return with review_form in the template's context or what have you

I found that you can set form values with
review_form.base_fields["content_type"] = ...
though this still didn't seem to work for content_type. This was actually a mistake on my part. I meant to instantiate a Review object after the form was validated and set the content_type on that object. Much easier.

Related

How can I delete form field data in django after submit

I'm working on a django project where during registration, a user can submit a code to get special discounts. The validation of the discount codes is already working nicely, but I'm missing one beautifying aspect: After the user submits an invalid code I want to empty out the input field; i.e.:
def validate_code(value):
# check code for validity or raise ValidationError
class CodeForm(forms.Form):
code = forms.CharField(validators=[validate_code])
# in my views.py
def code_verification_view(request):
if request.method == 'POST':
form = CodeForm(request.POST)
if form.is_valid():
# proceed with given code
else:
# modify form to return an empty html input for the code field
# this is where I'm stuck
form.fields['code'].value = ''
# ... render the form in a template
The end result should be a form with an empty input field, but the validation errors showing. The behavior should be similar to how password input fields are emptied if the form verification fails.
EDIT: I solved the problem, but in a very hacky way:
see https://stackoverflow.com/a/46564834/8572938
I'd appreciate a proper solution that does not rely on accessing protected members of the form.
the key is to reset form variable
form = CodeForm(None)
in your code
def code_verification_view(request):
if request.method == 'POST':
form = CodeForm(request.POST)
if form.is_valid():
# proceed with given code
else:
form = CodeForm(None)
Just render your template, if your form is not valid, it will show error, In case if it is valid process your data
def code_verification_view(request):
if request.method == 'POST':
form = CodeForm(request.POST)
if form.is_valid():
// process your data
else:
form.data['field'] = None
return render(request, template_name, {'form': form})
Make a field validation in your form definition:
class CodeForm(forms.Form):
code = forms.CharField(validators=[validate_code])
def clean_code(self):
code = self.cleaned_data(code)
error = # some of your process
if error:
self.fields['code'] = None
raise forms.ValidationError('...')
else:
return code
And remove the else part in your view, instead you want to do something else. If you just want to display the form with error, the raise forms.ValidationError will do it.
You can in django form add a clean_<field_name> to control each field as you like.
More info here
I found a way that works, but it's quite dirty:
old_form = CodeForm(request.POST)
form = CodeForm()
if old_form.is_valid():
# ...
else:
form._errors = old_form._errors
# pass form into the rendering context
This way, I get a clean form with the preserved errors.
While it does the job, it is clearly an ugly hack.

Can't figure out why form.has_changed() is always true?

I'm trying to learn Django and have come up with a situation I can't figure out. I have the following code:
def contact_add(request):
if request.method == 'POST':
form = ContactManageForm(request.POST)
if form.is_valid():
if form.has_changed(): # <-- ALWAYS RETURNS TRUE!
form.clean()
...
elif 'id' in request.GET: # Request to show an existing contact
new_contact_dynamic = contacts.models.PersonDynamic.objects.get(person_static = request.GET['id'],
current_record_fg = True)
form = ContactManageForm(new_contact_dynamic.__dict__, initial=new_contact_dynamic.__dict__)
else: # This must be to add a new contact
form = ContactAddForm()
return render(request, 'contact_manage.html', {'form': form})
So, if I'm sent an ID number, I read a record and display it on the screen. My template gives the user a 'submit changes' button. My problem, as noted above, is that Django always shows that the form has changed, even if the user hasn't changed any data on the screen (i.e. he just hit the submit changes button without changing anything).
So, am I doing something obviously wrong in my code that's creating this situation? Am I misinterpreting how the form.has_changed() method works?
It's my assumption that when I use the initial=parameter after a GET request, Django is storing that data somewhere and knows the context when the user then hits the 'submit data' button, is this wrong?
Yes you need to initialize your Form with initial data.
In your view the GET and POST requests have no common context. You may want to use sessions for that.
But in this case, it is not necessary. You can retrieve the instance on each request:
def contact_add(request):
if 'id' in request.GET:
new_contact_dynamic = contacts.models.PersonDynamic.objects.get(
person_static = request.GET['id'],
current_record_fg = True
)
if request.method == 'POST':
form = ContactManageForm(request.POST, initial=new_contact_dynamic.__dict__)
...
else: # Show an existing contact
form = ContactManageForm(initial=new_contact_dynamic.__dict__)
else:
form = ContactAddForm()
return render(request, 'contact_manage.html', {'form': form})

Form Validation Error when a required field is remained blank in django

I want to have errors as a label above a field if it is not filled.
This is my views.py:
#login_required(login_url='user_profile:login')
def NewWriting(request):
if request.method=="POST":
form=WritingForm(request.POST)
if form.is_valid():
post=form.save(commit=False)
post.author=request.user
post.save()
return redirect('user_profile:index')
else:
form = WritingForm()
subject = Subject.objects.all()
return render(request,'user_profile/writing_form.html', {'form':form , 'subject':subject})
what should I add to my code?
Thanks
Without seeing your form class ...
Option 1:
If you really want the user to be able to submit the form with empty data and then specifically show them that error using the form, set the required=False kwarg for the specific field in your WritingForm class. Then override the clean_<fieldname> (link) method and then you could do:
def clean_<fieldname>:
if self.cleaned_data['<fieldname>'].strip() == '':
raise ValidationError('This field cannot be blank!')
return self.cleaned_data['<fieldname>']
Replacing <fieldname> with whatever that fieldname is.
Option 2:
The default for any form is to make all fields required (IE: required=True kwarg on the field). So in general, if the field is required most browsers will at least move the cursor to the empty field and won't allow the form to be submitted while there is no data in the field.
You also need to return a bound form in the case where form.is_valid() returns False or you won't ever see the errors (right now you don't return anything if the form is invalid). Please see the django docs here for a common functional view pattern using forms.
You need to add another all to render if the form is not valid, and in your template, you need to make use of form.errors. Something like this should work so that form validation errors are then passed back to the UI/template for display to the user:
#login_required(login_url='user_profile:login')
def NewWriting(request):
form = None
if request.method=="POST":
form=WritingForm(request.POST)
if form.is_valid():
post=form.save(commit=False)
post.author=request.user
post.save()
return redirect('user_profile:index')
if form is None:
form = WritingForm()
subject = Subject.objects.all()
return render(request,'user_profile/writing_form.html', {'form':form , 'subject':subject})

Django validation error triggered with initial data in modelformset_factory

I'm currently running Django 1.4.
When I'm creating a modelformset and provide an initial value to the extra form, Django then runs validation against it and finds that the other required fields are empty and thus throws a validation error.
My code looks something like this:
QueryFormset = modelformset_factory(Query, extra=1,
can_delete=True, form=QueryForm
)
if request.method == "POST":
qformset = QueryFormset(request.POST)
if qformset.is_valid():
qformset.save()
else:
# This is where we go when the formset is saved without
# any values inserted into the extra form
else:
qformset = QueryFormset(
queryset=Query.objects.filter(user=request.user),
initial=[{'user': request.user}]
)
If I just click save without making any changes to the values of the form (existing forms, or to the extra form) the formset is marked as invalid because the extra form has something in the user field, but is missing the other required fields.
How do I make Django let this pass by? It should throw away the extra form as nothing there has been changed.
I'm not saying this is the best solution, but I was able to work around this problem by modifying the form's 'is_bound' attribute. This is an internal flag indicating whether the form has something worth validating (from what I can tell).
initial_data = [{...},]
if request.POST:
formset = ContactFormSet(request.POST, initial=initial_data)
valid = True
for form in formset:
if not form.has_changed():
# we don't want to complain about an unmodified form.
form.is_bound = False
if not form.is_valid():
valid = False
if valid:
for form in formset:
if form.has_changed():
# do stuff
else:
formset = ContactFormSet(initial=initial_data)
...
It'd definitely be nicer to integrate this workaround into the form/formset itself, rather than the view, but I don't need this behaviour often, so it's good enough for me.

Django initiate form fields with model instance

I thought it looks trivial, and was surprised.
What I have
I have a Django model + form (ModelForm).
My user fills in the form, and on my view I have the usual:
if request.POST:
form = myForm(request.POST)
if request.method == "POST" and form.is_valid():
result = form.save(commit=False)
Now I need to heavily manipulate some fields of the form (in the "result" object) and I want to check the forms is_valid() again before saving.
The Problem
I tried to create a new form using the "result" object (that is a ModelForm object) using a dictionary (as suggested here)
result_dictionary = dict((x.name, getattr(result, x.name)) for x in result._meta.fields)
or
result_dictionary = model_to_dict(result, fields=[field.name for field in result._meta.fields])
plus
testForm = myForm(initial=result_dictionary)
but it doesn't pass is_valid() and does'nt give any errors!
The fields are passed OK to the new form...
Any ideas?
Sometimes, looking in the Django source can be really helpful, here's BaseForm.is_valid():
def is_valid(self):
"""
Returns True if the form has no errors. Otherwise, False. If errors are
being ignored, returns False.
"""
return self.is_bound and not bool(self.errors)
So if there are no errors, is_valid() returns false because you haven't bound the form, you haven't given the form anywhere to look for data. Try using the form.data dictionary instead, something like this:
if request.POST:
form = myModel(request.POST)
if request.method == "POST" and form.is_valid():
form.data['field1'] = 'Changing this'
form.data['field2'] = 34
testform = myModel(data=form.data)