Django Models not showing in template - django

I am finding it quite difficult to display django models in template. The Model does not show at all in the template. Any help will indeed be appreciated.
models.py
from django.db import models
from django.urls import reverse
from datetime import datetime
class Blog(models.Model):
name= models.CharField(max_length = 200)
company= models.CharField(max_length = 200)
post = models.CharField(max_length = 200)
author= models.ForeignKey('auth.User', on_delete = models.PROTECT)
mantra= models.CharField(max_length = 200, help_text='make it short and precise')
photo= models.ImageField(upload_to='photos/jobs/%Y/%m/%d/', blank=False, null=False)
publish = models.BooleanField(default =True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('index')
views.py
from django.shortcuts import render
from django.views.generic import TemplateView,ListView
from django.views.generic.edit import CreateView
from .models import Blog
class Home(ListView):
model = Blog
context_object_name = 'test'
template_name='test.html'
fields = ['name', 'company', 'post', 'author', 'mantra', 'continent', 'photo']
urls.py
from django.urls import path
from .views import Home
urlpatterns=[
path('', Home.as_view(), name='index'),
]
Template
<p>{{test.name}}</p>
<p>{{test.author}}</p>
<p>{{test.post}}</p>

You should loop on the queryset:
{% for object in test %}
<p>{{object.name}}</p>
<p>{{object.author}}</p>
<p>{{object.post}}</p>
{% endfor %}

Related

get request in django?

I have problem with django request.I dont know. I tried to do everything, but I got
'blog' object has no attribute 'get'. I want to do mini blog on my website,but it isnt working now. I would like to get all objects from database.(Sorry,If I did something wrong,I am beginner in django and tried to functions for my website) :)
models.py
from django.db import models
# Create your models here.
CHOOSE =[
('Usual','Обычный тариф'),
('Premium','Премиум тариф'),
('Prise','Аукционный')
]
class VDSTARIFS( models.Model):
id = models.CharField(max_length=40, primary_key= True,serialize=True)
name = models.CharField(max_length=20, verbose_name = 'Цены')
choosen = models.CharField(max_length= 20, choices = CHOOSE, verbose_name = 'Тариф', help_text='Выбор тарифного плана.')
title = models.CharField(max_length= 15)
def __str__(self):
return str(self.title)
class blog(models.Model):
id = models.CharField(max_length=40, primary_key= True,serialize=True)
message = models.TextField( verbose_name= 'Сообщение блога')
titleblog = models.CharField(max_length=50, verbose_name = 'Название')
img = models.ImageField(upload_to = 'admin/', verbose_name= 'Картинка' )
def __str__(self):
return str(self.titleblog)
def get_all_objects(self): ##maybe I have troubles with it.
queryset = self.__class__.objects.all()
blog.html
{% csrftoken %}
{% for item in message %}
{% endfor %}
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render
from django.http import HttpResponseRedirect
import os
from polls.models import VDSTARIFS
from polls.models import blog
from django.template.loader import render_to_string
def index_view(request):
#return HttpResponse("<h1>Hello</h1>")
return render(request, "home.html", {})
def about(request):
return render(request, "about.html", {})
def minecraft(request):
return render(request, "minecraft.html",{})
def vds(request):
HTML_STRING = render_to_string("vds.html", context = context1)
return HttpResponse(HTML_STRING)
try:
VDS1 = VDSTARIFS.objects.get(id=0)
name = VDS1.name
except VDSTARIFS.DoesNotExist:
VDS1 = None
context1 = {
'name':name,
'prise':VDS1,
}
def messagesblog(request,self):
HTML_STRING = render_to_string('blog.html')
return HttpResponse(HTML_STRING)
urls.py
from django.contrib import admin
from django.urls import path
from polls import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index_view, name='home'),
path('vds', views.vds, name='vds' ),
path('minecraft', views.minecraft, name='minecraft' ),
path('about', views.about, name='about'),
path('blog', views.blog, name='blog')
]
The actual error is probably caused by the wrong url pattern:
path('blog', views.blog, name='blog')
views.blog refers to the blog model due to:
from polls.models import blog
What you need here is the view not the model, so:
path('blog', views.messagesblog, name='blog')
Then, remove the "self" argument from your messagesblog function.
Use the "render" function from django.shortcuts and provide a context with the blog objects:
def messagesblog(request):
return render(request, "blog.html", {message: blog.objects.all()})
That might solve your problem.
Still, there are some things you could improve.
E.g.: Don't use "id" fields in your model definitions if you don't really, really have to, as this is usually an auto-generated number (BigInt) field.
That's only one tip from an old Django veteran happy to be finally heard. You'll find out much more yourself as you proceed.

