Django ModelForm not saving data

2024/9/20 13:39:55

I've tried solutions from the following posts:

Saving data from ModelForm : Didn't work

ModelForm data not saving django : Didn't work.

I'm trying to save data from a ModelForm into the model.

models.py:

class Testimonials(models.Model):name = models.CharField(max_length=128)credentials = models.CharField(max_length=128)test = models.CharField(max_length=2000)id = models.AutoField(primary_key=True)NO = 'NO'YES = 'YES'APPROVAL = ((NO, 'no'), (YES, 'yes'))verified = models.CharField(choices=APPROVAL, default=NO, max_length=3) #Field for making sure only verified testimonials are displayeddef __unicode__(self):return self.id

forms.py:

class TestimonialForm(forms.ModelForm):name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control input-area', 'placeholder': 'Enter your name'}), required=True)credentials = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control input-area', 'placeholder': 'Enter your designation'}), required=True)test = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control test-form-area', 'placeholder': 'Testimonial', 'rows': '5'}), required=True)verified = forms.ChoiceField(widget=forms.HiddenInput())class Meta:model = Testimonials  

views.py

def add_testimonial(request):context = RequestContext(request)if request.method == 'POST':form = TestimonialForm(request.POST)if form.is_valid():form.save(commit=True)return HttpResponseRedirect('/testimonials/thanks/')else:print form.errorselse:form = TestimonialForm()return render_to_response('templates/add_testimonial.html', {'form': form}, context)

Template:

<form id="testimonial_form" method="POST" action="/testimonials/thanks/">{% csrf_token %}{% for hidden in form.hidden_fields %}{{ hidden }}{% endfor %}{% for field in form.visible_fields %}{{ field.help_text}}{{ field }}{% endfor %}<input type="submit" name="submit" value="Add testimonial" class="btn btn-info test-button"/>
</form>

EDIT:

urls.py

url(r'^testimonials/all/', views.testimonials, name='testimonial'),
url(r'^testimonials/thanks/', views.testimonials_thanks, name='testimonial_thanks'),
url(r'^add_testimonial', views.add_testimonial, name='add_testimonial'),

However, on redirect, it doesn't save the form into the model which I'm checking from both PHPMyAdmin (using a MySQLdb) and the Django Admin panel. Any idea why?

Answer

You are POSTing to /testimonials/thanks/ which should be changed to your add_testimonial route to have your view handle the POST. So, the solution is to change the action value in your template's form tag.

If you can post the relevant code from your urls.py I can provide a more specific answer as to what the value of the action attribute should be.

Update

The redirect will happen in your view when a valid form is POSTed. Change your template's action attribute value to:

<form id="testimonial_form" method="POST" action="{% url 'add_testimonial' %}">

In your view:

if form.is_valid():form.save()return HttpResponseRedirect(reverse('testimonial_thanks'))

And make sure you include the following import in your view:

from django.core.urlresolvers import reverse

Update 2

Display your form errors in your template:

<form id="testimonial_form" method="POST" action="{% url 'add_testimonial' %}">{% csrf_token %}{% if form.non_field_errors %}<div class="form-group text-error">{{ form.non_field_errors }}</div>{% endif %}{% for hidden in form.hidden_fields %}{{ hidden }}{% endfor %}{% for field in form.visible_fields %}{{ field.help_text}}{{ field }}{% if field.errors %}<span>{{ field.errors|striptags }}</span>{% endif %}{% endfor %}<input type="submit" name="submit" value="Add testimonial" class="btn btn-info test-button"/>
</form>

Update 3

Now that you can see your form errors, you will need to provide your default value to the hidden field, and there's no need to make it a ChoiceField if the user has no choice (it's hidden!). So change the verified form field to:

verified = forms.CharField(widget=forms.HiddenInput(), initial='no')

Also, it would be a good idea to verify the value in your view since even though the field is hidden, an enterprising, evil user can still POST other values.

https://en.xdnf.cn/q/72492.html

Related Q&A

When is it appropriate to use sample_weights in keras?

According to this question, I learnt that class_weight in keras is applying a weighted loss during training, and sample_weight is doing something sample-wise if I dont have equal confidence in all the …

Django South - turning a null=True field into a null=False field

My question is, what is the best practice for turning a null=True field into a null=False field using Django South. Specifically, Im working with a ForeignKey.

Apostrophes are printing out as \x80\x99

import requests from bs4 import BeautifulSoup import resource_url = requests.get(http://www.nytimes.com/pages/business/index.html) div_classes = {class :[ledeStory , story]} title_tags = [h2,h3,h4,h5,h…

Have Sphinx replace docstring text

I am documenting code in Sphinx that resembles this: class ParentClass(object):def __init__(self):passdef generic_fun(self):"""Call this function using /run/ParentClass/generic_fun()&quo…

exit is not a keyword in Python, but no error occurs while using it

I learn that exit is not a keyword in Python by,import keyword print(exit in keyword.kwlist) # Output: FalseBut there is no reminder of NameError: name exit is not defined while using it. The outpu…

Tensorflow Datasets Reshape Images

I want to build a data pipeline using tensorflow dataset. Because each data has different shapes, I cant build a data pipeline.import tensorflow_datasets as tfds import tensorflow as tfdataset_builder …

Why is the python client not receiving SSE events?

I am have a python client listening to SSE events from a server with node.js APIThe flow is I sent an event to the node.js API through call_notification.py and run seevents.py in loop using run.sh(see …

sklearn Pipeline: argument of type ColumnTransformer is not iterable

I am attempting to use a pipeline to feed an ensemble voting classifier as I want the ensemble learner to use models that train on different feature sets. For this purpose, I followed the tutorial avai…

PyQT Window: I want to remember the location it was closed at

I have a QDialog, and when the user closes the QDialog, and reopens it later, I want to remember the location and open the window at the exact same spot. How would I exactly remember that location?

Django Reusable Application Configuration

I have some Django middleware code that connects to a database. I want to turn the middleware into a reusable application ("app") so I can package it for distribution into many other project…