Django form fields are not displayed - python

I want to make a form for adding comments, but I only display a form without fields for input, it does not give any errors.
how it looks on the web-site, there should be a form to post a comment.
I would also like to know how this code can be improved.
Any help is appreciated!
Here is my forms.py:
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['body']
views.py:
def comments(request, id):
if request.method == 'POST':
cf = CommentForm(request.POST or None)
if cf.is_valid():
body = request.POST.get('body')
comment = Comment.objects.create(post=post, user=request.name, body=body)
comment.save()
return redirect(post.get_absolute_url())
else:
cf = CommentForm()
context = {
'cf': cf,
}
return render(request, 'main/article_detail.html', context)
urls.py:
from django.urls import path, include
from . import views
from .views import *
urlpatterns = [
path('', PostListViews.as_view(), name='articles'),
path('article/<int:pk>/', PostDetailViews.as_view(), name='articles-detail'),
path('register/', register, name='register'),
path('login/', login, name='login'),
]
My form in template:
<form method="POST">
{% csrf_token %}
{{ cf.as_p }}
<button type="submit" class="btn btn-primary" style="width: 100px;position: relative;">Submit</button>
</form>
my models.py:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Article(models.Model):
title = models.CharField(max_length=30)
content = models.TextField()
pub_date = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey(Article, related_name='comments', on_delete=models.CASCADE)
name = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['date']
def __str__(self):
return f'Comment {self.body} by {self.name}'

In your views.py
def comments(request, id):
if request.method == 'POST':
cf = CommentForm(request.POST or None)
if cf.is_valid():
comment = cf.save(commit=False)
comment.user = request.user
comment.post = post # you also will have to query your post first (i presume thats what the id is for in the function declaration)
comment.save()
return redirect(post.get_absolute_url())
else: # fix this
cf = CommentForm()
context = {
'cf': cf,
}
return render(request, 'main/article_detail.html', context) # fix this
Your indentation is implying that the template will render only with the POST method, since when you're accessing the view you are calling a GET method, your render function never gets called.
Also just use regular form.save() method to save your objects to database, its much easier to understand. And you do have to query your post before assigning a comment to it.

In your views, your else block is not indented with request.method if block and also use return render method...
Also use data=request.post in your parentheses bracket instead of "request.post or none". Try this....it should work then....

Related

ValueError at /adding-url-patterns-for-views

