how to use slug to form urls - python

my models.py file looks like this
from django.db import models
from django.template.defaultfilters import slugify
class Entertainmentblog(models.Model):
slug = models.SlugField(max_length=100)
body = models.TextField()
posted = models.DateTimeField('date published')
img_url0 = models.CharField(max_length=100)
img_alt0 = models.CharField(max_length=100)
title1 = models.CharField(max_length=100)
title2 = models.CharField(max_length=100)
def save(self):
super(Entertainmentblog, self).save()
self.slug = '%i-%s' % ( self.id, slugify(self.slug) )
super(Entertainmentblog, self).save()
And my app urls.py file looks like this
from django.conf.urls import patterns, url
from entertainment import views
urlpatterns = patterns('',
url(r'^$', views.ListView.as_view(), name='index'),
url(r'^(?P<slug>[^\.]+),(?P<id>\d+)/$', views.DetailView.as_view(), name='article'),
)
But this gives an error.
Exception Value: Reverse for 'article' with arguments '(u'what-is-happening',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'entertainment/(?P[^\.]+),(?P\d+)/$']
My view.py file
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from entertainment.models import Entertainmentblog
class ListView(generic.ListView, slug, id):
template_name = 'entertainment/index.html'
context_object_name = 'latest_article_list'
def get_queryset(self):
return Entertainmentblog.objects.order_by('-posted')[:25]
class DetailView(generic.DetailView):
model = Entertainmentblog
template_name = 'entertainment/article.html'
How do I correct this?

Oh, there is serious problems with your views:
First:
class ListView(generic.ListView, slug, id)
should be
class ListView(generic.ListView)
see python inheritance.
Second:
slug and id must be class members of your view so you can redefine you view like this:
class ListView(generic.ListView):
template_name = 'entertainment/index.html'
context_object_name = 'latest_article_list'
slug = None
id = None
def get_queryset(self):
return Entertainmentblog.objects.order_by('-posted')[:25]
Third:
Youre naming a derivate class as its parent. I don't know the implications of doing this, but surely, isn't a good practice.
Finally:
The error you're getting is becouse the view returned by views.DetailView.as_view() (remember DetailView is your derived class) don't receives the arguments you are passing through url. Check your url, I can see in the error that is complaining about and argument (u'what-is-happening',) but there is no id. It should be something like, for example, (u'what-is-happening', '4')

Related

How to resolve Django IntegrityError NOT NULL Constraint Field?

