I want to show the details of a product added.
I followed this link and i could create an add product page
https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html
once the product is added, i want to show the details of the product added in a new page.
So i tried the following:
class ProductDetailView(DetailView):
model = Product
context_object_name = 'product'
queryset = Product.objects.filter(pk)
I really don't know what to put in the filter, or using filter is correct. i had tried using latest and order by instead of filter but they did not work.
my urls.py is as follows:
urlpatterns = [
path('', views.ProductDetailView.as_view(), name='product_changelist'),
#path('', views.ProductListView.as_view(), name='product_changelist'),
path('add/', views.ProductCreateView.as_view(), name='product_add'),
path('<int:pk>/', views.ProductUpdateView.as_view(), name='product_change'),
path('ajax/load-subcategory/', views.load_subcategory, name='ajax_load_subcategory'),
#path('<int:product_id>', views.detail, name='detail'),
]
Currently i am getting error as
AttributeError at /product/
Generic detail view ProductDetailView must be called with either an object pk or a slug.
I read that we have to provide the pk in urls.py so i tried providing pk as follows:
path('<int:pk>', views.ProductDetailView.as_view(), name='product_changelist'),
but then i get an error as follows:
NoReverseMatch at /product/add/
Reverse for 'product_changelist' with no arguments not found. 1 pattern(s) tried: ['product\\/(?P<pk>[0-9]+)$']
Any help in solving this problem is highly appreciated. I am new to django so may have done many mistakes above.
Edit 1:
I tried the suggestion given by #Radico, but still the same error: What i did is as follows:
Changed my ProductDetailView as follows:
class ProductDetailView(DetailView):
model = Product
context_object_name = 'product'
the product_list.html now has the following content
{% extends 'base.html' %}
{% block content %}
<br />
<br />
<br />
<br />
<br />
This is the page getting displayed121
{% url 'product_changelist' pk=object.pk %}
{% endblock %}
Still i get the same error as
AttributeError at /product/
Generic detail view ProductDetailView must be called with either an object pk or a slug
I did not change anything in urls.py.... do i have to change anything in it as well?
Edit 2:
Here is my urls.py
from django.urls import include, path
from . import views
urlpatterns = [
path('<int:pk>', views.ProductDetailView.as_view(), name='product_changelist'),
#path('', views.ProductDetailView.as_view(), name='product_changelist'),
#path('', views.ProductListView.as_view(), name='product_changelist'),
path('add/', views.ProductCreateView.as_view(), name='product_add'),
path('', views.ProductUpdateView.as_view(), name='product_change'),
path('ajax/load-subcategory/', views.load_subcategory, name='ajax_load_subcategory'),
#path('<int:product_id>', views.detail, name='detail'),
]
My views.py is as follows:
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views.generic import CreateView, UpdateView, ListView, DetailView
from category.models import Subcategory
from product.forms import ProductForm
from product.models import Product
class ProductListView(ListView):
model = Product
context_object_name = 'product'
queryset = Product.objects.filter()
class ProductDetailView(DetailView):
model = Product
context_object_name = 'product'
# queryset = Product.objects.filter()
# class ProductDetailView(DetailView):
# template_name = 'product/product_list.html'
# #model = User
# #context_object_name = 'foo'
#
# def get_object(self):
# #return get_object_or_404(Product, pk=request.session['product_id'])
# return get_object_or_404(Product, pk=self.request.
class ProductCreateView(CreateView):
model = Product
form_class = ProductForm
success_url = reverse_lazy('product_changelist')
def productlist(request, product_id):
product = Product.objects.get(productid=product_id)
return render(request, 'product/product_list.html', {'product': product})
# def productlist(request):
# prodlist = Product.objects.order_by('-pk')[0]
# return render(request, 'product/product_list.html', {'prodlist': prodlist})
class ProductUpdateView(UpdateView):
model = Product
form_class = ProductForm
success_url = reverse_lazy('product_changelist')
def load_subcategory(request):
category_id = request.GET.get('category')
subcategory = Subcategory.objects.filter(category_id=category_id).order_by('name')
return render(request, 'product/subcategory_dropdown_list_options.html', {'subcategory': subcategory})
My product_list.html is as i had pasted earlier
{% extends 'base.html' %}
{% block content %}
<br />
<br />
<br />
<br /><br />
This is the page getting displayed121
{% url 'product_changelist' pk=object.pk %}
{% endblock %}
First: You don't need to get query set within the detailview the object is already available, you can call it in the template object or class name lowercase in your case product.
Second: make sure that you pass pk in urls refer to the detailview within templates i.e {% url 'product_change' pk=object.pk %}
I believe you got the error for second part check the url in product_changelist template and you may forgot to pass pk=object.pk
If you want to use Regular expressions when you're using path:
from django.urls import path , re_path
re_path(r'^product/(?P<pk>\d+)$', views.ProductUpdateView.as_view(), name='product_change'),
Related
I created a small Django application to manage data that fits a simple a model. For now I only need two views: one to list all records and another to edit a record with a generic form. Everything functions as expected, except the redirection from the edit view upon a successful update. In urls.py are the following contents:
from django.urls import path
from . import views
app_name = 'reqs'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.ReqUpdateView.as_view(), name='update'),
]
In forms.py:
from django.forms import ModelForm
from .models import Requirement
class RequirementForm(ModelForm):
class Meta:
model = Requirement
fields = ['name', 'priority', 'source' , 'rationale']
And the templeate requirement_form.html:
<h1>{{ requirement.id }} - {{ requirement.name }}</h1>
<form method="post" novalidate>
{% csrf_token %}
<table>
{{ form.as_table }}
<tr><td></td><td><button type="submit">Save</button></td></tr>
</table>
</form>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<br><br>
Back to list
Finally views.py, on a first attempt to redirect the update to the list:
from django.views.generic import ListView, UpdateView
from django.urls import reverse_lazy
from .models import Requirement
from .forms import RequirementForm
class IndexView(ListView):
template_name = 'reqs/index.html'
context_object_name = 'requirements_list'
def get_queryset(self):
return Requirement.objects.order_by('subject')
class ReqUpdateView(UpdateView):
model = Requirement
form_class = RequirementForm
success_url = reverse_lazy('/')
With this formulation the Save button produces this error:
Reverse for '/' not found. '/' is not a valid view function or pattern name.
I also tried an empty string as argument to reverse_lazy, as well as the path name index, but a similar error message is produced.
On a second attempt I tried to redirect to the same page, redefining the get_success_url method to do nothing:
class ReqUpdateView(UpdateView):
model = Requirement
form_class = RequirementForm
context_object_name = 'requirement_update'
def get_success_url(self):
pass #return the appropriate success url
This returns a 404 error trying to redirect the browser to /reqs/1/None.
A third attempt to redirect to the form with the same record:
class ReqUpdateView(UpdateView):
model = Requirement
form_class = RequirementForm
context_object_name = 'requirement_update'
def get_success_url(self):
pk = self.kwargs["pk"]
return reverse("update", kwargs={"pk": pk})
Which complains about not finding the view:
Reverse for 'update' not found. 'update' is not a valid view function or pattern name.
How can I redirect success to a valid URL? It can either be the items list or the item update view, as long as it works.
There are few misconception that you did
reverse parameter should be as documented
URL pattern name or the callable view object
You have set namespace but you are not reversing with namespace as documented
So in your case
def get_success_url(self):
pk = self.kwargs["pk"]
return reverse("reqs:update", kwargs={"pk": pk})
reverse / reverse_lazy are used to get the url using view name or pattern name. If you want to use a url directly just write:
success_url = '/'
For the case of return reverse("update", kwargs={"pk": pk}) not working since you set app_name = 'reqs' you should be using return reverse("reqs:update", kwargs={"pk": pk}) instead.
How to load multiple models in one template in Django 2?
i've read Django Pass Multiple Models to one Template but, i'm lost in the answer and there is no specific answer there to get that view into the template,
Im trying to pass 3 models in views to template, which is Info, Slogan & Berita.
My views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Artikel, Berita, Data, Galeri, Info, Slogan, Profil
from django.views.generic import ListView, DetailView
def home(request):
extra_context : {"info" : Info.objects.all(),
"slogan": Slogan.objects.all(),
"berita": Berita.objects.all(),
#and so on for all the desired models...
}
return render (request, 'blog/home.html')
class HomeListView(ListView):
context_object_name = 'slogan'
template_name = 'blog/home.html'
queryset = Info.objects.all()
def get_context_data(self, **kwargs):
context = super(HomeListView, self).get_context_data(**kwargs)
context['slogan'] = Slogan.objects.all()
context['berita'] = Berita.objects.all()
# And so on for more models
return context
my template home.html looks like:
{% for slogans in slogan %}
<p>{{ slogans.konten }}</p>
<p>{{ slogans.author }}</p>
{% endfor %}
my url urls.py looks like:
from blog.views import HomeListView
urlpatterns = [
url(r'^$', HomeListView.as_view(), name="home"),
]
and page source on browser shows nothing.
Im stuck on this, i found at least 3 similar result on this site but not works for me.
I need to make form in header section of site. This form will be available for all pages in my site. For example, i have in my app "accounts":
forms.py
class SignupForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ('phone',)
views.py
def signup(request):
form = SignupForm(request.POST or None)
# CODE #
ctx = {
'form': form,
}
return render(request, 'accounts/signup.html', ctx)
urls.py
from django.urls import path
from . import views
app_name = 'accounts'
urlpatterns = [
path('signup/', views.signup, name='signup'),
]
accounts/signup.html
{% block signup %}
{{ form }}
{% endblock %}
If I add{% include 'accounts/signup.html' %} to my _base.html, I don't, get form - {{ form }} but all other content will be included.
And can you tell me how exactly get form for all pages in site? Is it the correct approach?
Use a custom templatetag to initialize an empty form and display it from wherever you want - just make sure the action attribute of the HTML <form> tag points to your signup view.
I am new to Django and have been making a sample project. I have been trying to use Generic Detailview. It seems that url redirection works fine but DetailView can't get primarykey from the url.
Main url.py::
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^',include('personal.urls')),
]
Here is my app's urls.py code:
urlpatterns = [
url(r'(?P<pk>\d+)/$',views.detailView.as_view(),name="detail"),]
View file for the DetailView:
from django.shortcuts import render
from django.views import generic
from .models import Story
class detailView(generic.DetailView):
model = Story
template_name = 'personal/storydetail.html'
def get_context_data(self, **kwargs):
pk = kwargs.get('pk') # this is the primary key from your URL
print("PK:",pk)
Template Code:
{% block content %}
{{ Story.writer }}
<h6> on {{ Story.story_title }}</h6>
<div class = "container">
{{ Story.collection }}
</div>
{% endblock %}
Story Class code:
class Story(models.Model):
story_title = models.CharField(max_length=200) #Story title
writer = models.CharField(max_length=200) #WriterName
collection=models.CharField(max_length=200) #Collection/Book name
When I check primary key value on view it shows it 'NONE'. I can't find issue with the code. My pased url looks like : http://127.0.0.1:8000/personal/2/ where personal is the name of app and 2 should be taken as id.
The problem is that you are using kwargs instead of self.kwargs inside the get_context_data method. It should be something like:
def get_context_data(self, **kwargs):
# You need to call super() here, so that the context from the DetailView is included
kwargs = super(detailView, self).get_context_data(**kwargs)
pk = self.kwargs['pk'] # No need for get() here -- if you get a KeyError then you have a problem in your URL config that should be fixe # this is the primary key from your URL
# edit kwargs as necessary
...
return kwargs
In the get_context_data method, kwargs are those passed to the method to make up the context. They are different from self.kwargs, which are from the url pattern.
I am fairly new to CBV and am trying to make sense of it. I copied the following example from the django doc page:
https://docs.djangoproject.com/en/dev/topics/class-based-views/generic-editing/
models.py
from django.core.urlresolvers import reverse
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=200)
def get_absolute_url(self):
return reverse('author-detail', kwargs={'pk': self.pk})
views.py
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.urlresolvers import reverse_lazy
from myapp.models import Author
class AuthorCreate(CreateView):
model = Author
fields = ['name']
class AuthorUpdate(UpdateView):
model = Author
fields = ['name']
class AuthorDelete(DeleteView):
model = Author
success_url = reverse_lazy('author-list')
urls.py
from django.conf.urls import patterns, url
from myapp.views import AuthorCreate, AuthorUpdate, AuthorDelete
urlpatterns = patterns('',
# ...
url(r'author/add/$', AuthorCreate.as_view(), name='author_add'),
url(r'author/(?P<pk>\d+)/$', AuthorUpdate.as_view(), name='author_update'),
url(r'author/(?P<pk>\d+)/delete/$', AuthorDelete.as_view(), name='author_delete'),
)
At author/add/ I indeed get the form, but when I enter the string I get the following error:
Reverse for 'author-detail' with arguments '()' and keyword arguments '{'pk': 3}' not found.
It seems like the new entry has been added to the database, but it could not resolve the URL for the next view?
So I am puzzled, what is this get_absolute_url() object's method supposed to do, how does it work (I could not grasp it from the django doc) and how do I fix the issue?
Thanks.
EDIT 1: added the template:
author_form.html:
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Create" />
</form>
By default, when a new model is created django will redirect you to a models absolute url as returned by the get_absolute_url method. In your example you would need to add a url with the name author-detail that accepts a pk keyword argument.
urlpatterns = patterns('',
# ...
url(r'author/(?P<pk>\d+)/$', AuthorDetail.as_view(), name='author-detail'),
)
Note the name of the url matches the name of the view in the get_absolute_url method.
Use it in your templates:
{% for author in authors %}
{{author.name}}
{% endfor %}