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,))
Related
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.
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
# ⋮
def get_success_url(self):
return reverse('todoapp:cbvdetail', kwargs={'pk':self.object.id})
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"
I want to use the {{ post.title }} and {{ for post in object_list }}
into my home template to show the latest 4 posts, I tried to import from blog.models import Post, but it doesn't work. I guess I'm putting it in the wrong place.
blog.models
from django.db import models
from ckeditor.fields import RichTextField
class Post(models.Model):
title = models.CharField(max_length = 140)
image = models.ImageField(upload_to="media", blank=True)
body = RichTextField(config_name='default')
date = models.DateField()
def __str__(self):
return self.title
home.urls
from django.urls import path
from . import views
urlpatterns = [
path('', views.HomePageView.as_view(), name='home'),
]
home.views
from django.views.generic import TemplateView
from allauth.account.forms import LoginForm
class HomePageView(TemplateView):
template_name = 'home/index.html'
mysite tree look like this
mysite
home
admin
app
models
tests
urls
views
blog
admin
app
models
tests
urls
views
You can override get_context_data and add the latest blog posts to the template context.
from blog.models import Post
class HomePageView(TemplateView):
template_name = 'home/index.html'
def get_context_data(self, **kwargs):
context = super(HomePageView, self).get_context_data(**kwargs)
context['object_list'] = Post.objects.order_by('-date')[:4]
return context
I have a django model defined as
from utils.utils import APIModel
from django.db import models
from django.core.urlresolvers import reverse
class DjangoJobPosting(APIModel):
title = models.CharField(max_length=50)
description = models.TextField()
company = models.CharField(max_length=25)
def get_absolute_url(self):
return reverse('jobs.views.JobDetail', args=[self.pk])
with a view
from restless.views import Endpoint
from restless.models import serialize
from .models import *
from utils.utils import JSON404
import ujson as json
class JobList(Endpoint):
def get(self, request):
fields = [
('url', lambda job: job.get_absolute_url()),
'title',
('description',lambda job: job.description[:50]),
'id'
]
jobs = DjangoJobPosting.objects.all()
return serialize(jobs, fields)
class JobDetail(Endpoint):
def get(self, request, pk):
try:
job = DjangoJobPosting.objects.get(pk=pk)
print(job)
fields = ["title","description","company","id"]
return serialize(job,fields)
except Exception as e:
return JSON404(e)
What I have seen in other posts which talk about reverse method is that they define the first reverse parameter in the terms I specified above, but their urls.py uses the same kind of definition, while mine uses
from django.conf.urls import patterns, include, url
from .views import *
urlpatterns = patterns('',
url(r'^$',JobList.as_view()),
url(r'^(?P<pk>\d+)/$', JobDetail.as_view()),
)
What I keep getting is an error that states
"Reverse for 'jobs.views.JobDetail' with arguments '(1,)' and keyword arguments '{}' not found."
Give urls names:
from django.urls import reverse
urlpatterns = patterns('',
url(r'^$',JobList.as_view(), name='joblist'),
url(r'^(?P<pk>\d+)/$', JobDetail.as_view(), name='jobdetail'),
)
Use that name when call reverse:
return reverse('jobdetail', args=[self.pk])
or
return reverse('jobdetail', kwargs={'pk': self.pk})