I'm building an online judge in which I have a Question model and an Answer model.
models.py
from django.db import models
from django.core.validators import FileExtensionValidator
from django.urls import reverse
class Question(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
solution = models.FileField(
validators=[FileExtensionValidator(allowed_extensions=['txt'])], upload_to= 'media')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('coder:detail', kwargs={'pk': self.pk})
class Answer(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
result = models.CharField(max_length=100,default = 'answer', null = True, blank = True)
# result = models.FileField( null= True, blank=True, default = 'media/media/output.txt',
# validators=[FileExtensionValidator(allowed_extensions=['txt'])], upload_to= 'media')
def __str__(self):
return f'{self.question.title} Answer'
def get_absolute_url(self):
return reverse('coder:detail', kwargs={'pk': self.pk})
views.py
from django.shortcuts import get_object_or_404, render
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import ListView, DetailView, CreateView, UpdateView, RedirectView
from django.db.models import Q
from .models import Question, Answer
class CoderListView(ListView):
model = Question
template_name = "coder/coder_list.html"
context_object_name = 'question'
class CoderDetailView(DetailView):
model = Question
template_name = "coder/coder_detail.html"
class CoderCreateView(CreateView):
model = Answer
fields = ['result']
context_object_name = 'answer'
success_url = reverse_lazy('coder:list')
template_name = "coder/coder_form.html"
def form_valid(self, form):
return super().form_valid(form)
What exactly am I doing wrong here?
I was trying out FileField earlier but when I kept getting an error, I tried CharField after flushing the database to debug further but I kept getting this error:
And yes, I did try out setting null, blank, and default values appropriately but still no luck. Maybe something to do with a signals.py file? Or maybe I'm implementing the Foreign key wrong, whatever it is that I'm doing wrong I'm unable to point out at the moment. Help with that would be appreciated.
This page is using CoderCreateView.
I believe this is what caused the problem:
class CoderCreateView(CreateView):
model = Answer
fields = ['result']
context_object_name = 'answer'
For the answer model, you forget to pass in the primary key/object (whichever way you prefer) of the question that the answer is linked to, as in this line in your models.py:
question = models.ForeignKey(Question, on_delete=models.CASCADE)

URL Redirection is not working (Django 3.0)

I am the newbie of writing programming, now I am learning django.
I have a problem for URL redirection. I create the model and it does work at admin site.
Also I set the PK for each article, that successfully generate the URL by PK.
However when I post the message form the front-end, after posting it appear the error message suppose it should be redirect to the page of DetailViewand
I have imported the reverse function in my model, but it seem not working.
My python version : 3.7.6 and django version : 3.0.0
ImproperlyConfigured at /add/
No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.
My View
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView
from .models import Page
class PageListView(ListView):
model = Page
template_name='home.html'
context_object_name = 'all_post_list'
class PageDetailView(DetailView):
model = Page
template_name='post.html'
class PageCreateView(CreateView):
model = Page
template_name='post_new.html'
fields = ['title', 'author', 'body', 'body2']
Model
from django.urls import reverse
from django.db import models
from ckeditor.fields import RichTextField
class Page(models.Model):
title = models.CharField(max_length=50)
author = models.ForeignKey(
'auth.User',
on_delete=models.CASCADE,
)
body = RichTextField()
body2 = models.TextField()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post', args=[str(self.id)])
URL
from django.urls import path
from .views import PageListView, PageDetailView, PageCreateView
urlpatterns = [
path('add/', PageCreateView.as_view(), name='post_new'),
path('', PageListView.as_view(), name='home'),
path('blog/<int:pk>/', PageDetailView.as_view(), name='post'),
]
Thanks for helping. :)
I think your indentation is the problem here. Fix it by:
class Page(models.Model):
title = models.CharField(max_length=50)
author = models.ForeignKey(
'auth.User',
on_delete=models.CASCADE,
)
body = RichTextField()
body2 = models.TextField()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post', args=[self.id])

I have a problem with my Django URL pattern naming

For whatever reason when I give a name="..." - argument to a URL pattern and I want to refer to it by using the name it does not seem to work.
That's my 'webapp/urls.py' file:
from django.urls import path
from .views import PostListView, PostDetailView, PostCreateView
from .import views
app_name = 'webapp'
urlpatterns = [
path("", PostListView.as_view(), name="webapphome"),
path("post/<int:pk>/", PostDetailView.as_view(), name="postdetail"),
path('post/new/', PostCreateView.as_view(), name="postcreate"),
path("about/", views.About, name="webappabout"),
]
And that's my 'webapp/views.py' file:
from django.shortcuts import render
from django.views import generic
from django.views.generic import ListView, DetailView, CreateView
from .models import Post
def Home(request):
context = {
'posts': Post.objects.all() }
return render(request, "webapp/home.html", context)
class PostListView(ListView):
model = Post
template_name = 'webapp/home.html'
context_object_name = 'posts'
ordering = ['-date']
class PostDetailView(DetailView):
model = Post
template_name = 'webapp/detail.html'
class PostCreateView(CreateView):
model = Post
fields = ['title', 'content']
template_name = 'webapp/postform.html'
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def About(request):
return render(request, "webapp/about.html", {'title': 'About'})
And that's my 'webapp/models.py' file:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=50)
content = models.TextField(max_length=300)
date = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("postdetail", kwargs={'pk': self.pk})
As you can see, I'm using the name 'postdetail' I've given to the URL path from PostDetailView but however I receive an Error like this when I create a new Post:
NoReverseMatch at /post/new/
Reverse for 'postdetail' not found. 'postdetail' is not a valid view function or pattern name.
Request Method: POST
Exception Type: NoReverseMatch
I'd suggest you read the Namespace section in Django Documentation, here
The issue is due to you having an app_name = 'webapp' but not using it with postdetail
The objective of app_name is to ensure you know where to redirect if you have two url in different apps with same names.
change
return reverse("postdetail", kwargs={'pk': self.pk})
to
return reverse("webapp:postdetail", kwargs={'pk': self.pk})

Improperly configured django error

I have a simple django project and whenever i run it, it gives me an improperly configured error. Tells me my model is missing a query set:
Improperly Configured Error Image
Here's the code for my views.py. The functionality doesn't matter for now:
import random
from django.shortcuts import render
from django.http import HttpResponse
from django.views import View
from django.views.generic import TemplateView
from django.views.generic.list import ListView
class RestaurantList(ListView):
querySet = Restaurant.objects.all()
template_name = 'restaurants/restaurants_list.html'
class SpicyList(ListView):
template_name = 'restaurants/restaurants_list.html'
querySet = Restaurant.objects.filter(category__iexact='spicy')
class AsianList(ListView):
template_name = 'restaurants/restaurants_list.html'
querySet = Restaurant.objects.filter(category__iexact='asian')
Here's the code for my models.py
from django.db import models
class Restaurant(models.Model):
name = models.CharField(max_length=120)
loocation = models.CharField(max_length=120, null=True, blank=True)
category = models.CharField(max_length=120, null=True, blank=False)
timestamp = models.DateTimeField(auto_now=True)
updated = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
urls.py code:
from django.contrib import admin
from django.conf.urls import url
from django.views.generic import TemplateView
from restaurant.views import *
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', TemplateView.as_view(template_name='home.html')),
url(r'^restaurants/$', RestaurantList.as_view()),
url(r'^restaurants/asian/$', AsianList.as_view()),
url(r'^restaurants/spicy/$', SpicyList.as_view()),
url(r'^Contact/$', TemplateView.as_view(template_name='Contact.html')),
url(r'^About/$', TemplateView.as_view(template_name='About.html'))
]
It's only the urls containing 'restaurants' that give me this error. The rest are fine.
Here's a picture of my file structure at the side
File Structure
The queryset attribute should be lower case at all.
all your views contain querySet
replace them by queryset lower case
Or you can provide the model attribute model = ModelName
See more In the Official Documentation

