1- Title link not working. When I click on the link it stays on the same page.
2- Create post not working. I get this error when I press the submit button.
Error message: AttributeError at /post/create/
'Post' object has no attribute 'get_absolute_url'
urls.py
from django.urls import path
from .import views
app_name='post'
urlpatterns = [
path('index/',views.post_index, name='index'),
path('<int:id>/detail',views.post_detail, name='detail'),
path('create/',views.post_create, name='create'),
path('<int:id>/update/',views.post_update, name='update'),
path('delete/',views.post_delete, name='delete'),
]
models.py
from django.db import models
from django.urls import reverse
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=120, verbose_name="Başlık")
content = models.TextField(verbose_name="İçerik")
publishing_date = models.DateTimeField(verbose_name="Yayımlanma Tarihi", auto_now_add=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post:detail', kwargs={'id': self.id})
#return "/post/{}".format(self.id)
views.py
from django.shortcuts import render, get_object_or_404, HttpResponseRedirect
from django.http import HttpResponse
from .models import Post
from .forms import PostForm
def post_index(request):
posts = Post.objects.all()
return render(request, 'post/index.html', {'posts': posts})
def post_detail(request, id):
post = get_object_or_404(Post, id=id)
context = {
'post': post,
}
return render(request, 'post/detail.html', context)
def post_create(request):
#if request.method == "POST":
#print(request.POST)
#title = request.POST.get('title')
#content = request.POST.get('content')
#Post.objects.create(title=title, content=content)
#if request.method == "POST":
#Formdan gelen bilgileri kaydet
#form = PostForm(request.POST)
#if form.is_valid():
#form.save()
#else:
#Formu kullanıcıya göster
#form = PostForm()
form = PostForm(request.POST or None)
if form.is_valid():
post = form.save()
return HttpResponseRedirect(post.get_absolute_url())
context = {
'form': form,
}
return render(request, 'post/form.html', context)
def post_update(request, id):
post = get_object_or_404(Post, id=id)
form = PostForm(request.POST or None, instance=post)
if form.is_valid():
form.save()
return HttpResponseRedirect(post.get_absolute_url())
context = {
'form': form,
}
return render(request, 'post/form.html', context)
def post_delete(request):
return HttpResponse("Burası Post delete sayfası")
index.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
{% for post in posts %}
{{post.id}}<br>
{{post.title}}<br>
{{post.content}}<br>
{{post.publishing_date}}<br>
{% endfor %}
</body>
</html>
Create post form:
forms.py
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = [
'title',
'content',
]
form.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form method="POST">
{% csrf_token %}
<h1>Form</h1>
{{form.as_p}}
<input type="submit" value="Gönder">
</form>
</body>
</html>
You have an identation problem on your Post model
from django.db import models
from django.urls import reverse
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=120, verbose_name="Başlık")
content = models.TextField(verbose_name="İçerik")
publishing_date = models.DateTimeField(verbose_name="Yayımlanma Tarihi", auto_now_add=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post:detail', kwargs={'id': self.id})
#return "/post/{}".format(self.id)
Related
I'm new to Django. I 'm trying to practice create Raw Update Class Based View but it get in to error Method Not Allowed (POST). Can any one help me please.
I already follow the instruction step by step but the result is the same. I also try a lot of method to fix but still can't. I really want to know what is the problem. I very appreciate for someone help me fix this.
view.py
from django.shortcuts import render, get_object_or_404
from django.views import View
from .models import Client
from .forms import ClientFrom
class ClientUpdateView(View):
template_name = "clients/client-update.html"
def get_object(self):
id = self.kwargs.get('id')
obj = None
if id is not None:
obj = get_object_or_404(Client, id=id)
return obj
def get(self, request, id=None, *args, **kwargs):
#GET Method
context = {}
obj = self.get_object()
if obj is not None:
form = ClientFrom(instance=obj)
context['object'] = obj
context['form'] = form
return render(request, self.template_name, context)
def post(self, request, id=None, *args, **kwargs):
#POST Method
context = {}
obj = self.get_object()
if obj is not None:
form = ClientFrom(request.POST, instance=obj)
if form.is_valid():
form.save()
context['object'] = obj
context['form'] = form
return render(request, self.template_name, context)
forms.py
from django import forms
from .models import Client
class ClientFrom(forms.ModelForm):
class Meta:
model = Client
fields = [
'Name',
'Address',
'Contact',
]
form in client-update.html
{% extends 'clienthead.html' %}
{% block content %}
<h1>Update: {{object.id}} - {{ object.Name }}</h1>
<form action='.' method='POST'> {% csrf_token %}
{{ form.as_p }}
<input type='submit' value='Save' />
</form>
{% endblock %}
urls.py
from django.urls import path
from .views import (
ClientUpdateView,
)
app_name = 'client'
urlpatterns = [
path('<int:id>/adjust', ClientUpdateView.as_view(), name='client-adjust'),
]
I am having this error any time i want to view posts that belong to a group
NoReverseMatch at /groups/posts/in/python/
Reverse for 'user-posts' with keyword arguments '{'username': ''}' not found. 1 pattern(s) tried: ['user/(?P<username>[^/]+)$']
Following is my urls.py codes
from django.urls import path
from .views import (PostListView, PostCreateView,
PostUpdateView, PostDetailView, PostDeleteView, UserPostListView)
from . import views
app_name = 'posts'
urlpatterns = [
path('', PostListView.as_view(), name="blog-home"),
path('user/<str:username>', UserPostListView.as_view(), name="user-posts"),
path('post/<int:pk>/', PostDetailView.as_view(), name="post-detail"),
path("post/<int:pk>/", views.post_comment, name="comments"),
path('post/new/', PostCreateView.as_view(), name="post-create"),
path('post/<int:pk>/update', PostUpdateView.as_view(), name="post-update"),
path('post/<int:pk>/delete', PostDeleteView.as_view(), name="post-delete"),
path('about/', views.about, name="blog-about"),
]
The problem seems to be coming from my _posts.html file, but I cant resolve it.
here is the _posts.html codes
<div class="media">
<h3 class="mr-5">#{{ post.user.username }}</h3>
<div class="media-body">
<strong>{{ post.user.username }}</strong>
<h5>{{ post.message_html|safe }}</h5>
<time class="time">{{ post.created_at }}</time>
{% if post.group %}
<span class="group-name">in {{ post.group.name }}</span>
{% endif %}
</h5>
<div class="media-footer">
{% if user.is_authenticated and post.user == user and not hide_delete %}
<a href="{% url 'posts:post-delete' pk=post.pk %}" title="delete" class="btn btn-simple">
<span class="fa fa-remove text-danger" aria-hidden="true"></span>
<span class="text-danger icon-label">Delete</span>
</a>
{% endif %}
</div>
</div>
</div>
Once I click on the group's list page to take me to posts associated with the group, I get the above error.
Someone said the username I am passing to the urls.py is empty, i cant figure out what is wrong with code from my views.py
from django.contrib import messages
from django.contrib.auth.mixins import (LoginRequiredMixin, UserPassesTestMixin)
from django.contrib.auth.models import User
from django.urls import reverse_lazy, reverse
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import (ListView, DetailView, CreateView,
UpdateView, DeleteView)
from .models import Post, Comment
from django.core.files.storage import FileSystemStorage
from .forms import CommentForm, PostForm
from . import models
def home(request):
context = {
'posts': Post.objects.all()
}
return render(request, 'blog/home.html', context)
def upload(request):
if request.method == 'POST':
form = PostForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('post_detail')
else:
form = PostForm()
return render(request, 'blog/post_detail.html',
{'form': form })
class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 6
class UserPostListView(ListView):
model = Post
template_name = 'blog/user_posts.html'
context_object_name = 'posts'
paginate_by = 6
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get('username'))
return Post.objects.filter(author=user).order_by('-date_posted')
class PostDetailView(DetailView):
model = Post
def post_comments(request, slug):
template_name = 'blog/post_detail.html'
post = get_object_or_404(Post, slug=slug)
comments = post.comments.filter(active=True)
new_comment = None
# Comment posted
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object but don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
return render(request, template_name, {'post': post,
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form})
class PostCreateView(LoginRequiredMixin, CreateView):
model = models.Post
fields = ['title', 'content', 'group', 'image']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Post
fields = ['title', 'content']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
model = Post
success_url = reverse_lazy('blog-home')
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
def about(request):
return render(request, 'blog/about.html', {'title': 'About'})
There is nothing wrong with your urls.py and template. The problem is with '{'username': ''}' because username is empty it won't match with the regex(user/(?P<username>[^/]+)$). try to find out why username is empty.
so i made it that my books will show in my admin but i dont know how to order the books(in the admin) by votes and not by last voted. I found some answers here on overflow but i wasnt able to integrate them by myself. Here are my files:
admin.py
from django.contrib import admin
from .models import Vote
admin.site.register(Vote)
apps.py
from django.apps import AppConfig
class SurveyConfig(AppConfig):
name = 'survey'
forms.py
from django import forms
from .models import Vote
class VotingForm(forms.Form):
chosen_books_options = forms.MultipleChoiceField(choices=[], label='Book Name', required=False,
widget=forms.SelectMultiple(
attrs={
'class': 'form-control'
}
))
other_book_name = forms.CharField(label='Other', max_length=100, required=False,
widget=forms.TextInput(
attrs={
'class': 'form-control',
'placeholder': 'Did we miss something?'
}
))
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
unique_books_names = Vote.objects.order_by('book_name').values_list('book_name', flat=True).distinct()
self.fields['chosen_books_options'].choices = [(book_name, book_name) for book_name in unique_books_names]
models.py
from django.db import models, transaction
class Vote(models.Model):
book_name = models.CharField(max_length=200)
count = models.IntegerField(default=0)
def __str__(self):
return '%s: %d votes' % (self.book_name, self.count)
#classmethod
def bulk_vote(cls, book_names):
with transaction.atomic():
for book_name in book_names:
if len(book_name) == 0:
continue
if Vote.objects.filter(book_name=book_name).exists():
Vote.objects.filter(book_name=book_name).update(count=models.F('count') + 1)
else:
Vote.objects.create(book_name=book_name, count=1)
views.py
from django.shortcuts import render
from .forms import VotingForm
from .models import Vote
def index(request):
if request.method == 'POST':
form = VotingForm(request.POST)
if form.is_valid():
chosen_books_options = form.cleaned_data.get('chosen_books_options', [])
other_book_name = form.cleaned_data.get('other_book_name', '')
Vote.bulk_vote(chosen_books_options + [other_book_name])
message = 'Thank You For Your Contribution!'
elif request.method == 'GET':
message = ''
form = VotingForm()
return render(request, 'templates/survey.html', {'form': form, 'message': message})
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<title>Document</title>
<style>
.form-control{
width: 50%;
}
</style>
</head>
<body>
<div class="container" id="thisone">
<h3>Select which books you'd like us to get started with.</h3>
<h5>{{ message }}</h5>
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
thank you for reading
note: this is not fully my code
Within your admin, you can use the ordering attribute like so...
from django.contrib import admin
from .models import Vote
class VoteAdmin(admin.ModelAdmin):
ordering = ('count',)
admin.site.register(Vote, VoteAdmin)
I have used django's models and forms to add a comment section to a blog app, however the form's text field will not show when loaded in the in the browser when i try to add a comment to a post. Only the submit button and the title is visible with no textfield to submit with.
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=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments')
author = models.CharField(max_length=200)
created_date = models.DateTimeField(default=timezone.now)
text = models.TextField()
def __str__(self):
return self.text
forms.py
from django import forms
from .models import Post, Comment
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'text')
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('author', 'text',)
views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_list_or_404, get_object_or_404, redirect
from django.utils import timezone
from blog.forms import PostForm
from .models import Post, Comment
from .forms import PostForm, CommentForm
# Create your views here.
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
stuff_for_frontend = {'posts': posts}
return render(request, 'blog/post_list.html', stuff_for_frontend)
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
stuff_for_frontend = {'post': post}
return render(request, 'blog/post_detail.html', stuff_for_frontend)
#login_required
def post_new(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
stuff_for_frontend = {'form': form}
return render(request, 'blog/post_edit.html', stuff_for_frontend)
def post_edit(request, pk):
post = get_list_or_404(Post, pk=pk)
if request.method == 'POST':
# updating existing form
form = PostForm(request.POST, instance=post)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm(instance=post)
stuff_for_frontend = {'form': form, 'post': post}
return render(request, 'blog/post_edit.html', stuff_for_frontend)
#login_required
def post_draft_list(request):
posts = Post.objects.filter(published_date__isnull=True).order_by('-created_date')
stuff_for_frontend = {'posts': posts}
return render(request, 'blog/post_drafts_list.html', stuff_for_frontend)
#login_required
def post_publish(request, pk):
post = get_object_or_404(Post, pk=pk)
post.publish()
return redirect('post_detail', pk=pk)
def add_comment_to_post(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.author = request.user
comment.post = post
comment.save()
return redirect('post_detail', pk=post.pk)
else:
form = CommentForm()
return render(request, 'blog/add_comment_to_post.html', {form: 'form'})
def comment_remove(request, pk):
comment = get_object_or_404(Comment, pk=pk)
comment.delete()
return redirect('post_detail', pk=comment.post.pk)
Add Comment HTML
{% extends 'blog/base.html' %}
{% block title %} Add Comment {% endblock %}
{% block content %}
<h1>New Comment</h1>
<form method="POST" class="post-form-blog">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Post</button>
</form>
{% endblock %}
enter image description here
I think you just mixed up two items in this line:
return render(request, 'blog/add_comment_to_post.html', {form: 'form'})
It should be
return render(request, 'blog/add_comment_to_post.html', {'form': form})
i am new to django when i try to run this project i wasn't getting any input fields in my template current page was only showing the given labels
i don't know where i've gone wrong
can any of you guys help??
these are my models.py file
from django.db import models
# Create your models here.
class Student(models.Model):
sid = models.CharField(max_length=100)
sname = models.CharField(max_length=100)
sclass = models.CharField(max_length=100)
semail = models.EmailField(max_length=100)
srollnumber = models.CharField(max_length=100)
scontact = models.CharField(max_length=100)
saddress = models.CharField(max_length=100)
class Meta:
db_table = "student"
the are my forms.py file
from django import forms
from student.models import Student
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = "__all__"
these are my views.py file
from django.shortcuts import render
from student.models import Student
from student.forms import StudentForm
def student_home(request):
return render(request, 'employee/dash.html')
def add_student(request):
if request.method == "POST":
form = StudentForm(request.POST)
if form.is_valid():
try:
form.save()
return render(request, 'employee/dash.html')
except:
pass
else:
form = StudentForm()
return render(request, 'student/addstudent.html')
template
<!DOCTYPE html>
<html lang="en">
<head>
<title>addstudent</title>
</head>
<body>
<a href="/home" >home</a>
<form method="POST" action="/add_student">
{% csrf_token %}
<label>Student ID:</label>
{{ form.sid }}
<label>Name :</label>
{{ form.sname }}
<label>Class :</label>
{{ form.sclass }}
<label>Email ID:</label>
{{ form.semail }}
<label>Roll Number :</label>
{{ form.srollnumber }}
<label>Contact :</label>
{{ form.scontact }}
<label>Address :</label>
{{ form.saddress }}
<button type="submit">Submit</button>
</form>
</body>
</html>
You forget to give the context to the render function:
return render(request, 'student/addstudent.html',context={'form':form})
should work
You have not included any context in your render functions. Your view should be:
def add_student(request):
if request.method == "POST":
form = StudentForm(request.POST)
if form.is_valid():
try:
form.save()
return render(request, 'employee/dash.html', context={'form': form})
except:
pass
else:
form = StudentForm()
return render(request, 'student/addstudent.html', context={'form': form})