TemplateDoesNotExist: home.html, femat/law_list.html

Why I am getting the above error while I have not defined or requested "law_list.html"? Where does the law_list.html come from? It should be something wrong with model and class based view. I am using Django 3.1.3.
#models.py
from django.db import models
class Law(models.Model):
name = models.CharField(max_length=100)
E = models.FloatField(null=False, blank=False, default=0)
def __str__(self):
return '{} {}'.format(self.name, self.E)
#views.py
from django.views.generic import ListView
from .models import Law
class HomeView(ListView):
model = Law
template_name = 'home.html'
#urls.py
from django.urls import path
from .views import HomeView
urlpatterns = [
path('', HomeView.as_view(), name='home'),
]
This should do it:
template_name= "femat/home.html"

In the process of categorising my blogs but keep hitting the wall "Page not found 404"

I am a complete beginner so I apologies for my noobiness explanation. I am in the process of categorising my blogs.
I created a model -> migrated it -> imported in view.py -> Imported the view that I created into urls.py -> and created URL for my new page but when I add the href to other pages (home) it takes me to the error.
My codes:
models.py
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=100)
content=models.TextField()
date_posted=models.DateTimeField(default=timezone.now)
author=models.ForeignKey(User, on_delete=models.CASCADE)
category = models.CharField(max_length=100, default='Engineering')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
Views.py:
from .models import Post, Category
class CategoryListView(ListView):
model = Post
template_name= 'blog/category_posts.html'
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 3
urls.py:
from django.urls import path
from .views import (
PostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView,
UserPostListView,
CategoryListView)
path('category/<str:category>/', CategoryListView.as_view(), name='category-posts'),
home.html
{{ post.category }}
In addition to what Arun said.
I think you need to set url_patters in your urls.py. Something like this:
from django.urls import path
from .views import (
PostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView,
UserPostListView,
CategoryListView)
urlpatterns = [
path('category/<str:category>/', CategoryListView.as_view(), name='category-posts'),
]
You should also pass the category in your url, like this
{{ post.category }}
Because your url needs a str parameter category.

Module 'django.db.models' has no attribute 'FileBrowseField'

