Reputation: 11
I saw the form documentation in the django site and I wonder how to add the data to the DB.
That`s the HTML :
<form action="/your-name/" method="post">
<label for="your_name">Your name: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>
That`s the function example given in the documentation :
def get_name(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks/')
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
Now I need to see how a function the adds the name to the database will look like.
Upvotes: 0
Views: 110
Reputation: 37846
I hope NameForm
is a modelform. in this case just save()
ing brings the data into db.
if form.is_valid():
form.save()
return HttpResponseRedirect('/thanks/')
if your form is a normal form, then you need to grab the passed value and create/assign to/ a model object:
if form.is_valid():
# modifying
name_object = Name.objects.get(some_field=some_field)
name_object.name_field = form.cleaned_data['your_name']
name_object.save()
# or creating
new_name_object = Name(name_field=form.cleaned_data['your_name'])
new_name_object.save()
return HttpResponseRedirect('/thanks/')
Upvotes: 2
Reputation: 615
for example:
my own model like this:
class MyModel(models.Model):
var = models.CharField(max_length=10)
so in my view:
if form.is_valid():
var = form.cleaned_data['var']
# do insertion or modification or deletion
obj = MyModel.objects.create(var=var)
obj.save()
You'd better take a look at the manual, it's detailed.
Upvotes: 0