I am developing a crud application using django,using Class based views, Create, retrieve, details functions are working properly but update function don't here is my code snippets
kindly dont mark my question negative, i'm a beginner.
ERROR
views.py
class Update(UpdateView):
fields = ('age', 'email')
models = models.CreateUser
urls.py
app_name='main'
urlpatterns = [
url(r'^create/$', views.Create.as_view(), name='create'),
url(r'^(?P<pk>\d+)/$', views.Details.as_view(), name='detail'),
url(r'^update/(?P<pk>\d+)/$', views.Update.as_view(), name='update'),
url(r'', views.UsersList.as_view(), name='allUsers'),
]
models.py
class CreateUser(models.Model):
name = models.CharField(max_length=256)
age = models.IntegerField()
email = models.CharField(max_length=256)
gender = models.CharField(max_length=50)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('main:create', kwargs={'pk': self.pk})
From details page i'm calling that view on a button
<!DOCTYPE html>
{% extends 'mainApp/base.html' %}
{% block body_block %}
<div class="jumbotron container">
<h1>Welcome to the Users detail page</h1>
<h2>User Details</h2>
<p>Name : {{user_details.name}}</p>
<p>Age: {{user_details.age}}</p>
<p>Email: {{user_details.email}}</p>
<p>Gender: {{user_details.gender}}</p>
<p><a class="btn btn-warning" href="{% url 'main:update' pk=user_details.pk %}">Update this</a></p>
</div>
{% endblock %}
Related
I' wanted to try Django framework and i tried the blog app tutorial. i tried to add a comment feature. i know these questions have been asked several times but couldn't find a solution to my problem.
I got the following error:
No Post matches the given query.
Thanks for your help. Here are the Model and all:
urls.py :
path('', PostListView.as_view(), name='blog-home'),
path('user/<str:username>/', UserPostListView.as_view(), name='user-posts'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/new/', PostCreateView.as_view(), name='post-create'),
path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('post/<int:pk>/comment/', PostCommentView.as_view(), name='post-comment'),
path('about/', views.about, name='blog-about'),
]
models.py:
class Post(models.Model):
title = models.CharField(max_length=50)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE) # many to one relation use foreign key
def __str__(self):
return self.title
#property
def get_comments(self):
return self.comment_content.all()
# return the url as string
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
class Comment(models.Model):
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, related_name='comment_content', on_delete=models.CASCADE)
def __str__(self):
return self.content
def get_absolute_url(self):
return reverse('comment-create', kwargs={'pk': self.pk})
forms.py:
class CommentForm(forms.ModelForm):
content=forms.Textarea()
class Meta:
model = Comment
fields=['content']
views.py:
class PostCommentView(LoginRequiredMixin, CreateView):
model = Comment
fields = ['content']
template_name = 'blog/comment_form.html'
success_url = '/'
def form_valid(self, form):
post = get_object_or_404(Post, id=self.kwargs.get('id'))
print(post.id)
form.instance.author = self.request.user
form.instance.post = post
return super().form_valid(form)
comment_form.htlm:
{% extends "blog/base.html" %}
{% load crispy_forms_filters %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Comment tag</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Post comment</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Abort the Comment? <a class="ml-2" href="{% url 'blog-home' %}">Back to Main Page</a>
</small>
</div>
</div>
{% endblock content %}
'id' is standard primary key of a Django Model but not of the POST that is created with ModelForm etc.
I suppose you need to put a hidden field "id" in your form to get it sent with the POST request.
Try print(self.kwargs.get('id')) before the 'get_object...' and you will see if 'id' has some content.
NoReverseMatch
Reverse for 'Edit_Product' with no arguments not found. 1 pattern(s) tried: ['shop/product/Edit_Product/(?P[0-9]+)$']
I could not understand the reason behind this error I tried looking for answers for around the web but nothing worked for me so far, I am new to django and trying to develop my skills if anyone can help please
Models.py
class Product(models.Model):
category = models.ForeignKey(Category,
related_name='products',
on_delete=models.CASCADE)
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True)
image = models.ImageField(upload_to='products/%Y/%m/%d',
blank=True)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('name',)
index_together = (('id', 'slug'),)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:product_detail', args=[self.id, self.slug])
forms.py
class EditProduct(forms.ModelForm):
class Meta:
model = Product
fields = ["category", "name", "image", "description",
"price", "available"]
views.py
#staff_member_required
def Edit_Product(request, id=None):
product = get_object_or_404(Product, id=id)
if request.method == "POST":
form = EditProduct(request.POST, instance=product)
if form.is_valid():
form = form.save(commit=False)
form.save()
return render(request, 'shop/product/Edit_Product.html', {'product': product, 'form':form})
else:
form = EditProduct(instance=product)
return render(request,'shop/product/Edit_Product.html', {'form': form})
urls.py
urlpatterns = [
path('', views.product_list, name='product_list'),
path('<slug:category_slug>/', views.product_list, name='product_list_by_category'),
path('<int:id>/<slug:slug>/', views.product_detail, name='product_detail'),
path('shop/Create_Product/', views.Create_Product, name='Create_Product'),
path('shop/product/Edit_Product/<int:id>', views.Edit_Product, name='Edit_Product'),
]
the templates look like this
{% extends "shop/base.html" %}
{% load static %}
<title> Edit </title>
{% block content %}
<div>
<form action="{% url 'shop:Edit_Product' id=Product.id %}" method="POST" enctype="multipart/form-data">
{{ form.as_p }}
<p><input type="submit" value="Update"></p>
{% csrf_token %}
</form>
</div>
{% endblock %}
I would be really grateful for any help I have been having for days now and when modifying it I receive either this error or 404 error.
the error is showing me the detailproduct view in the browser I tried arranging them making edit before it and add it to the render line but alos no luck there
This is how it looks like the view.py product detail just after the edit
def product_detail(request, id, slug):
product = get_object_or_404(Product,
id=id,
slug=slug,
available=True)
cart_product_form = CartAddProductForm()
return render(request,
'shop/product/detail.html',
{'product': product,
'cart_product_form': cart_product_form})
the Image link is here for the Error
enter image description here
Detail.html
{% block content %}
<div class="product-detail">
<img src="{% if product.image %}{{ product.image.url }}{% else %}{% static "img/no_image.png" %}{% endif %}">
<h1>{{ product.name }}</h1>
<h2>{{ product.category }}</h2>
<p class="price">${{ product.price }}</p>
<form action="{% url "cart:cart_add" product.id %}" method="post">
{{ cart_product_form }}
{% csrf_token %}
{% if request.user.is_staff %}
Edit Product
{% endif %}
<input type="submit" value="Add to cart">
</form>
{{ product.description|linebreaks }}
You should try to understand the error:
NoReverseMatch Reverse for 'Edit_Product' with no arguments not found.
This error is saying that you asked Django to reverse a url pattern with the name Edit_Product, that it expects an argument but no argument was given.
Indeed, this is your path:
path('shop/product/Edit_Product/<int:id>', views.Edit_Product, name='Edit_Product')
so in order to reverse it, you need to pass it the argument id:
# in a view
from django.urls import reverse
reverse('Edit_Product', kwargs={'id': <some_id>})
# in a template
{% url 'Edit_Product' id=<some_id> %}
You can now just search in your entire project for reverse('Edit_Product' and {% url 'Edit_Product' or narrow it down like this:
First, this is not an error in your Edit_Product view (at least not necessarily), it can happen in any view that reverses the url pattern. You need to look at the rest of the error message which tells you which url was requested or which view was used.
You already saw that this was happening in the product_detail() view, in the render() method actually.
So the error was triggered when rendering the template, in this case the detail.html template. Here you should check for {% url 'Edit_Product' ... %}.
There you have it, {% url 'Edit_Product' %} with no argument. Fix it by adding the product.id.
I am a beginner in Django. Right now, I am learning the framework by building an app, called PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models and their reviews.
Right now, I am trying to use slug in URLs. I have successfully used slug in two of my templates, which are index.html and phonemodel.html. However, I am facing issues with the third template, which is details.html.
When I go to http://127.0.0.1:8000/index, I see this page:
When I click on Samsung, I see this page:
Up to this is fine.
But when I click on any phone model, like Galaxy S10, I get 404 error. It looks like this:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/details/galaxy-s10
Raised by: PhoneReview.views.ReviewView
No review found matching the query
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
When I click on Samsung, I am supposed to see the details.html page, which has the review of the phone, along with the news link. Instead, I am getting the 404 error.
Here are my codes of models.py located inside PhoneReview folder:
from django.db import models
from django.template.defaultfilters import slugify
# Create your models here.
class Brand(models.Model):
brand_name = models.CharField(max_length=100)
origin = models.CharField(max_length=100)
manufacturing_since = models.CharField(max_length=100, null=True, blank=True)
slug = models.SlugField(max_length=150, null=True, blank=True)
def __str__(self):
return self.brand_name
def save(self, *args, **kwargs):
self.slug = slugify(self.brand_name)
super().save(*args, **kwargs)
class PhoneModel(models.Model):
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
model_name = models.CharField(max_length=100)
launch_date = models.CharField(max_length=100)
platform = models.CharField(max_length=100)
slug = models.SlugField(max_length=150, null=True, blank=True)
def __str__(self):
return self.model_name
def save(self, *args, **kwargs):
self.slug = slugify(self.model_name)
super().save(*args, **kwargs)
class Review(models.Model):
phone_model = models.ManyToManyField(PhoneModel, related_name='reviews')
review_article = models.TextField()
date_published = models.DateField(auto_now=True)
slug = models.SlugField(max_length=150, null=True, blank=True)
link = models.TextField(max_length=150, null=True, blank=True)
def __str__(self):
return self.review_article
Here are my codes of urls.py located inside PhoneReview folder:
from . import views
from django.urls import path
app_name = 'PhoneReview'
urlpatterns = [
path('index', views.BrandListView.as_view(), name='brandlist'),
path('phonemodel/<slug:slug>', views.ModelView.as_view(), name='modellist'),
path('details/<slug:slug>', views.ReviewView.as_view(), name='details'),
]
Here are my codes of views.py located inside PhoneReview folder:
from django.shortcuts import render, get_object_or_404
from django.views import generic
from .models import Brand, PhoneModel, Review
class BrandListView(generic.ListView):
template_name = 'PhoneReview/index.html'
context_object_name = 'all_brands'
def get_queryset(self):
return Brand.objects.all()
class ModelView(generic.ListView):
template_name = 'PhoneReview/phonemodel.html'
context_object_name = 'all_model_name'
def get_queryset(self):
self.brand = get_object_or_404(Brand, slug=self.kwargs['slug'])
return PhoneModel.objects.filter(brand=self.brand)
class ReviewView(generic.DetailView):
model = Review
template_name = 'PhoneReview/details.html'
Here are my codes of apps.py located inside PhoneReview folder:
from django.apps import AppConfig
class PhonereviewConfig(AppConfig):
name = 'PhoneReview'
Here are my codes of index.html located inside templates folder:
{% extends 'PhoneReview/base.html' %}
{% load static %}
{% block title%}
Brand List
{% endblock %}
{% block content %}
<!--Page content-->
<h1>This is Brand List Page</h1>
<h2>Here is the list of the brands</h2>
<ul>
{% for brand in all_brands %}
<!-- <li>{{ brand.brand_name }}</li>-->
<li>{{ brand.brand_name }}</li>
{% endfor %}
</ul>
<img src="{% static "images/brandlist.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
{% endblock %}
Here are my codes of phonemodel.html located inside templates folder:
{% extends 'PhoneReview/base.html' %}
{% load static %}
{% block title%}
Phone Model Page
{% endblock %}
{% block content %}
<!--Page content-->
<h1>This is Phone Model Page</h1>
<h2>Here is the phone model</h2>
<ul>
{% for phonemodel in all_model_name %}
<li>{{ phonemodel.model_name }}</li>
{% endfor %}
</ul>
<img src="{% static "images/brandlist.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
{% endblock %}
Here are my codes of details.html located inside templates folder:
{% extends 'PhoneReview/base.html' %}
{% load static %}
<html>
<link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}">
<html lang="en">
{% block title%}Details{% endblock %}
{% block content %}
<h1>This is the Details Page</h1>
<h2>Review:</h2>
<p>{{ review.review_article }}</p>
<h2>News Link:</h2>
<a href={{ review.link }}>{{ review.link }}</a>
{% endblock %}
</html>
Have I made any mistake in models.py or details.html?
I don't think there is an error in the code here. open Django shell by python3 manage.py shell then run the following query
I guess this will probably give NotFound error because there is no model with slug galaxy-s10
from your_app.models import Review
samsung_s10 = Review.objects.get(slug='galaxy-s10')
print(smasung_s10.slug)
This is for a library management web app, I need to filter a specific book object by it's id from a BookIssue object and make it as ISSUED when I click on issue button.
Here Post model have details of book and BookIssue have details of Library Member to borrow book.
When I click on Issue in html, it will go class BookIssueView, fromviews.py I need to change the value of issued field of Post model to True
See post = Post.objects.filter(id=self.request.GET.get('id')).update(issued=True) in views.py
Here I need to get the specific book that I selected by it's id.
How can I implement it?
models.py
class Post(models.Model):
title = models.CharField(max_length=100)
book_author = models.CharField(default="",max_length=100)
publisher = models.CharField(default="",max_length=100)
content = models.TextField(max_length=200)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
issued = models.BooleanField(default=False)
issued_to = models.CharField(default="",max_length=100,null=False)
issue_to_phone_number = models.CharField(default="",max_length=10)
def __str__(self):
return [self.title,self.id]
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk' : self.pk})
class BookIssue(models.Model):
issue_name = models.CharField(max_length=100,null=False)
issue_email = models.EmailField(max_length=254)
issue_phone_number = models.CharField(default="",max_length=10)
issue_address = models.TextField(max_length=300)
issued_book = models.ManyToManyField(Post,default="")
def __str__(self):
return self.issue_name
def get_absolute_url(self):
return reverse('blog-home')
views.py
class BookIssueView(LoginRequiredMixin,CreateView,Post):
model = BookIssue
fields = ['issue_name','issue_email','issue_phone_number','issue_address']
def form_valid(self, form):
post = Post.objects.filter(id=self.request.GET.get('id')).update(issued=True)
form.instance.author = self.request.user
return super().form_valid(form)
Template
bookissue_form.html
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="post">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Issue Book</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-success" type="submit" name="button">Issue</button>
<button class="btn btn-danger" type="submit" name="button">Cancel</button>
</div>
</form>
</div>
{% endblock %}
urls.py
from django.urls import path
from . import views
from .views import (PostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView,
BookIssueView,
BookReturnView)
urlpatterns = [
# path('',views.home, name='blog-home'),
path('',PostListView.as_view(), name='blog-home'),
path('post/<int:pk>/',PostDetailView.as_view(), name='post-detail'),
path('post/new/',PostCreateView.as_view(), name='post-create'),
path('post/<int:pk>/update/',PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/delete/',PostDeleteView.as_view(), name='post-delete'),
path('post/<int:pk>/issue/',BookIssueView.as_view(), name='book-issue'),
path('post/<int:pk>/return/',BookReturnView.as_view(), name='book-return'),
path('about/',views.about, name='blog-about'),
]
The id is not in request.GET, it is in the pk kwarg of the URL.
Also, you don't seem to be doing anything to associate the Post with the BookIssue.
post = Post.objects.get(id=self.kwargs["pk"])
post.issued=True
post.save()
response = super().form_valid(form)
form.instance.issued_book.add(post)
return response
I'am begginer in Django so please try to understand me.
I have a problem with the blocks in my django project. I created the base.html like this
{% include 'firmy/header.html' %}
<html>
<body>
<h4>Ostatnio dodane</h4>
{% block firmy %}
{% endblock %}
<h4>Kategorie</h4>
{% block kategorie %}
{% endblock %}
</body>
{% include 'firmy/footer.html' %}
</html>
and {%block firmy%} showing me every records what I want from another file but the {%block kategorie%} showing nothing.
in views.py I have the code:
from django.shortcuts import render
from .models import Witryna, Kategorie
from django.utils import timezone
def widok_strony(request):
firmy = Witryna.objects.filter(data_publikacji__lte=timezone.now()).order_by('data_publikacji')
return render(request, 'firmy/widok_strony.html', {'firmy': firmy})
def widok_kategorii(request):
kategorie = Kategorie.objects.all().order_by('glowna')
return render(request, 'firmy/widok_kategorii.html', {'kategorie': kategorie})
and in urls.py i have the code :
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.widok_strony, name='widok_strony'),
url(r'^$', views.widok_kategorii, name='widok_kategorii'),
]
and on the end models.py
from django.db import models
from django.utils import timezone
class Kategorie(models.Model):
glowna = models.CharField(max_length=150, verbose_name='Kategoria')
class Meta:
verbose_name='Kategoria'
verbose_name_plural='Kategorie'
def __str__(self):
return self.glowna
class Witryna(models.Model):
nazwa = models.CharField(default="", max_length=150, verbose_name = 'Nazwa strony')
adres_www = models.CharField(max_length=70, verbose_name='Adres www')
slug = models.SlugField(max_length=250, verbose_name='Przyjazny adres url')
email = models.CharField(max_length=100, verbose_name='Adres e-mail')
text = models.TextField(max_length=3000, verbose_name='Opis strony')
kategoria = models.ForeignKey(Kategorie, verbose_name='Kategoria')
data_publikacji = models.DateTimeField(blank=True, null=True, verbose_name='Data publikacji')
class Meta:
verbose_name='Strona www'
verbose_name_plural = 'Strony www'
def publikacja(self):
self.data_publikacji=timezone.now()
self.save()
def __str__(self):
return self.nazwa
and widok_kategorii.html
{% extends 'firmy/base.html' %}
{% block kategorie %}
{% for kategoria in kategorie %}
<p>{{ kategoria.glowna }}</p>
{% endfor %}
{% endblock kategorie %}
Really I don't know where is the problem but when I open the browser on localhost:8000 the I can't see the details from class Kategorie.
You have a huge misconception about how views and URLs work.
A URL can only be served by one view. That view will be entirely responsible for creating the response, which it usually does by rendering a single template. You need to pass all the information for your template from that view.