I need to create a comment form on my site. When I try to display comment_form in HTML instead of the browser, I receive this error:
[u'ManagementForm data is missing or has been tampered with'].
Why is this? How can I fix it?
Here is models.py:
class Category(models.Model):
category_name = models.CharField(max_length=255)
def __unicode__(self):
return u'{0}'.format(self.category_name)
class Category_Form(forms.Form):
category_name = forms.CharField(label='Category_name', max_length=255)
class Comments(models.Model):
comment = models.CharField(max_length=512)
article = models.ForeignKey('Article')
class Comments_Form(forms.Form):
comment = forms.CharField(label='Comment', max_length=512)
article_id = forms.CharField()
class Article(models.Model):
author = models.CharField(max_length=100)
title = models.CharField(max_length=255)
short_text = models.CharField(max_length=1024)
full_text = models.CharField(max_length=5024)
date = models.DateTimeField(default=datetime.now())
category = models.ForeignKey('Category')
class Article_Form(forms.Form):
author = forms.CharField(label='author_article', max_length=100)
title = forms.CharField(label='title_article', max_length=255)
short_text = forms.CharField(label='short_text_article', max_length=1024, widget=CKEditorWidget())
full_text = forms.CharField(label='full_text_article', max_length=5024, widget=CKEditorWidget())
date = forms.DateTimeField()
category = forms.ModelChoiceField(queryset=Category.objects.order_by('category_name'))
My views.py:
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django import forms
from django.template import RequestContext
from sghome.models import News_Form, News, Article_Form, Article, Category, Category_Form, User, User_Form, \
Comments_Form, Comments
from django.forms.formsets import formset_factory
from django.shortcuts import render_to_response
from django.core.urlresolvers import reverse
def Show_Article_Site(request, num):
article = list(Article.objects.filter(id=num))
CommentFormSet = formset_factory(Comments_Form)
formset = CommentFormSet(request.POST, request.FILES)
# formset = CommentFormSet()
return render_to_response('Show_Article_Site.html', {'article': article, 'formset': formset, },
context_instance=RequestContext(request))
def Create_Comment(request):
if request.method == 'POST':
# formset = CommentFormSet(request.POST, request.FILES)
Comment = Comments()
Comment.comment = request.POST['form-0-comment']
else:
Show_Article_Site.formset = Show_Article_Site.CommentFormSet()
return HttpResponseRedirect(reverse(Show_Article_Site))
And my template:
{% extends "base_site.html" %}
{% block center_site %}
{% csrf_token %}
<div class="create_news">
{% for artic in article %}
<br><p>Автор: </p> {{ artic.author }}
<br><p>Дата: </p> {{ artic.date }}
<br><p>Заголовок: </p>{{ artic.title }}
<br><p>Текст: </p>{{ artic.full_text }}
{% endfor %}
<form method="post" action="/Create_Comment/">
{% for form in formset %}
{{ form.comment }}
<input type="submit" value="Add">
{% endfor%}
</form>
</div>
{% endblock %}
Use
formset = CommentFormSet()
Instead of
formset = CommentFormSet(request.POST, request.FILES)
Cause your request.POST and request.FILES are not initiated in that place
Related
I am trying to add a comment section to add a comment section to my blog detail using django but when i run my server i get no error in the development server and the comments are not being displayed. I added the comments from my admin site.
The snippet of my code is below.
views.py
from .models import Post
from django.utils import timezone
from .forms import PostForm, CommentsForm
from django.contrib.auth.decorators import user_passes_test
# Create your views here.
def home(request):
return render (request, 'blogapp/home.html')
def blog_list(request):
post = Post.objects.order_by('-published_date')
context = {
'posts':post
}
return render(request, 'blogapp/blog_list.html', context)
def blog_detail(request, pk=None):
detail = Post.objects.get(pk=pk)
context = {
'detail': detail
}
return render(request, 'blogapp/blog_detail.html', context)
def add_post(request, pk=None):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid:
body = form.save(commit=False)
body.published_date = timezone.now()
body.save()
return redirect('blog_list')
form = PostForm()
else:
form = PostForm()
context = {
'form': form
}
return render(request, 'blogapp/add_post.html', context)
def add_comments(request, pk=None):
if request.method == "POST":
form = CommentsForm(request.POST)
if form.is_valid:
comment = form.save(commit=False)
comment.date_added = timezone.now()
comment.save()
return redirect('blog_detail')
form = CommentsForm()
else:
form = CommentsForm()
context = {
'form': form
}
return render(request, 'blogapp/add_comments.html', context)
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="homepage"),
path('blog/', views.blog_list, name="blog_list"),
path('blog/post/<int:pk>/', views.blog_detail, name="blog_detail"),
path('blog/add_post/', views.add_post, name="add_post"),
path('blog/add_comments/', views.add_comments, name="add_comments"),
]
forms.py
from django import forms
from .models import Post, Comments
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('author', 'title', 'post_description', 'image', 'image_description', 'body',)
class CommentsForm(forms.ModelForm):
class Meta:
model = Comments
fields = ('post', 'name', 'body',)
models.py
from django.db import models
from django.utils import timezone
# Create your models here.
class Post(models.Model):
author = models.ForeignKey('auth.user', on_delete=models.CASCADE)
title = models.CharField(max_length=300)
body = models.TextField()
post_description = models.CharField(max_length=500, blank=True, null=True)
image = models.ImageField(blank=True, null=True, upload_to="image/")
image_description = models.CharField(max_length=500, blank=True, null=True)
published_date = models.DateTimeField(default=timezone.now, blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
class Comments(models.Model):
post = models.ForeignKey('Post', related_name="comments", on_delete=models.CASCADE)
body = models.TextField()
name = models.CharField(max_length=300)
date_added = models.DateTimeField(default=timezone.now, blank=True, null=True)
def __str__(self):
return '%s - %s' % (self.post.title, self.name)
blog_detail.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<article>
<strong>
<h1><b>{{ detail.title }}</b></h1>
</strong>
<h3>POST AUTHOR: {{ detail.author }}</h3>
<h4><i>{{ detail.post_description }}</i></h4>
<h4>PUBLISHED:{{ detail.published_date }}</h4>
<p>
<hr>
{% if detail.image %}
<center>
<br>
<img src="{{ detail.image.url }}" width="1000" height="700">
<br><br>
<i>IMAGE DESCRIPTION: {{ detail.image_description }}</i>
</center>
{% endif %}
<hr>
<br><br><br>
{{ detail.body|linebreaksbr }}
</p>
<hr class="solid">
<h2>COMMENTS ...</h2>Add One
{% for comment in post.comments.all %}
<strong>
{{ comment.name }}-{{ comment.date_added }}
</strong>
{{ comment.body }}
{% endfor %}
</article>
{% endblock %}
add_comments.html
{% extends 'base.html' %}
{% block content %}
<article>
{% if user.is_authenticated %}
<h1>CREATE NEW BLOG POST.</h1>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">ADD COMMENT</button>
<input type="hidden" name="next" value="{% url 'blog_detail' pk=post.pk %}"/>
</form>
{% else %}
<h2>Login HERE to add comments.</h2>
{% endif %}
</article>
{% endblock %}
in your template you use
{% for comment in post.comments.all %}
but in template context there is no post variable
you should use {% for comment in detail.comments.all %}
I have a blog app and the comments can be added on the detail page of the blog, im having trouble implementing a way for users to edit comments they have already made. I have it so a url shows up on comments where only the person signed in can click the link to edit their comments on the post however im getting this error when I try to load the detail page now. Any help would be appreciated thank you
Reverse for 'update_comment' with arguments '(None,)' not found. 1 pattern(s) tried: ['posts(?P[0-9]+)/(?P[0-9]+)/(?P[0-9]+)/(?P[-a-zA-Z0-9_]+)/(?P<comment_id>[0-9]+)/update$']
edit:
I corrected my detail.html file and now im getting this error:
update_comment() missing 1 required positional argument: 'id'
models.py
from django.db.models.signals import pre_save
from Date.utils import unique_slug_generator
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
from django.conf import settings
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager,
self).get_queryset()\
.filter(status='cleared')
class Post(models.Model):
STATUS_CHOICES = (
('cleared','Cleared'),('UnderReview','Being Reviewed'),('banned','Banned'),)
title = models.CharField(max_length = 300)
slug = models.SlugField(max_length = 300, unique_for_date='publish')
author = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='forum_posts',null=True)
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=12,choices=STATUS_CHOICES,default='cleared')
objects = models.Manager()
cleared = PublishedManager()
class Meta:
ordering =('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('posts:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug])
def slug_generator(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = unique_slug_generator(instance)
pre_save.connect(slug_generator, sender=Post)
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.SET_NULL, related_name='comments',null=True)
name = models.ForeignKey(User, on_delete=models.SET_NULL,null=True)
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)
class Meta:
ordering = ('created',)
def __str__(self):
return f'Comment by {self.name} on {self.post}'
urls.py
from . import views
from django.urls import path, include
from django.contrib.auth import views as auth_views
from .views import PostListView, PostCreateView,PostUpdateView
app_name = 'posts'
urlpatterns = [
path('', views.PostListView.as_view(), name='post_list'),
#path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.PostDetailView.as_view(),name='post_detail'),
path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.post_detail,name='post_detail'),
path('post/new/',PostCreateView.as_view(), name='post-create'),
path('<int:year>/<int:month>/<int:day>/<slug:post>/update/',PostUpdateView.as_view(), name='post-update'),
path('<int:year>/<int:month>/<int:day>/<slug:post>/<int:comment_id>/update',views.update_comment, name='update_comment'),
]
views.py
from django.shortcuts import render, get_object_or_404
from .models import Post, Comment
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.generic import ListView, CreateView, UpdateView
from .forms import CommentForm, PostForm
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib import messages
from django.urls import reverse
class PostListView(ListView):
queryset = Post.cleared.all()
context_object_name = 'posts'
paginate_by = 3
template_name = 'posts/post/list.html'
"""class PostDetailView(DetailView, Post):
queryset = Post.cleared.all()
model = Post
fields = ['title','body']
template_name = 'posts/post/detail.html'
form_class = CommentForm
def get_object(self, *args, **kwargs):
return get_object_or_404(
Post,
publish__year=self.kwargs['year'],
publish__month=self.kwargs['month'],
publish__day=self.kwargs['day'],
slug=self.kwargs['post'],
)
return post
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['comment'] = Comment.objects.all()
context['comment_form'] = CommentForm()
return context
def post(self, request, *args, **kwargs):
post = get_object_or_404(Post , slug=post, status='cleared',publish__year=year,publish__month=month,publish__day=day)
comment_form = self.form_class(request.POST)
if comment_form.is_valid():
return HttpResponseRedirect( post.get_absolute_url() )
return render(request, self.template_name, {'comment_form': comment_form})"""
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
fields = ['title','body']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class PostUpdateView(LoginRequiredMixin, UpdateView):
model = Post
fields = ['title','body']
template_name = 'posts/post-update.html'
def get_object(self, *args, **kwargs):
return get_object_or_404(
Post,
publish__year=self.kwargs['year'],
publish__month=self.kwargs['month'],
publish__day=self.kwargs['day'],
slug=self.kwargs['post'],
author=self.request.user
)
def get_success_url(self):
return reverse('posts:post_detail',
args=[
self.object.publish.year,
self.object.publish.month,
self.object.publish.day,
self.object.slug
]
)
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def post_detail(request, year, month, day, post, comment_id = None):
post = get_object_or_404(Post , slug=post, status='cleared',publish__year=year,publish__month=month,publish__day=day)
comments = post.comments.filter(active=True)
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
comment_form.instance.post = post
comment_form.instance.name = request.user
comment_form.save()
return HttpResponseRedirect( post.get_absolute_url() )
else:
comment_form = CommentForm()
return render(request,'posts/post/detail.html', {'post':post , 'comments': comments,'comment_form': comment_form, 'comment_id':comment_id })
def update_comment(request, year, month, day, post,id, comment_id = None):
post = get_object_or_404(Post , slug=post, status='cleared',publish__year=year,publish__month=month,publish__day=day, id=id)
comments = post.comments.filter(active=True)
comment_form = CommentForm
if comment_id:
comment_form = CommentForm(instance=Comment.objects.get(id=comment_id), data=request.POST)
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
comment_form.instance.post = post
comment_form.instance.name = request.user
comment_form.save()
return HttpResponseRedirect( post.get_absolute_url() )
else:
comment_form = CommentForm()
return render(request,'posts/update_comment.html', {'post':post , 'comments': comments,'comment_form': comment_form, 'comment_id':comment_id })
forms.py
from django import forms
from .models import Comment,Post
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('body',)
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields =('title','body',)
detail.html
{% extends "Main/Base.html" %}
{% block title %}{{ post.title }}{% endblock %}
{% block content %}
<h1>{{ post.title }}<h1>
<p class="date">
Published {{ post.publish }} by {{ post.author }}
</p>
{{ post.body|linebreaks }}
{% if user.is_authenticated and user == post.author %}
<h3>Update your post</h3>
{% endif %}
{% with comments.count as total_comments %}
<h2>
{{ total_comments }} comment{{ total_comments|pluralize }}
</h2>
{% endwith %}
{% for comment in comments %}
<div class="comment">
<p class="info">
Comment by {{comment.name }}
{{ comment.created }}
</p>
{{ comment.body|linebreaks}}
{% if user.is_authenticated and user == comment.name %}
<p>edit</p>
{% endif %}
</div>
{% empty %}
<p>There are no comments yet.</p>
{% endfor %}
{% if new_comment %}
<h2>Your comment has been added.</h2>
{% else %}
{% if request.user.is_authenticated %}
<h2>Add a new comment</h2>
<form method="post">
{{ comment_form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Add comment"></p>
</form>
{% else %}
<h3>You need to be logged in to make a comment please log-in if you dont have an account register here now</h3>
{% endif %}
{% endif %}
{% endblock %}
update_comment.html
{% extends "Main/Base.html" %}
{% block content %}
<form method="POST" action="{% url 'posts:update_comment' post.publish.year post.publish.month post.publish.day post.slug comment.id %}">
{{ comment_form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Add comment"></p>
</form>
{% endblock %}
Ive been trying a bunch of this to try and make it work so my code is a bit of a mess, there aren't many tutorials on making editable comments with django.
I've created a new form for comments the articles on a website. When I add the new comment from django admin everything works ok, but when I try to add the new comment directly from detail page nothings happen and I'am redirecting to the page with list of articles.
here are my files
models.py:
class Komentarz(models.Model):
post = models.ForeignKey(Wpisy, related_name="komentarze", verbose_name="Komentarze do artykułu", on_delete=models.CASCADE)
name = models.CharField(max_length=80, verbose_name="Imię")
email = models.EmailField(verbose_name="Email")
content = models.TextField(verbose_name="Treść komentarza")
created_date = models.DateTimeField(verbose_name="Utworzono", auto_now_add=True)
active = models.BooleanField(verbose_name="Aktywny?", default=True)
class Meta:
ordering = ('created_date',)
verbose_name="Komentarz"
verbose_name_plural="Komentarze"
def __str__(self):
return 'Komentarz dodany przez {} dla strony {}'.format(self.name, self.post)
vies.py with the function of details
from django.shortcuts import render, get_object_or_404
from .models import Wpisy, Komentarz
from .forms import KomentarzeForma
....
def detale_bajki(request, slug, ):
detale_bajki = get_object_or_404(Wpisy, slug=slug)
komentarze = detale_bajki.komentarze.filter(active=True)
if request.method == 'POST':
formularz_komentarza = KomentarzeForma(data=request.POST)
if formularz_komentarza.is_valid():
nowy_komentarz = formularz_komentarza.save(commit=False)
nowy_komentarz.detale_bajki = detale_bajki
nowy_komentarz.save()
else:
formularz_komentarza = KomentarzeForma()
return render(request, 'bajki/detale_bajki.html', {'detale_bajki': detale_bajki, 'komentarze': komentarze, 'formularz_komentarza': formularz_komentarza})
forms.py
from .models import Komentarz
from django import forms
class KomentarzeForma(forms.ModelForm):
class Meta:
model = Komentarz
fields = ('name', 'email', 'content')
and detail.html
...
{% with komentarze.count as total_komentarze %}
<h2>
{{ total_komentarze }} komentarz{{ total_komentarze|pluralize:"y" }}
</h2>
{% endwith %}
{% for komentarz in komentarze %}
Komentarz dodany przez <strong>{{komentarz.name}}</strong>
{{komentarz.created_date}}
<p>
{{ komentarz.content|linebreaks }}<br>
{% empty %}
<p>Nie dodano jeszcze żadnych komentarzy</p>
{% endfor %}
{% if nowy_komentarz %}
<h2>Twój komentarz został dodany</h2>
{% else %}
<h2>Dodaj nowy komentarz</h2>
<form action="." method="post">
{{formularz_komentarza.as_p}}
{% csrf_token %}
<p><input type="submit" value="Dodaj komentarz"></p>
</form>
{% endif %}
clas Wpisy in models.py
class Wpisy(models.Model):
title = models.CharField(max_length=400, verbose_name="Tytuł")
slug = models.SlugField(unique=True, max_length=400,verbose_name="Przyjazny adres url")
content = models.TextField()
status_audio = models.BooleanField(default=False, verbose_name="Czy dostępny będzie plik audio?")
audio_file = models.FileField(upload_to='uploads/',verbose_name="Plik audio")
created_date = models.DateTimeField(blank=True, null=True, verbose_name="Data utworzenia")
category = models.ForeignKey(Kategorie, verbose_name="Kategoria", on_delete=models.CASCADE)
class Meta:
verbose_name="Wpis"
verbose_name_plural="Wpisy"
def __str__(self):
return self.title
Your url pattern is
path('bajki/<slug>', views.detale_bajki, name='detale_bajki')
Note that it doesn't have a trailing slash. Your form's action is "."
<form action="." method="post">
That means you are submitting to /bajki/, which is the wrong URL.
You could fix this by adding a trailing slash to the url (which is common in Django URLs)
path('bajki/<slug>/', views.detale_bajki, name='detale_bajki')
Or you could change the form action to "" instead of ".". In the comments it looks like you fixed the issue by changing the form action to {{ detale_bajki.slug }}.
However these changes to the form action are fragile, and could break if you change your URL patterns again. The best approach is to use the {% url %} tag to reverse the correct URL.
<form action="{% url 'detale_bajki' detale_bajki.slug %}" method="post">
Try out:
nowy_komentarz.post = detale_bajki
...
return render(request, 'html page', {'key': 'what you want to return to your context'}) # don't fornget to add some return to your view.
After clicking the upload button on a form I get a bullet point beneath the 'Job ID' field stating "This field is required." even though I have values enterred into the field. Here is my code:
forms.py:
class UploadFileForm(forms.ModelForm):
class Meta:
model = Job
fields = ['jobID',
'original_file']
labels = { 'jobID': _('Job ID'),
'original_file': _('File'),}
error_messages = {
'jobID': {'max_length': _("Job ID is limited to 50 characters."),
},
NON_FIELD_ERRORS: {
'unique_together': "%(model_name)s's %(field_labels)s are not unique.",
}
}
models.py:
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
class Job(models.Model):
user = models.ForeignKey('auth.User')
original_file = models.FileField()
jobID = models.CharField(max_length=50)
rev = models.IntegerField()
create_date = models.DateTimeField(default = timezone.now)
def save(self):
"Get last value of rev considering jobID and User and increment"
"see https://stackoverflow.com/questions/1065089/auto-increment-a-value-in-django-with-respect-to-the-previous-one"
last_rev = Job.objects.filter(user=self.user).filter(jobID=self.jobID).order_by('-rev')
if last_rev:
rev = last_rev[0].rev + 1
else:
rev = 1
super(Job,self).save()
def __unicode__(self):
return self.jobID + " rev " + str(self.rev)
class Meta:
indexes = [
models.Index(fields=['user','jobID']),
]
unique_together = ("user","jobID","rev")
ordering = ['-create_date']
views.py
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import UploadFileForm
from .models import Job
# Create your views here.
def upload(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return render(request,'precheck/prestage.html')
else:
form = UploadFileForm()
return render(request, 'precheck/upload.html',{'form': form})
def success(request):
return render(request, 'precheck/prestage.html')
upload.html
{% extends 'base.html' %}
{% block content %}
<h2>Upload File</h2>
{% if error %}
{{ error }}
<br />
<br />
{% endif %}
<form method = "POST" action="{% url 'precheck:upload' %}">
{% csrf_token %}
{{ form.as_p }}
<br />
<input type="submit" class="btn btn-primary" value="Upload">
</form>
{% endblock %}
I tried manually building the form (ie not using a modelform) with the same results. Thanks for the help.
EDIT:
Changing the form to include enctype="multipart/form-data" did the trick:
<form method = "POST" action="{% url 'precheck:upload' %}" enctype="multipart/form-data">
The error is not for jobID, but for original_file. This is because you are not using the enctype="multipart/form-data" attribute on the form element.
I can't get my django app to post to the db. I'm trying to pass my foreign key so I can post it correctly.
Sorry if it's something basic I'm missing I'm just starting. I think it never gets to form = ResultForm(request.POST). And just gives me the form = ResultForm.
Here is my code:
Model:
class Result(models.Model):
category = models.ForeignKey(Category)
category_result = models.CharField(max_length=200)
rating = models.DecimalField('', '', 8, 3)
votes = models.IntegerField(default=0)
created_by = models.IntegerField(default=0, null=True, blank=True)
created_on = models.DateTimeField('created on')
def __unicode__(self):
return self.category_result
Form:
class ResultForm(forms.ModelForm):
category_result = forms.CharField(max_length=200,help_text="Your best line")
rating = forms.DecimalField(widget=forms.HiddenInput(), initial=0)
votes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
created_by = forms.IntegerField(widget=forms.HiddenInput(), initial=1)
category = forms.IntegerField(widget=forms.HiddenInput())
class Meta:
model = Result
fields = ('category_result', 'rating', 'votes')
view:
def help_out(request, category_id):
if request.method == 'POST':
form = ResultForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.category = category_id
form.save()
return index(request)
else:
print form.errors
else:
form = ResultForm
context = {'form': form, 'category_id': category_id}
return render(request,'pocketwingman/help_out.html', context)
template:
<!DOCTYPE html>
<html>
<head>
<title>Pocketwingman</title>
</head>
<body>
<h1>Add a Result</h1>
<form id="result_form" method="post" action="/pocketwingman/help_out/{{category_id}}/">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text}}
{{ field }}
{% endfor %}
<input type="submit" name="submit" value="Create Line" />
</form>
</body>
</html>
url config:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^(?P<category_id>\d+)/$', views.help_me, name='help_me'),
url(r'^help_out/(?P<category_id>\d+)/$', views.help_out, name='help_out'),
)
You should initiate your form if it's not a POST:
else:
form = ResultForm()
append () to form class.