Issue
I'm working on some project and ended up with some issues. So my form doesn't display itself at all in my template. But I've created another form before and it works as it should!
So my code:
models.py
class Project(models.Model):
class Meta:
db_table = "project"
COLORS = (
('R', 'Red'),
('B', 'Blue'),
('G', 'Green'),
('Y', 'Yellow')
)
project_title = models.CharField(max_length=200)
project_color = models.CharField(max_length=1, choices=COLORS)
def __str__(self):
return self.project_title
forms.py
class ProjectForm(ModelForm):
class Meta:
model = Project
fields = ['project_title', 'project_color']
views.py
def addproject(request):
if request.POST:
form_p = ProjectForm(request.POST)
if form_p.is_valid():
form_p.save(commit=False)
return HttpResponseRedirect('/')
else:
form_p = ProjectForm()
context = {
'projects': Project.objects.all(),
"form": form_p,
'username': auth.get_user(request).username,
}
context.update(csrf(request))
return render(request, 'index.html', context)
urls.py
urlpatterns = [
url(r'^addproject/$', views.addproject, name='addproject'),]
index.html
<form action="/addproject/" method="post">
{% csrf_token %}
{{ form_p.as_table }}
<button type="submit" class="btn btn-primary">Add Project</button>
</form>
Solution
The problem is within your template, you are calling your context variable as form_p while passing it as "form":
index.html
<form action="/addproject/" method="post">
{% csrf_token %}
{{ form.as_table }}
<button type="submit" class="btn btn-primary">Add Project</button>
</form>
Answered By - Bernardo Duarte
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.