I would like to have on my Django 2.1.1 site django-filebrowser-no-grappelli. I've followed this indications but at the end of the procedure, when I restart my server, I've this error:
header_image = models.FileBrowseField("Image", max_length=200,
directory="images/", extensions=[".jpg"], blank=True) AttributeError:
module 'django.db.models' has no attribute 'FileBrowseField'
This are the files of my project:
MODELS.PY
from django.db import models
from django.urls import reverse
from tinymce import HTMLField
from filebrowser.fields import FileBrowseField
class Post(models.Model):
"""definizione delle caratteristiche di un post"""
title = models.CharField(max_length=70, help_text="Write post title here. The title must be have max 70 characters", verbose_name="Titolo", unique=True)
short_description = models.TextField(max_length=200, help_text="Write a post short description here. The description must be have max 200 characters", verbose_name="Breve descrizione dell'articolo")
contents = HTMLField(help_text="Write your post here", verbose_name="Contenuti")
publishing_date = models.DateTimeField(verbose_name="Data di pubblicazione")
updating_date = models.DateTimeField(auto_now=True, verbose_name="Data di aggiornamento")
header_image = models.FileBrowseField("Image", max_length=200, directory="images/", extensions=[".jpg"], blank=True)
slug = models.SlugField(verbose_name="Slug", unique="True", help_text="Slug is a field in autocomplete mode, but if you want you can modify its contents")
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("singlearticleView", kwargs={"slug": self.slug})
class Meta:
verbose_name = "Articolo"
verbose_name_plural = "Articoli"
VIEWS.PY
from django.shortcuts import render
from .models import Post
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
class SingleArticle(DetailView):
model = Post
template_name = "single_article.html"
class ListArticles(ListView):
model = Post
template_name = "list_articles.html"
def get_queryset(self):
return Post.objects.order_by('-publishing_date')
URLS.PY
from django.urls import path
from .views import ListArticles, SingleArticle
urlpatterns = [
path("", ListArticles.as_view(), name="listarticlesView"),
path("<slug:slug>/", SingleArticle.as_view(), name="singlearticleView"),
]
ADMIN.PY
from django.contrib import admin
from .models import Post
class PostAdmin(admin.ModelAdmin):
"""creazione delle caratteristiche dei post leggibili nel pannello di amministrazione"""
list_display = ["title", "publishing_date", "updating_date", "id"]
list_filter = ["publishing_date"]
search_fields = ["title", "short_description", "contents"]
prepopulated_fields = {"slug": ("title",)}
fieldsets = [
(None, {"fields": ["title", "slug"]}),
("Contenuti", {"fields": ["short_description", "contents"]}),
("Riferimenti", {"fields": ["publishing_date"]}),
]
class Meta:
model = Post
admin.site.register(Post, PostAdmin)
URLS.PY PROJECT
from django.contrib import admin
from django.urls import path, include
from filebrowser.sites import site
urlpatterns = [
path('admin/filebrowser/', site.urls),
path('grappelli/', include('grappelli.urls')),
path('admin/', admin.site.urls),
path('', include('app4test.urls')),
path('tinymce/', include('tinymce.urls')),
]
I've started all of this because I will use TinyMCE and a file browser application is necessary. When I deactive the string header_image in models.py the project running well but, obviously, when I try to upload an image I've an error.
Where I made a mistake?
your import is done like this:
from filebrowser.fields import FileBrowseField
but you're trying to use the field following way:
header_image = models.FileBrowseField(...)
It's not part of the models package, just do it without the models. part:
header_image = FileBrowseField(...)

Data not shown in Django admin after adding by my form

I am a beginner to Django.
I want to create a form that allow user to store their data to the database, but I face to an issue.
If I add data through Django admin, the data will shown correctly. But if I add data through my form. Data will store into database successfully but they don't shown in my Django admin.
Note: The Django version I used is 1.11.2
The is my Django admin page. There are 8 data in the database but just show the one I added by the Django admin.
views.py
from django.shortcuts import render
from django.views.generic import CreateView
from .forms import ApplyFormCreateForm
from .models import ApplyForm
class ApplyFormCreateView(CreateView):
form_class = ApplyFormCreateForm
template_name = 'form.html'
success_url = "/"
models.py
from django.db import models
from course.models import Semester
DEFAULT_SEMESTER_ID = 1
class ApplyForm(models.Model):
name = models.CharField(max_length=15)
school = models.CharField(max_length=20)
department = models.CharField(max_length=20)
email = models.EmailField(max_length=100)
is_beginner = models.BooleanField(default=False)
introduction = models.TextField(max_length=2000)
motivation = models.TextField(max_length=2000)
comments = models.TextField(max_length=2000, blank=True)
semester = models.ForeignKey(Semester, default=DEFAULT_SEMESTER_ID)
created_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.school + self.department + self.name
def __str__(self):
return self.school + self.department + self.name
form.html
{% extends "base.html" %}
{% block content %}
<form method='POST'> {% csrf_token %}
{{form.as_p}}
<button type='submit'>Save</button>
</form>
{% endblock content %}
form.py
from django import forms
from .models import ApplyForm
class ApplyFormCreateForm(forms.ModelForm):
class Meta:
model = ApplyForm
fields = [
'name',
'school',
'department',
'email',
'is_beginner',
'introduction',
'motivation',
'comments',
]
url.py
from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from myweb.views import HomeView
from course.views import CourseListView
from applyform.views import ApplyFormCreateView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', HomeView.as_view(), name='home'),
url(r'^course/$', CourseListView.as_view(), name='course'),
url(r'^apply/$', ApplyFormCreateView.as_view(), name='applyform'),
]