Problam with views and template in Django - show data in template - python

I have a problam in Django. I'm a amature Django developer. I can't show my "Category" data in Template. here is my code :
models.py
from django.db import models
from taggit.managers import TaggableManager
class Category(models.Model):
title = models.CharField(max_length=40)
def __unicode__(self):
return self.title
class Post (models.Model):
title = models.CharField(max_length=150)
body = models.TextField()
date = models.DateTimeField()
tags = TaggableManager ()
cats = models.ManyToManyField(Category)
def __unicode__ (self):
return self.title
views.py
from django.shortcuts import render
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
from blog.models import Category
render(request, 'index.html', args)
def cats(request):
t = get_template('category.html')
for i in Category.object.get :
html = t.render(Context({'cat': i}))
return HttpResponse(html)
urls.py
from django.conf.urls import include, url, patterns
from django.views.generic import ListView, DetailView
from blog.models import Post, Category
urlpatterns = patterns('blog.views',
url(r'^$',ListView.as_view(
queryset = Post.objects.all().order_by("-date")[:2],
template_name="index.html")),
url(r'^(?P<pk>\d+)$',DetailView.as_view(
model = Post,
template_name="post.html")),
url(r'^(?P<pk>\d+)$','cats'),
)
A part of template "post.html"
#some html code here
{% include "category.html" %}
#another some html code here
This is my category.html
<li>{{cat}}</li>
Thank you.

Your way of writing code is not quite correct. Views are meant for backend codes, urls.py is meant only for url specifications not for writing queries.
views.py
from blog.models import Category
from blog.models import Post
def cats(request):
queryset = Post.objects.all().order_by("-date")[:2]
return render_to_response('category.html',{'queryset': queryset},
context_instance=RequestContext(request))
add this in urls.py
url(r'^cats', 'blog.views.cats', name='cats')
In category.html you can access any field of the object that is passed from views.py (here queryset )
<li>{{querset.title}}</li>

Related

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

[Django]How to get the str(id) of a ModelA object in order to give the source code of a page as initial value of a CharField that belongs to a ModelB?

I started to code a two-apps django project. ModelA belongs to appone and ModelB belongs to apptwo. My purpose is to create a ModelA instance everytime that the user creates a ModelB instance. And the value of a ModelA CharField (that is ckeditor widgeted) must be the source code of a ModelB admin view. I used a post_data signal to link a function of creation for that. The problem is that i use the id of each instance of ModelB in order to create the good content for each instance of ModelA. When I try to use a string of the url sending the id parameter, the content field has for value the source code of the debug page
(error 500, DoesNotExist at /admin/apptwo/modelb/my_view/ref=76, [76 is an example] ModelB matching query does not exist. Exception location : /home/me/Desktop/env/lib/python3.5/site-packages/django/db/models/query.py in get, line 385)
But when I try to visit the url "http://localhost:8000//admin/apptwo/modelb/my_view/ref=76", or when I hardcode the url, without a str(instance.id), the page exists and everything works perfectly.
I don't understand why.
Could anybody give me some help to solve this problem ?
Thanks in advance,
PS :
The first app has a model.py that contains the following code :
from django.db import models
from django.contrib.auth.models import User
from registre.models import *
class ModelA(models.Model):
content = models.CharField(max_length=255, null=True)
def __str__(self):
return "ModelA : " + str(self.id)
the admin.py of this first app also contains :
from django.contrib import admin
from appone.models import *
from apptwo.models import ModelB
from django.http import HttpResponse
from django.template.response import TemplateResponse
from django.conf.urls import url
from registre import views
from django.db.models.signals import post_save
from django.dispatch import receiver
import datetime
from django.contrib.auth.models import User
from django import forms
from ckeditor.widgets import CKEditorWidget
from django.template.loader import render_to_string
import requests
class ModelAAdminForm(forms.ModelForm):
content = forms.CharField(widget=CKEditorWidget())
class Meta:
model = ModelA
fields = '__all__'
class ModelAAdmin(admin.ModelAdmin):
form = ModelAAdminForm
def create_A(sender, instance, **kwargs):
string = "http://localhost:8000/admin/apptwo/modelb/my_view/ref=" + str(instance.id)
r = requests.get(string)
ModelA.objects.create(contenu=r.text.encode('utf-8'))
post_save.connect(create_A, sender=ModelB)
admin.site.register(ModelA, ModelAAdmin)
the second app (apptwo) has a models.py like this :
from django.db import models
from django.contrib.auth.models import User
class ModelB(models.Model):
owner = models.ForeignKey(User, null=True)
name = models.CharField(max_length=255, null=True)
def __str__(self):
return self.name
and an admin.py that contains :
from django.contrib import admin
from appone.models import *
from apptwo.models import *
import datetime
from django.conf.urls import url, include
from django.template.response import TemplateResponse
class ModelBAdmin(admin.ModelAdmin):
def get_queryset(self, request):
qs = super(ModelB, self).get_queryset(request)
if request.user.is_superuser:
return qs
return qs.filter(owner=request.user)
def save_model(self, request, obj, form, change):
obj.owner = request.user
obj.save()
def get_urls(self):
urls = super(ModelBAdmin, self).get_urls()
my_urls = [
url(r'^my_view/ref=(?P<id>\d+)$', self.my_view),
]
return my_urls + urls
def my_view(self, request, id):
context = dict(
self.admin_site.each_context(request),
selector = ModelB.objects.get(id=id),
)
return TemplateResponse(request, "myview.html", context)
admin.site.register(ModelB, ModelBAdmin)
and finally a template myview.html with :
<p>Test {{ selector.name }}</p>

how to use ListView class for two different templates

I have a ListView class in view.py
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):
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]
class DetailView(generic.DetailView):
model = Entertainmentblog
template_name = 'entertainment/article.html'
and I'm using this view to display a list of articles in index.html.But,I would like to show the same list of articles in article.html after the article.I have used the blocks correctly but,it won't show any articles because in ListViewthe template name is index.html.How do I solve this?
Use a Mixin:
class LatestArticleMixin(object):
def get_context_data(self, **kwargs):
context = super(LatestArticleMixin, self).get_context_data(**kwargs)
try:
context['latest_article_list'] = Entertainmentblog.objects.order_by('-posted')[:25]
except:
pass
return context
Then refactor your DetailView:
class DetailView(LatestArticleMixin, generic.DetailView):
model = Entertainmentblog
template_name = 'entertainment/article.html'
In your template if there are articles:
{% if latest_article_list %}
....
{% endif %}
In urls.py you can set template_name as attribute to ListView url entry router.
urls.py
urlpatterns = patterns('',
(r'^a/$', ListView.as_view(model=Poll, template_name="a.html")),
(r'^b/$', ListView.as_view(model=Poll, template_name="b.html")),
)
In views.py even you don't need to set template.
views.py
class ListView(generic.ListView):
model = Poll

Categories