TemplateDoesNotExist: home.html, femat/law_list.html - django

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"

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.

Reverse for 'cbvdetail' not found. 'cbvdetail' is not a valid view function or pattern name

i can't call my detail class using reverse_lazy
from django.shortcuts import render, redirect
from django.urls import reverse_lazy, reverse
from . models import Task
from . forms import Taskform
from django.views.generic import ListView
from django.views.generic.detail import DetailView
from django.views.generic.edit import UpdateView
class Tasklistview(ListView):
model = Task
template_name = 'home.html'
context_object_name = 'task'
class Detailview(DetailView):
model=Task
template_name = "details.html"
context_object_name = 'task'
class Updateview(UpdateView):
model = Task
template_name = "update.html"
context_object_name = "task"
fields = ('name', 'priority', 'date')
def get_success_url(self):
return reverse_lazy("cbvdetail",kwargs={'pk':self.object.id})
urls.py
from django.urls import path
from . import views
app_name='todoapp'
urlpatterns = [
path('',views.home,name='home'),
# path('details', views.details,name='ere')
path('delete/<int:id>/',views.delete,name='delete'),
path('edit/<int:id>/',views.update,name='update'),
path('cbvhome/',views.Tasklistview.as_view(),name='home'),
path('cbvdetail/<int:pk>/',views.Detailview.as_view(),name='cbvdetail'),
path('cbvupdate/<int:pk>/',views.Updateview.as_view(),name='edit'),
]
i want to resolve this
You specified an app_name in the urls.py file. That means you need to prefix the name of the view with that app label, so:
def get_success_url(self):
return reverse_lazy('todoapp:cbvdetail', kwargs={'pk':self.object.id})
If you override get_success_url, it does not make much sense to work with reverse_lazy, since that method will (normally) only be triggered in case the urls are already loaded, you can thus work with:
from django.urls import reverse
# &vellip;
def get_success_url(self):
return reverse('todoapp:cbvdetail', kwargs={'pk':self.object.id})

NoReverseMatch with generic DeleteView

I cannot figure out why I'm getting NoReverseMatch when trying to use this view. I'd like to get generic views to work because it seems like alot less code to do the same task.
views.py
from django.views.generic import DetailView, ListView, UpdateView, CreateView, DeleteView
from django.urls import reverse_lazy
from .models import *
class ProductDeleteView(DeleteView):
model = Product
success_url = reverse_lazy('homepage_view')
models.py
from django.db import models
from django.urls import reverse
from autoslug import AutoSlugField
class Product(models.Model):
name = models.CharField(max_length=50)
slug = AutoSlugField(null=True, default=None,
unique=True, populate_from='name')
def get_delete_url(self):
return reverse('product_delete_view', args=(self.slug,))
class Meta:
verbose_name_plural = "Products"
def __str__(self):
return self.name
urls.py
from . import views
from django.urls import path, include
from django.views.generic import TemplateView
app_name = "main"
urlpatterns = [
path('product/delete/<slug:slug>/', views.ProductDeleteView.as_view(), name='product_delete_view'),
]
template
<p>
<a class="btn btn-primary" href="{{product.get_delete_url}}">Delete Product</a>
</p>
you should add the app name also in get delete url method
def get_delete_url(self):
return reverse('main:product_delete_view', args=(self.slug,))

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(...)

What would be the format of urls.py for class based views?

I am new to django so i want to know how to write urls.py for a project.
I want to make backend api for inventory management system.
When i type localhost:8000/inventory_backend/dep/, I am having following error:
**Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
The current path, inventory_backend/dep/, didn't match any of these.
My code for mysite/urls.py**
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^inventory_backend/', include('inventory_backend.urls')
),
url(r'^admin/', admin.site.urls) ,
]
inventory_backend/urls.py:
from inventory_backend.views import DepartmentsView,InventoriesView
from rest_framework import routers
router = routers.SimpleRouter()
router.register(r'dep/',DepartmentsView )
router.register(r'inv/',InventoriesView )
urlpatterns = router.urls
serializers.py
from rest_framework import serializers
from inventory_backend.models import Departments,Inventories
class DepartmentsSerializer(serializers.ModelSerializer):
class Meta:
model : Departments
fields: ('id','name')
class InventoriesSerializer(serializers.ModelSerializer):
dept = DepartmentsSerializer(many=True)
class Meta:
model : Inventories
fields : ('id','name','description','dept')
models.py
from django.db import models
class Departments(models.Model):
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Inventories(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=200)
dept = models.ManyToManyField(Departments)
def __str__(self):
return self.name
views.py
from rest_framework import viewsets
from inventory_backend.models import Inventories,Departments
from inventory_backend.serializers import InventoriesSerializer,
DepartmentsSerializer
class DepartmentsView(viewsets.ModelViewSet):
queryset = Departments.objects.all();
serializer_class = DepartmentsSerializer;
class InventoriesView(viewsets.ModelViewSet):
queryset = Inventories.objects.all();
serializer_class = InventoriesSerializer;
Change your inventory_backend.urls.py,
urlpatterns = [
url(r'^', include(router.urls))
]