For some reason, I can't get form.save() to save to my database. I'm able to create the form, and have the form pass itself off to my template, but nothing is getting saved to the database. I've mucked around with it for many hours and haven't been able to get it to work.
Any help is appreciated.
Here is the relevant code..
This is my add/model.py
from django.db import models
from django.forms import ModelForm
class addTask(models.Model):
task = models.CharField('Task', max_length=60)
taskNotes = models.CharField('Notes', max_length=600)
def __unicode__(self):
return self.task
class addTaskForm(ModelForm):
class Meta:
model = addTask
template/addTHEtask.html. This is getting referenced correctly.
<form action="/todo/" method="post">
{{ form.as_p }}
<input type="submit" value="Add Task" />
</form>
add/views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
from myToDo.add.models import addTask, addTaskForm
def create_task(request):
if request.method == 'POST':
form = addTaskForm(request.POST)
if form.is_valid():
form.save()
else:
form = addTaskForm()
return render_to_response('addTHEtask.html', {'form': form})
To properly debug your code, change your template to:
<form action="/todo/" method="post"> {{ csrf_token }}
{{ form.errors }}
{{ form.as_p }}
<input type="submit" value="Add Task" />
</form>
And your view to:
def create_task(request):
if request.method == 'POST':
form = addTaskForm(request.POST)
if form.is_valid():
form.save()
else:
form = addTaskForm()
return render_to_response(
'addTHEtask.html',
{'form': form},
context_instance=RequestContext(request))
I don't think the context_instance will do anything significant for you, but it is usually the right thing to pass when using render_to_response.
Showing the errors in the form may help you track down what the actual problem is. Your code looks (mostly) correct, except the missing csrf_token. Adding the token, and displaying any errors, should show you what is going wrong.
Related
I've imported this from django.contrib.auth.forms import UserCreationForm
used csrf_token in the form but still when I hit submit the page reloads but doesn't save the data to database.
def signup(req):
if req.method == 'POST':
form = UserCreationForm(req.POST)
if form.is_valid():
form.save()
form = UserCreationForm()
reg_con={
'regform': form
}
return render(req, 'signup.html', reg_con)
form
<form action="." method="POST">
{% csrf_token %}
{{ regform.as_ul }}
<input type="submit" value="Sign Up">
</form>
This is normally because something is wrong with your form the problem is however that you each time construct a new form, and you thus can not see what went wrong. You should only create a new form in case it is a GET request, so:
def signup(req):
if req.method == 'POST':
form = UserCreationForm(req.POST)
if form.is_valid():
form.save()
else:
form = UserCreationForm()
reg_con={
'regform': form
}
return render(req, 'signup.html', reg_con)
Try removing the action attribute from your form tag. Also don't forget to redirect after calling form.save()
I'm trying to make a non model form that just gets input text for a chat like interface.
views.py
def get_input(request):
if request.method == 'POST':
form = inputForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/thanks/')
else:
form = inputForm()
return render(request, 'index.html', {'form': form})
def shelley_test(request):
form = inputForm()
return render(request, 'shelley_test.html')
form.py
from django import forms
class inputForm(forms.Form):
input = forms.CharField(label='input field')
shelley_test.html
<form action="/get_input/" method="get">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
please please help. I'm new at django and stumped :(
You're not sending the form to the context in your shelley_test method - see the difference in the render line compared with get_input.
Note though you don't need shelley_test at all: just go straight to /get_input/ to see the empty form.
Only the button is visible and headings are visible cannot see CharField
forms.py
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from compare.forms import NameForm
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})
index.htm
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
You should give the if form.is_valid() part, one more tab.
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from compare.forms import NameForm
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})
I'm not yet allowed to add comments to your question, but you did notice, that your view renders name.html while you're providing the code for index.htm.
Basically your code seems valid, while it can be further optimized:
def get_name(request):
form = NameForm(request.POST or None)
if form.is_valid():
return HttpResponseRedirect('/thanks/')
return render(request, 'name.html', {'form': form})
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
This should work by adding editing {{form.as_p}}
After user logs in, user is able to submit a form. On click of submit button, data is being stored in DB, but how should I connect this information to the submitting user.
I would need the code as well as the structure of the new db
Kind of starting out in django.
Any help would be appreciated!!!
I have included user as foreign key in the CustomizeRequest model, but now how do i fill in this information?
Exact Scenario: After user log in, once he comes to contactUs.html, he submits a form which tells the number of travellers. This number is being stored in the DB. But now how do I connect each of these numbers to the submitted user?
models.py
class CustomizeRequest(models.Model):
user = models.ForeignKey(User)
travellers = models.CharField(max_length=2)
def __str__(self):
return self.travellers
contactUs.html
<form method="POST" class="form-horizontal">
{% csrf_token %}
<div class="btn-group" data-toggle="buttons">
{% for radio in crform.travellers %}
<label class="btn btn-default {% if radio.choice_label = '1' %}active{% endif %}" for="{{ radio.id_for_label }}">
{{ radio.choice_label }}
{{ radio.tag }}
</label>
{% endfor %}
</div>
<button type="submit" class="btn btn-default btn-block btn-warning">SUBMIT</button>
</form>
views.py
def contactUs(request):
if request.method=="POST":
form = CustomizeRequestForm(request.POST)
form.save()
else:
form = CustomizeRequestForm()
context_dict = {'form': form}
return render(request, 'tour/contactUs.html', context_dict)
Based on catavaran answer (with a check to see if the form is valid):
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
#login_required
def contactUs(request):
form = CustomizeRequestForm(data=request.POST or None)
if request.method == "POST":
if form.is_valid():
customize_request = form.save(commit=False)
customize_request.user = request.user
customize_request.save()
return redirect('.')
else:
pass # could add a notification here
context_dict = {'form': form}
return render(request, 'tour/contactUs.html', context_dict)
Logged user is available as request.user property. You can get the unsaved model instance using form.save(commit=False) trick, set the user field and then save the instance to database:
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
#login_required
def contactUs(request):
if request.method == "POST":
form = CustomizeRequestForm(request.POST)
if form.is_valid():
customize_request = form.save(commit=False)
customize_request.user = request.user
customize_request.save()
return redirect('.')
else:
form = CustomizeRequestForm()
context_dict = {'form': form}
return render(request, 'tour/contactUs.html', context_dict)
I have created form using ModelForm but its not saving data into database.
views.py
def answer(request):
if request.method == 'POST':
form = AnswerForm(request.POST)
if form.is_valid():
form.save()
else:
form = AnswerForm()
return render_to_response('quiz/index.html', {'form': form, })
template
<form action="." method="post">
{{ form.as_p }}
<input type="submit" value="Submit">
</form>
model
class Answer(models.Model):
answer = models.TextField()
class AnswerForm(ModelForm):
class Meta:
model = Answer
Where i was wrong ? :/
You forgot to handle the case where the form isn't valid.