I am trying to allow user to post answer and comments to a particular bloq question
Q&A
Error displayed:
ValueError at /adding-url-patterns-for-views
Cannot assign "<SimpleLazyObject<django.contrib.auth.models.AnonymousUser object at 0x04A5B370>>": "PostAnswer.user" must be a "CustomUser" instance.
Here is my model
class PostQuestion(models.Model):
""" Model for posting questions """
title = models.CharField(max_length=100, unique=True)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE, null=True, blank=True)
slug = models.SlugField(unique=True, null=True, max_length=250)
created_on = models.DateTimeField('date published',
auto_now_add=True)
text_content = models.TextField()
tags = TaggableManager()
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('detail_view', kwargs={'slug': self.slug})
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
return super().save(*args, **kwargs)
class PostAnswer(models.Model):
""" Model for answering questions"""
question = models.ForeignKey(
PostQuestion,
on_delete=models.CASCADE,
related_name='comments',
)
text_content = models.TextField()
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
)
approved_comment = models.BooleanField(default=False)
created_on = models.DateTimeField('published', auto_now_add=True)
class Meta:
ordering = ['created_on']
def approve(self):
self.approved_comment = True
self.save()
def __str__(self):
return 'comment by {} on {}'.format(self.user, self.question)
Here is my views.py on an app
class Index(ListView):
queryset = PostQuestion.objects.all()
template_name = 'index.html'
context_object_name = 'posts'
paginate_by = 10
def detail(request, slug):
post = get_object_or_404(PostQuestion, slug=slug)
comments = post.comments.all()
# comment posted
if request.method == 'POST':
form = CommentForm(data=request.POST)
if form.is_valid():
form.instance.question = post
form.instance.user = request.user
form.save()
return redirect('post_detail', slug=slug)
else:
form = CommentForm()
context = {'post': post,
'comments': comments,
'form': form}
return render(request, 'detail.html', context)
My App form:
class CommentForm(forms.ModelForm):
text_content = forms.CharField(widget=PagedownWidget())
class Meta:
model = PostAnswer
fields = ['text_content']
My urls.py view for the app
from .views import detail, ask, Index
from django.urls import path
urlpatterns = [
# path('<slug:slug>/comment', add_comment_to_post, name='add_comment_to_post'),
path('ask/', ask, name='ask'),
path('<slug:slug>', detail, name='detail_view'),
path('', Index.as_view(), name='index'),
]
Here is the html template for the comment
<!--------Display a form for users to add a new comment------->
<h3>Leave a comment</h3>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary btn-sm">Add Comment</button>
</form>
This is all of code that I think you need to know the problem. I don't know if the problem can be caused for database or why are not all instructions in the views.
If you can help me, thanks you in advance.
The name of the field is question, not post, so you should rewrite the logic to:
new_comment.question = post
This will however still raise an error, since the user field is not filled in either.
Using commit=False is however not a good idea, since then the form can no longer save many-to-many fields. As far as I can see, there are at the moment no many-to-many fields, but nevertheless, if you later add such fields, you have to rewrite the logic. You can improve the view to:
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect
#login_required
def detail(request, slug):
post = get_object_or_404(PostQuestion, slug=slug)
comments = post.comments.all()
if request.method == 'POST':
form = CommentForm(data=request.POST)
if form.is_valid():
form.instance.question = post
form.instance.user = request.user
form.save()
return redirect('page:detail_view', slug=slug)
else:
form = CommentForm()
context = {
'post': post,
'comments': comments,
'form': form
}
return render(request, 'detail.html', context)
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.
Note: You can limit views to a view to authenticated users with the
#login_required decorator [Django-doc].

NOT NULL constraint failed: community_comment.posts_id?

how can I fix this issue?
the page runs perfectly. when I do post the post. it posts but when I want to type the comment and send by 'GET' I get this error. so, how can I ignore this error this my first question?
- also, I need anyone to give me the best way to make a relationship between post and comment
models.py
from django.db import models
from django.contrib.auth.models import User
class Publication(models.Model):
title = models.CharField(max_length=30)
class Meta:
ordering = ['title']
def __str__(self):
return self.title
class Article(models.Model):
publications = models.ManyToManyField(Publication)
headline = models.CharField(max_length=100)
class Meta:
ordering = ['headline']
def __str__(self):
return self.headline
class Post(models.Model):
users = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
question = models.TextField(max_length=500)
def __str__(self):
return self.title
class Comment(models.Model):
posts = models.ForeignKey(Post, on_delete=models.CASCADE)
comment = models.TextField(max_length=500)
def __str__(self):
return self.comment
views.py
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from .models import Post, Comment
from .forms import PostForm, CommentForm
def index(request):
# All questions
posts = Post.objects.all()
return render(request, 'community/index.html', {'posts': posts})
def post_view(request):
post_form = PostForm
context = {'posted': post_form}
# Create post
if request.method == 'GET':
post_form = PostForm(request.GET)
if post_form.is_valid():
user_post = post_form.save(commit=False)
user_post.title = post_form.cleaned_data['title']
user_post.question = post_form.cleaned_data['question']
post = Post.objects.create(users=User.objects.get(username=request.user), title=user_post.title, question=user_post.question)
post.save()
return redirect('community:index')
return render(request, 'community/post.html', context)
def answers(request, post_id):
# Specific post
posts = Post.objects.get(id=post_id)
# Create comment
comment_form = CommentForm
context = {'posts': posts, 'comment_form': comment_form}
if request.method == 'GET':
comment_form = CommentForm(request.GET)
if comment_form.is_valid():
user_comment = comment_form.save(commit=False)
user_comment.comment = comment_form.cleaned_data['comment']
user_comment.save()
return render(request, 'community/answers.html', context)
urls.py
from django.urls import path
from . import views
app_name = 'community'
urlpatterns = [
path('', views.index, name='index'),
path('post/', views.post_view, name='post'),
path('answers/<int:post_id>', views.answers, name='answers'),
]
forms.py
from .models import Post, Comment
from django import forms
from django.contrib.auth.models import User
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = '__all__'
exclude = ['users']
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = '__all__'
exclude = ['users', 'posts']
You forgot to assign the post, or the post_id of the comment you created:
def answers(request, post_id):
# Specific post
posts = Post.objects.get(id=post_id)
# Create comment
comment_form = CommentForm
context = {'posts': posts, 'comment_form': comment_form}
if request.method == 'GET':
comment_form = CommentForm(request.GET)
if comment_form.is_valid():
comment_form.instance.post_id = post_id
user_comment = comment_form.save()
# …
That being said, the above view does not really respect the HTTP assumptions. A view that makes a GET request is not supposed to change entities, so if you want to create a comment, you need to do that through a POST request. Furthemore in order to implement the Post/Redirect/Get pattern [wiki] a successful POST request should return a redirect response.