AttributeError at /app/api/get

I got an error,
AttributeError at /app/api/get
Got AttributeError when attempting to get a value for field task_name on serializer TaskSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the Color instance.
Original exception text was: 'Color' object has no attribute 'task_name'.
Now I wanna make a page that shows model's content in json format.
models.py is
from django.db import models
# Create your models here.
class Color(models.Model):
name = models.CharField(max_length=255)
background_color = models.CharField(max_length=255)
h1_color = models.CharField(max_length=255)
p_color = models.CharField(max_length=255)
def __str__(self):
return self.name
serializers.py is
from .models import Color
from rest_framework import serializers
class TaskSerializer(serializers.Serializer):
task_name = serializers.CharField(max_length=100)
status = serializers.SerializerMethodField('get_task_status')
def get_task_status(self, instance):
return instance.status.status
class Meta:
model = Color
fields = ('name',
'background_color',
'h1_color',
'p_color',
'task_name')
urls.py is
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'api/get',views.TaskGet.as_view(),name='task-get')
]
views.py is
from django.shortcuts import render
from .models import Color
from .forms import ColorForm
from .serializers import TaskSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
# Create your views here.
def index(request):
d = {
'colors': Color.objects.all(),
'form': ColorForm(),
}
return render(request, 'index.html', d)
class TaskGet(APIView):
def get(self, request, format=None):
obj = Color.objects.all()
serializers = TaskSerializer(obj, many=True)
return Response(serializers.data, status.HTTP_200_OK)
I wrote url(r'api/get',views.TaskGet.as_view(),name='task-get') in urls.py,so I really cannot understand why this error happens.I already run commands of migration of model. How can I fix this?
My ideal web page is like
You try get status by foreign key instance.status.status but in your model class Color i don't see any foreign keys or methods for it.
And for task_name did you want to see the model field name try to add source params
task_name = serializers.CharField(max_length=100, source='name')
# ^^^^^^^^^
are you sure you want serialize Task for model Color?
new edit
in your get_task_status the 'instanceis instance of serializer model, so if your modelColorhas no property or methodstatus` you will catch an error

Categories