Django ModelForm returns None instead of HttpResponse

I've been following the tutorial for 'File Upload With Model Forms' here: https://simpleisbetterthancomplex.com/tutorial/2016/08/01/how-to-upload-files-with-django.html
I'm pretty sure I followed it to the letter (except using my own project). However I'm getting the error
The view myproject.views.InspectionReportForm_Create didn't return an HttpResponse object. It returned None instead.
Here is my code:
models.py:
class Inspection(models.Model):
InspectionID = models.AutoField(primary_key=True, unique=True)
PartID = models.ForeignKey('Part', on_delete=models.CASCADE, null=True)
#classmethod
def create(cls, partid):
inspection = cls(PartID = partid)
return inspection
class InspectionReport(models.Model):
ReportID = models.AutoField(primary_key=True, unique=True)
InspectionID = models.ForeignKey('Inspection', on_delete=models.CASCADE, null=True)
Date = models.DateField(auto_now=False, auto_now_add=False, null=True)
Comment = models.CharField(max_length=255, blank=True)
FileName = models.CharField(max_length=255, blank=True)
Report = models.FileField(upload_to='docs', null=True, blank=True)
Signature = models.CharField(max_length=255, blank=True)
#classmethod
def create(cls, inspid, date, comment, rept, sig):
inspreport = cls(InspectionID = inspid, Date = date, Comment = comment, Report = rept, Signature = sig)
return inspreport
forms.py:
class InspectionReportForm(forms.ModelForm):
class Meta:
model = InspectionReport
fields = ('InspectionID', 'Date', 'Comment', 'Report', 'Signature')
views.py:
def InspectionReportForm_Create(request):
if request.method == 'POST':
form = InspectionReportForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('sites/1')
else:
form = InspectionReportForm()
return render(request, 'moorings/uploadReport.html', {'form': form })
uploadReport.html (just the form. everything else is styling and titles etc):
<div id="wrapper" class="dark">
<div id="loginwrapper" class="dark">
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Create</button>
</form>
</div>
</div>
The misfitting div name on the form wrapper is just because I reused the layout from my login page which used a similar form.
EDIT: One thing that might be the issue... the tutorial doesn't say anything about urls.py. So I added this in, which may or may not be correct:
urls.py:
urlpatterns = [
path('', views.index, name='index'),
path('sites/<int:site>', views.sites, name='sites'),
path('parts/<int:part>', views.parts, name='parts'),
path('signup/', views.signup, name = 'signup'),
path('uploadReport/', views.InspectionReportForm_Create, name = 'CreateReport')
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Change
def InspectionReportForm_Create(request):
if request.method == 'POST':
form = InspectionReportForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('sites/1')
else:
form = InspectionReportForm()
return render(request, 'moorings/uploadReport.html', {'form': form })
to
def InspectionReportForm_Create(request):
if request.method == 'POST':
form = InspectionReportForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('sites/1')
else:
form = InspectionReportForm()
return render(request, 'moorings/uploadReport.html', {'form': form })

Django filter generic form Select attribute from generic class-based view by Username or prepopulate and hide the form Select-attribute

I Need to Restrict the Options in a Select Field of a Django Form for not staff users.
So these are my models.py:
#!/usr/bin/python3
from django.db import models
from django.urls import reverse
class Extension(models.Model):
username = models.CharField(primary_key=True, max_length=200, help_text='')
callerid = models.CharField(max_length=200, help_text='')
extension = models.CharField(max_length=3, help_text='')
firstname = models.CharField(max_length=200, help_text='')
lastname = models.CharField(max_length=200, help_text='')
password = models.CharField(max_length=200, help_text='')
context = models.ForeignKey('Context', on_delete=models.SET_NULL, null=True)
def get_absolute_url(self):
return reverse('extension-detail', args=[str(self.username)])
def my_get_absolute_url(self):
return reverse('my-extension-detail', args=[str(self.username)])
def __str__(self):
return self.username
class Context(models.Model):
name = models.CharField(primary_key=True, max_length=200, help_text='')
countryprefix = models.CharField(max_length=200, help_text='')
cityprefix = models.CharField(max_length=200, help_text='')
number = models.CharField(max_length=200, help_text='')
extensionsfrom = models.CharField(max_length=200, help_text='')
extensionstill = models.CharField(max_length=200, help_text='')
portscount = models.CharField(max_length=200, help_text='')
def get_absolute_url(self):
return reverse('context-detail', args=[str(self.name)])
def my_get_absolute_url(self):
return reverse('my-context-detail', args=[str(self.name)])
def __str__(self):
return self.name
views.py:
#!/usr/bin/python3
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from django.contrib.auth.models import Permission
from catalog.models import Extension, Context
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
class ExtensionCreate(LoginRequiredMixin, PermissionRequiredMixin, CreateView):
model = Extension
fields = '__all__'
permission_required = 'catalog.add_extension'
class ExtensionUpdate(LoginRequiredMixin, PermissionRequiredMixin, UpdateView):
model = Extension
fields = '__all__'
permission_required = 'catalog.change_extension'
class ExtensionDelete(LoginRequiredMixin, PermissionRequiredMixin, DeleteView):
model = Extension
success_url = reverse_lazy('extensions')
permission_required = 'catalog.delete_extension'
urls.py:
#!/usr/bin/python3
from . import views
from django.urls import path
urlpatterns = [
path('', views.index, name='index'),
path('extensions/', views.ExtensionListView.as_view(), name='extensions'),
path('extension/<str:pk>', views.ExtensionDetailView.as_view(), name='extension-detail'),
path('extension/create/', views.ExtensionCreate.as_view(), name='extension-create'),
path('extension/<str:pk>/update/', views.ExtensionUpdate.as_view(), name='extension-update'),
path('extension/<str:pk>/delete/', views.ExtensionDelete.as_view(), name='extension-delete'),
path('myextensions/', views.ExtensionsByUserListView.as_view(), name='my-extensions'),
path('myextension/<str:pk>', views.ExtensionsByUserDetailView.as_view(), name='my-extension-detail'),
path('contexts/', views.ContextListView.as_view(), name='contexts'),
path('context/<str:pk>', views.ContextDetailView.as_view(), name='context-detail'),
path('context/create/', views.ContextCreate.as_view(), name='context-create'),
path('context/<str:pk>/update/', views.ContextUpdate.as_view(), name='context-update'),
path('context/<str:pk>/delete/', views.ContextDelete.as_view(), name='context-delete'),
path('mycontexts/', views.ContextByUserListView.as_view(), name='my-contexts'),
path('mycontext/<str:pk>', views.ContextByUserDetailView.as_view(), name='my-context-detail'),
]
template:
{% extends "base_generic.html" %}
{% block content %}
<form action="" method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit">
</form>
{% endblock %}
In this is how it looks like:
The Username is always the same as one of the contexts.
Only Staff User can create a new Context and new Users.
The users then should add their extensions.
While employees should be able to select the context when creating a new extension, customers should only be able to see or select their context in the list.
Therefore it is needed to filter the Select-attribute for non-staff members so that only the user's context is visible, which is equal to his Username.
Alternatively, I want to prepopulate and hide the context form field with the Username (=own context)
How can I do either of this in the easiest way possible?
Here is what I tried myself so far:
Like described in this how-to: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Forms#Renew-book_form_using_a_Form_and_function_view I Defined a Form in forms.py:
#!/usr/bin/python3
from django import forms
class MyExtensionCreateForm(forms.Form):
# username = forms.CharField(help_text="")
# callerid = forms.CharField(help_text="")
# context = forms.CharField(help_text="")
firstname = forms.CharField(help_text="")
lastname = forms.CharField(help_text="")
extension = forms.CharField(help_text="")
password = forms.CharField(help_text="")
def clean_data(self):
data = self.cleaned_data
# Remember to always return the cleaned data.
return data
I then added the folowing to the views.py:
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.urls import reverse
from catalog.forms import MyExtensionCreateForm
def MyExtensionCreate(request):
# extension = get_object_or_404(Extension)
# If this is a POST request then process the Form data
if request.method == 'POST':
# Create a form instance and populate it with data from the request (binding):
form = MyExtensionCreateForm(request.POST)
# Check if the form is valid:
if form.is_valid():
# process the data in form.cleaned_data as required
form.firstname = form.cleaned_data['firstname']
form.lastname = form.cleaned_data['lastname']
form.extension = form.cleaned_data['extension']
form.password = form.cleaned_data['password']
# Prepopulated Fields
form.context = request.user
form.callerid = str(form.cleaned_data['firstname'])+" "+str(form.cleaned_data['lastname'])+" "+str(form.cleaned_data['extension'])
form.username = str(request.user)+"_"+str(form.cleaned_data['extension'])
form.save()
# redirect to a new URL:
return HttpResponseRedirect(reverse('my-extensions'))
# If this is a GET (or any other method) create the default form.
else:
form = MyExtensionCreateForm({'context': request.user})
context = {
'form': form,
}
return render(request, 'catalog/extension_form-by-user.html', context)
# class MyExtensionCreate(LoginRequiredMixin, CreateView):
# model = Extension
# fields = '__all__'
# form_class = MyExtensionCreateForm
Then I added a new URL to URL patterns in urls.py and added the new Link to the base_generic.html
path('myextensions/create/', views.MyExtensionCreate, name='my-extension-create'),
<li>Add Extension</li>
I can view the form, and if I add the context field to the visible form fields, I can see that the context will initially fill with the logged-in username (See First Picture Below). But as soon as I submit the form I'll get Error's no matter what I try, So basically the GET is working, but the POST isn't really.
See Folowing Pictures:
I was able to Filter the Choices by the Username in the ModelForm but since then I'm not able to save the form to the database anymore.
Here is the new Stack Post with the Resolution of this Post here and the new Question/Problem.
Django: saving the Form does not work (The ModelForm Filters the ForeignKey choices by request.user)

Fixed a bug of views django: Page not found

My english is not good !
I have tried many ways but still get error: page not found.
File views.py:
def create_article(request, template_name='vlogntruong/create_article.html'):
if request.method == "POST":
create_form = VlogForm(request.POST)
if create_form.is_valid():
new_article = create_form.save()
return HttpResponeRedirect(new_article.get_absolute_url())
else:
create_form = VlogForm(request)
template_context = {
'create_form': create_form,
}
return render_to_response(
template_name,
template_context,
RequestContext(request)
)
File forms.py
from django import forms
from .models import VlogNTruong
class VlogForm(forms.Form):
title= forms.CharField(max_length=100,
widget=forms.TextInput(attrs={'size':50}))
name = forms.CharField(max_length=50,
widget = forms.TextInput(attrs={'size':50}))
sumary = forms.CharField(widget = forms.Textarea(attrs={"rows":10, "cols":80}))
content = forms.CharField(widget = forms.Textarea(attrs={"rows":20, "cols":80}))
video = forms.CharField(required = False,
widget = forms.TextInput(attrs={'size':60}))
def save(self):
create_form = VlogNTruong(title = self.cleaned_data['title'],
name = self.cleaned_data['name'],
sumary = self.cleaned_data['content'],
content = self.cleaned_data['content'],
video = self.cleaned_data['video'])
create_form.save()
return create_form
File models.py:
from django.db import models
from django.db.models import permalink
from embed_video.fields import EmbedVideoField
from django.template.defaultfilters import slugify
from django.contrib import admin
import datetime
class VlogNTruong (models.Model):
title = models.CharField(max_length=100)
slug_field = models.TextField(null=True, blank=True)
name = models.CharField(max_length=50)
sumary = models.TextField()
content = models.TextField()
time_create = models.DateTimeField(auto_now_add=True)
video = EmbedVideoField(null=True, blank=True)
class Meta:
ordering = ('-time_create',)
def __unicode__(self):
return "%s" % self.title
#permalink
def get_absolute_url(self):
return ('vlogntruong.views.article_detail', [self.slug_field])
def save(self, *args, **kwargs):
if not self.slug_field:
self.slug_field = slugify(self.title)
super(VlogNTruong, self).save(*args, **kwargs)
file html
{% extends 'vlogntruong/base.html' %}
{% block panel_content %}
<form action="/" method="post">{% csrf_token %}
<table>
{{form.as_table}}
</table>
<input type="submit" name="Create" />
</form>
{% endblock %}
file urls
urlpatterns = patterns('vlogntruong.views',
url(r'^$', 'list_article',
{'template_name':'vlogntruong/list_article.html'}),
url(r'^(?P<slug_field>[-\w\d]+)/$', 'article_detail'),
url(r'^create/$', 'create_article'),
)
Help me
Error
Page not found (404)
Request Method: GET
Request URL: /nhuttruong/create/
No VlogNTruong matches the given query.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
Your problem is that your save() method in your form is not returning the object it creates in the database, it is returning the unsaved instance, for which you are trying to get the redirect url.
I would suggest you read the modelforms guide to help you along.
Your form should look like this:
from django import forms
from .models import VlogNTruong
class VlogForm(forms.ModelForm):
title= forms.CharField(max_length=100,
widget=forms.TextInput(attrs={'size':50}))
name = forms.CharField(max_length=50,
widget = forms.TextInput(attrs={'size':50}))
sumary = forms.CharField(widget = forms.Textarea(attrs={"rows":10, "cols":80}))
content = forms.CharField(widget = forms.Textarea(attrs={"rows":20, "cols":80}))
video = forms.CharField(required = False,
widget = forms.TextInput(attrs={'size':60}))
class Meta:
model = VlogNTruong
Then, in your views, you need to adjust it like this:
from django.shortcuts import render
def create_article(request, template_name='vlogntruong/create_article.html'):
create_form = VlogForm(request.POST or None)
if create_form.is_valid():
new_article = create_form.save()
return HttpResponeRedirect(new_article.get_absolute_url())
template_context = {'create_form': create_form,}
return render(request, template_name, template_context)
You also need to make sure that the VlogNTruong model has a get_absolute_url method which returns a URL. Your method just returns a tuple, fix it like this:
def get_absolute_url(self):
from django.core.urlresolvers import reverse
return reverse('vlogntruong.views.article_detail', args=[self.slug_field])
Finally your __unicode__ method must return a unicode object, yours is returning a string:
def __unicode__(self):
return unicode('{}'.format(self.title))
The regular expression that you are using in the third url() does not match with the requested URL:
r'^create/$' will not match '/nhuttruong/create/'
To achieve your objective you should use something like r'.+/create/$'

Categories

Resources