Related
When rendering a new page, the html form action on that new page is stopping the page from being rendered... even though it has nothing to do with the page itself being rendered (if I remove that one line of HTML code, the page loads just fine). I've been working on solving this problem for over 3 days, tried hundreds of possible solutions, nothing works. Please help
This is the error:
NoReverseMatch at /newgallery/rodneyadmin
Reverse for 'editgallery' with arguments '('rodneyadmin', '')' not found. 1 pattern(s) tried: ['editgallery/(?P<username>[^/]+)/(?P<new_gallery>[0-9]+)\\Z']
Request Method: GET
Request URL: http://127.0.0.1:8000/newgallery/rodneyadmin
Django Version: 4.0
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'editgallery' with arguments '('rodneyadmin', '')' not found. 1 pattern(s) tried: ['editgallery/(?P<username>[^/]+)/(?P<new_gallery>[0-9]+)\\Z']
Exception Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/urls/resolvers.py, line 729, in _reverse_with_prefix
Python Executable: /Library/Frameworks/Python.framework/Versions/3.9/bin/python3
Python Version: 3.9.7
Python Path:
['/Users/rodneyrussell/Desktop/github/Capstone/Capstone',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload',
'/Users/rodneyrussell/Library/Python/3.9/lib/python/site-packages',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages']
Server time: Thu, 10 Feb 2022 16:41:21 -0500
Error during template rendering
In template /Users/rodneyrussell/Desktop/github/Capstone/Capstone/templates/galleries/newgallery.html, error at line 21
Reverse for 'editgallery' with arguments '('rodneyadmin', '')' not found. 1 pattern(s) tried: ['editgallery/(?P<username>[^/]+)/(?P<new_gallery>[0-9]+)\\Z']
11 Create new gallery
12 </h1>
13 </div>
14 </div>
15
16
17 <div class="row mb-3 d-flex justify-content-center">
18
19 <div class="col-lg-4 col-med-8 col-sm-8 text-primary" style="height: fit-content;">
20
21 <form action="{% url 'gallery_app:editgallery' user.username new_gallery.id %} " style="font-weight: bolder;" enctype='multipart/form-data' method='POST' class='gap-2'>
22
23 {% csrf_token %}
24
25
26 <div class="form-group mb-5">
27 <label style="margin-right: 20px;">Public Gallery</label>
28 {{form.public_gallery}}
29 </div>
30
31 <div class="form-group mb-5">
This is the line of code being highlighted as cause for error (form action):
<form action="{% url 'gallery_app:editgallery' user.username new_gallery.id %} " style="font-weight: bolder;" enctype='multipart/form-data' method='POST' class='gap-2'>
Views.py:
#login_required
def newgallery(request, username):
if request.method == 'GET':
form = NewGalleryForm
context = {
'form': form,
'username': username,
}
return render(request, 'galleries/newgallery.html', context)
def editgallery(request, username):
if request.method == "POST":
form = NewGalleryForm(request.POST)
if form.is_valid():
new_gallery = form.save(commit = False)
## connect the new gallery with the user (foreign key)
new_gallery.user = request.user
new_gallery.save()
url = "https://api.opensea.io/api/v1/assets?order_direction=desc&offset=0&limit=5"
params={'owner': new_gallery.wallett_address}
headers = {
"Accept": "application/json",
"X-API-KEY": ""
}
response = requests.request("GET", url, headers=headers, params=params)
response = response.json()["assets"]
list_of_nfts = []
for dictionary in response:
token_id = dictionary["token_id"]
token_address = dictionary["asset_contract"]["address"]
contract_address = 'https://api.opensea.io/api/v1/asset/' + token_address + '/' + token_id + '/'
name = dictionary["name"]
if len(name) > 50:
name = (name[:50] + '...')
nft_created_date = dictionary["asset_contract"]["created_date"]
nft_created_date = nft_created_date[:10]
nft_created_date = datetime.strptime(nft_created_date, '%Y-%m-%d').strftime('%m/%d/%Y')
image = dictionary["image_url"]
description = dictionary["description"]
if description is not None and '*' in description:
head, sep, tail = description.partition('*')
description = head
if description is not None and len(description) > 50:
description = (description[:150] + '...')
if isinstance(description, str) != True:
description = 'No description provided'
link = dictionary["permalink"]
nft_dict = {
'contract_address': contract_address,
'name': name,
'image': image,
'description': description,
'link': link,
'nft_created_date': nft_created_date,
}
list_of_nfts.append(nft_dict)
context = {
'new_gallery': new_gallery,
'list_of_nfts': list_of_nfts,
'raw_nft_data': json.dumps(list_of_nfts),
'new_gallery_name': new_gallery.gallery_name,
'user': new_gallery.user,
username:username,
}
return render(request, 'galleries/editgallery.html', context)
New Gallery HTML (page where user enters basic information regarding New Gallery that he or she is creating... when this form is submitted, the user is brought to a page where they can edit the gallery that was just created (by edit, I mean add new NFT's to that gallery):
<div class="row mb-3">
<div class="col-lg-12 col-sm-12 text-primary d-flex justify-content-center align-items-center">
<h1
class="homepagetitle mt-4 mb-5"
style="font-size: 2.4rem; color: rgb(231, 114, 208)"
>
Create new gallery
</h1>
</div>
</div>
<div class="row mb-3 d-flex justify-content-center">
<div class="col-lg-4 col-med-8 col-sm-8 text-primary" style="height: fit-content;">
<form action="{% url 'gallery_app:editgallery' user.username new_gallery.id %} " style="font-weight: bolder;" enctype='multipart/form-data' method='POST' class='gap-2'>
{% csrf_token %}
<div class="form-group mb-5">
<label style="margin-right: 20px;">Public Gallery</label>
{{form.public_gallery}}
</div>
<div class="form-group mb-5">
<label>Gallery Name </label>
{{form.gallery_name}}
</div>
<div class="form-group mb-5">
<label>Wallett Address</label>
<span class="hovertext" style="color: rgb(231, 114, 208); font-weight: normal;" data-hover="You will be adding NFT's from this wallet. Max wallet size: 50 NFT's">?</span>
{{form.wallett_address}}
</div>
<div class="form-group mb-5">
<label style="margin-right: 20px;">Category </label>
{{form.gallery_category}}
</div>
<button
type="submit"
class="btn btn-dark mt-4 mb-4"
style="
font-size: 1.1rem;
height: 50px;
width:fit-content;
"
>
Add NFT's   <i class="far fa-arrow-alt-circle-right"></i>
</button>
</form>
</div>
</div>
User Profile HTML (page where user clicks on an a tag to bring them to the the New Gallery HTML (the other HTML I have listed above). That is when the code breaks and gives that error. The url in that a tag is href="{% url 'gallery_app:newgallery' user.username %}":
<h1 class="homepagetitle mt-4 mb-5 d-flex justify-content-center align-items-center" style="font-size: 2.4rem; color: rgb(231, 114, 208);">
Hello 
<span style="font-size: 2.4rem; color: rgb(231, 114, 208);"
>{{user.username}} <i class="far fa-hand-paper" style="font-size: 2.4rem; color: rgb(231, 114, 208);"></i></span
>
</h1>
{% endif %}
<div class="row col-12">
<div class="col-lg-6">
<div class="pt-3 profile-image">
<img
src="{% static user.avatar.url %}"
alt="{{user.username}}'s avatar"
class="rounded-circle shadow"
height="300"
width="275"
/>
</div>
{% if request.user == user %}
<span>
<div class="editicon">
<a
href="{% url 'users_app:update' user.username %}"
style="
color: rgb(226, 81, 197);
-webkit-text-stroke: 1px black;
text-decoration: none;
"
>
<i class="fas fa-user-edit"></i>
</a>
</div>
</span>
{% endif %}
<!-- 'users_app:update' user.username -->
<table class="table profile-margin">
<tbody>
{% if request.user == user %}
<tr>
<th scope="row"></th>
<td>Name:</td>
<td>{{user.first_name}} {{user.last_name}}</td>
</tr>
<tr>
<th scope="row"></th>
<td>Email:</td>
<td>{{user.email}}</td>
</tr>
{% endif %}
<tr>
<th scope="row"></th>
<td>Username:</td>
<td>{{user.username}}</td>
</tr>
<tr>
<th scope="row"></th>
<td>Profile created:</td>
<td>{{user.date_joined|date}}</td>
</tr>
<tr>
<th scope="row"></th>
<td>Galleries:</td>
<td>0</td>
</tr>
<tr>
<th scope="row"></th>
<td>Followers:</td>
<td>0</td>
</tr>
<tr>
<th scope="row"></th>
<td>Following:</td>
<td>0</td>
</tr>
</tbody>
</table>
</div>
<div class="col-lg-6">
{% if request.user.is_authenticated %}
<h3 class=" d-flex homepagetitle" style="justify-content:center; margin-top: 30px; margin-bottom: 0px; padding:10px; height: 75px; font-size: 2.2rem; color: rgb(231, 114, 208);">
<i><a class="homepagetitle far fa-plus-square" href="{% url 'gallery_app:newgallery' user.username %}" style="text-decoration: none; font-size: 2.2rem; color: rgb(231, 114, 208); position:relative; left: -70px; font-size: 2rem;"></i></a>
Your Galleries:
</h3>
{% else %}
<h3 class=" d-flex justify-content-center homepagetitle" style="margin-top: 30px; margin-bottom: 0px; padding:10px; height: 75px; font-size: 2.2rem; color: rgb(231, 114, 208);">
{{user.username}}'s Galleries:
</h3>
{% endif %}
<div class='user-galleries d-flex justify-content-center' style="background-color: rgb(247, 229, 243); border-radius: 8px;">
<div class="gallery-posts py-3">
<table class="table profile-margin" style="color:rgb(231, 114, 208); font-weight: bolder;">
<tbody>
{% for gallery in user.newgallery.all %}
<tr>
<th scope="row"></th>
<td>{{ gallery.gallery_name }}</td>
<td>NFT's: 0</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
Urls.py:
app_name = 'gallery_app'
urlpatterns = [
path('newgallery/<str:username>', views.newgallery, name='newgallery'),
path('editgallery/<str:username>/<int:gallery_id>', views.editgallery, name='editgallery'),
path('galleryview/<str:username>/<int:gallery_id>', views.galleryview, name='galleryview'),
]
It looks like the url argument new_gallery.id is empty when you render the html template.
update: so the template is called from view newgallery.
In your original code there is 2 things to change:
to instantiate the form please add () after NewGalleryForm. Without you just handover a link to the class.
in this view/template you do not yet have an instance of newgallery (just the form). So you can not use newgaller.id. Implement a POST branch in newgallery to save it and remove newgallery.id from the form action and point the action back to newgallery view.
after saving you have a newgallery instance with an id and you can call the edit view if you need to with newgallery in the context
def newgallery(request, username):
if request.method == 'POST':
# save newgallery here
if request.method == 'GET':
form = NewGalleryForm()
context = {
'form': form,
'username': username,
}
return render(request, 'galleries/newgallery.html', context)
<form action="{% url 'gallery_app:newgallery' user.username %} " style .... >
You need to pass the gallery as context into the view that has the edit form. I don't see in the views that you posted that you have a detail view but I do see a detail view url. So I'm assuming you're passing the edit form to your create view instead? That view doesn't return a context with new_gallery as a context variable. I would create a detail view for your gallery instead and pass the edit form, user and gallery as context to the template.
Reverse for 'editgallery' with arguments '('rodneyadmin', '')' not found.
New context
def galleryview(request, username, gallery_id):
# Logic
gallery = get_object_or_404(Gallery, pk=gallery_id)
context = {
'form': form,
'username': username,
'new_gallery': gallery,
}
# return an html response with context
Also, when you instantiate an unbound form you should add parenthesis after it.
form = NewGalleryForm()
i am trying to develop a django webapp .i want the user to be able to submit other and get redirected to the user's platform where the user sees all his orders . i want a system where the user can make orders and get redirected to a page where will see all his orders
client form:
{% extends 'base.html' %}
{% load static %}
{% load crispy_forms_tags %}
{% block content %}
{% if user.is_authenticated %}
<div class="container" style="width: 50rem;">
<div class="col-md-10 offset-md-1 mt-5">
<div class="jumbotron">
<!--<h3 id="form-title">Job Specification </h3>-->
<h3 class="display-4" style="text-align: center;">Service Request</h3>
<p id="form-title" style="color: #343a40; text-align: center;">Please provide us with the following information</p>
<hr class="my-4">
<form action="{% url 'clients:add_item' %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<div class="col-md-4">
{{ form.job_name|as_crispy_field }}
</div>
<div class="col-md-8">
{{ form.text_description|as_crispy_field }}
</div>
</div>
<div class="row">
<div class="col-md-4">
{{ form.location|as_crispy_field }}
</div>
<div class="col-md-8">
{{ form.address|as_crispy_field }}
</div>
</div>
<div class="row">
<div class="col-md-6">
<!--{{ form.phone|as_crispy_field }}-->
<input style="height: 2.5rem;margin: 0 0 8px 0; width: 100%; text-align: center; position: relative; " type="text" name="phone" value="{{ user.details.phone }}" readonly><br>
</div>
<div class="col-md-6">
<input style="height: 2.5rem;margin: 0 0 8px 0; width: 100%; text-align: center; position: relative; " type="text" name="email" value="{{user.email}}" placeholder=" email " readonly><br>
</div>
</div>
<div class="row">
<div class="col-md-6">
{{ form.status|as_crispy_field }}
</div>
<div class="col-md-6" style="height: 2rem;">
<!---{{ form.customer|as_crispy_field }}-->
<input style="height: 2.5rem;margin: 0 0 8px 0; width: 100%; text-align: center; position: relative; top: 30px;" type="text" name="customer" value="{{ user.username}}" placeholder="username" readonly><br>
</div>-->
</div>
<div class="col-md-6">
<input style="height: 2.5rem;margin: 0 0 8px 0; width: 100%; text-align: center; position: relative; " type="text" name="id" value="{{ user.details.id }}" placeholder=" id " readonly><br>
</div>
<h2>
<!-- Your template -->
</h2>
<!--<div class="d-flex justify-content-center mt-3 login_container">
<input class="btn login_btn" type="submit" value="Submit">
</div>-->
<button role="button" class="btn btn-danger btn-lg">Submit</button>
</form>
</div>
</div>
</div>
{{ form.errors }}
{% else %}
<div class="container" style="width: 20rem; background-color: #6e1a52; margin-top: 70px; height: 20rem;" >
<div class="col-md-10 offset-md-1 mt-5" >
<!--<div class="jumbotron">
<h3 id="form-title" style="text-align: center;">Please login to enable you request the service you want</h3>-->
<h3 class="display-44" style="text-align: center; font-size: 22px; margin-top: 50px; color: #343a40;">request service</h3>
<p id="form-title" >Please login to enable you request the service you want</p>
<a href="{% url 'accounts:login' %}"
style="font-size: 24px; text-align: center; text-decoration: none;" >Login</a>
<!-- <a action="{% url 'profession:add_item' %}" role="button" class="btn btn-primary btn-lg">Submit</a>-->
</div>
</div>
{% endif %}
view file for client view:
#login_required
def insert_ClientJob(request):
if request.method == 'POST':
form = ClientJobForms(request.POST)
user_id=request.POST.get('id')
if form.is_valid():
product = form.save(commit=False)
#customer = ClientJob.objects.create(customer=product)
#product.customer =customer
product.save()
messages.success(request ,"successful")
return redirect('profession:user',user_id)
else:
form = ClientJobForms()
return render(request ,'job_request.html' ,{'form': form})
url file client url:
om django.urls import path
from .views import *
from .import views
app_name = 'clients'
urlpatterns = [
path('add_item/', views.insert_ClientJob ,name='add_item'),
]
model file client model:
from django.db import models
# Create your models here.
class ClientJob(models.Model):
STATUS = (
('Pending', 'Pending'),
#('On-going', 'On-going'),
('Completed', 'Completed'),
)
customer = models.ForeignKey('accounts.Customer', null=True,blank=True, on_delete= models.SET_NULL,related_name='client')
job_name = models.CharField(max_length=50,unique =False)
text_description = models.CharField(max_length=150,null=True)
location = models.ForeignKey('accounts.Area' ,on_delete =models.CASCADE)
address = models.CharField(max_length=200,unique =False)
phone =models.CharField(max_length=15,unique =False)
email = models.EmailField(unique = False)
date_created = models.DateTimeField(auto_now_add=True, null=True)
status = models.CharField(max_length=200, null=True, choices=STATUS,default='Pending')
def __str__(self):
return self.job_name
class Meta:
verbose_name_plural = "Client Job"
form file client form:
from django.db.models import fields
from django.forms import ModelForm
from django import forms
from django.contrib.auth.models import User
from .models import *
class ClientJobForms(ModelForm):
class Meta:
model = ClientJob
fields = ['job_name','text_description','location','address','phone','email','status','customer']
#fields ="__all__"
def __init__(self, *args, **kwargs):
super(ClientJobForms, self).__init__(*args, **kwargs)
self.fields['location'].empty_label ='Your location'
admin file client admin:
list_display = ('id','job_name','text_description','location','address','phone','email','date_created','status','customer')
admin.site.register(ClientJob ,ClientJobAdmin)
accounts model:
class Area(models.Model):
area_code = models.CharField(max_length=7)
location = models.CharField(max_length=100)
def __str__(self):
return self.location
class Meta:
verbose_name_plural = "Area"
class Customer(models.Model):
user = models.OneToOneField(User,null=True,blank=True, on_delete= models.SET_NULL,related_name='details')
address = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=15, null=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return str(self.user)
The error is raised :
Page not found (404) No cart matches the given query.
Request Method: GET Request
URL: http://127.0.0.1:8000/change_quan?cid=1&quantity=2
Raised by: myapp.views.change_quan
when i am trying to save quantity value in database
i tried but this error raised always
my views.py
def productcart(request):
context = {}
items = cart.objects.filter(user__id=request.user.id,status=False)
context["items"] = items
if request.user.is_authenticated:
if request.method=="POST":
pid = request.POST["pid"]
qty = request.POST["qty"]
img = request.POST["img"]
dis_price = request.POST["dis_price"]
is_exist = cart.objects.filter(product__id=pid,user__id=request.user.id,status=False)
if len(is_exist)>0:
context["msg"] = "item already exist in cart"
context["cls"] = "alert alert-warning"
else:
product = get_object_or_404(Product,id=pid)
usr = get_object_or_404(User,id=request.user.id)
c = cart(user=usr,product=product,quantity=qty,image=img,total_price=dis_price)
c.save()
context["msg"] = "{} Added in cart".format(product.name)
context["cls"] = "alert alert-success"
else:
context["status"] = "Please login first to add products to cart"
return render(request,'E-commerce-cart.html',context)
def get_cart_data(request):
items = cart.objects.filter(user__id=request.user.id,status=False)
sale,total,quantity=0,0,0
for i in items:
sale+=i.product.discount
total+=i.product.price
quantity+=i.quantity
res={
"total":total,"offer":sale,"quan":quantity
}
return JsonResponse(res)
def change_quan(request):
qty = request.GET["quantity"]
cid = request.GET["cid"]
print(request.GET)
cart_obj = get_object_or_404(cart,id=cid)
cart_obj.quantity = qty
cart_obj.save()
return HttpResponse(1)
my urls.py
"""emarket URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from os import name
from django.contrib import admin
from django.urls import path
from myapp import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.home,name='home'),
path('shop/',views.shop,name='shop'),
path('login/',views.create_user,name='login'),
path('logout/',views.user_logout,name='logout'),
path('cart/',views.productcart,name='cart'),
path('checkout/',views.checkout,name='checkout'),
path('product_detail/',views.product_detail,name='prodct-detail'),
path('find_us/',views.find_us,name='find'),
path('blog/',views.blog,name='blog'),
path('base/',views.base),
path('api/categories',views.all_categories,name="all_categories"),
path('api/brand',views.brand,name="brand"),
path('api/products',views.product_filter_api,name="product_filter_api"),
path('user_check/',views.check_user,name="check_user"),
path('filter_product/',views.filter_product,name="filter_product"),
path('add_to_favourite/',views.add_to_favourite,name="add_to_favourite"),
path('all_favourites/',views.all_favourites,name="all_favourites"),
path('forgotpass',views.forgotpass,name="forgotpass"),
path('resetpass',views.resetpass,name="resetpass"),
path('get_cart_data',views.get_cart_data,name="get_cart_data"),
path('change_quan',views.change_quan,name='change_quan'),
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
my models.py
class cart(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
product = models.ForeignKey(Product,on_delete=models.CASCADE)
image = models.ImageField(default=False)
total_price=models.FloatField(default=False)
quantity = models.IntegerField()
status = models.BooleanField(default=False)
added_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
def __str__(self):
return self.user.username
my html code
{% extends 'base.html' %}
{% block head %}
<style>
.k{height: 1px;background-color: rgb(211, 207, 207);}
.s{color:rgb(240, 240, 240);
letter-spacing: 3px;
font-family:-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
font-weight: 400;}
.cncl_icn{
float: left;
margin: 15px;
padding-top: 10px;
}
.a:hover{
background-color:rgba(152, 209, 255, 0.705);color: rgb(255, 255, 255);box-shadow:0px 0px 7px 7px rgba(204, 201, 201, 0.5) ;
}
#media screen and (max-width:680px){
.b{opacity: 0;}
/* .v{position: absolute;top: 5px;} */
.s{font-size: 15px;}
}
#media screen and (min-width:1024px){
.s{font-size: 20px;}
}
</style>
{% endblock %}
{% block body %}
{% if user.is_superuser %}
<div class="container-fluid "></div>
<h1 class="jumbotron my-5" >you are not Allowed here</h1>
{% else %}
{% if status %}
<h1 class="jumbotron my-5">{{status}}</h1>
{% else %}
{% if msg %}
<div class="{{cls}}">{{msg}}</div>
{% endif %}
<div class="row v " style="margin-right: 0%;">
<div class="col-lg-7" >
<div class="row text-center p-3 b" style="background-color: rgba(2, 184, 184, 0.863); background-attachment: fixed;">
<div class="col-md-3 "> <h3 class="s">Product</h3></div>
<div class="col-md-3 "><h3 class="s">Price</h3></div>
<div class="col-md-3 "><h3 class="s">Qantity</h3></div>
<div class="col-md-3 "><h3 class="s">Total</h3></div>
</div>
{% for i in items %}
<div class="row a border-bottom" id="col{{i.product.id}}">
<div class="col-md-3 text-center " >
<i class="far fa-times-circle cncl_icn" id="cross{{i.product.id}}" style="font-size: 30px;"></i>
<img class="mt-4" src="/media/{{i.image}}" alt="check ur internet!" height="150px">
<h4 class="ml-5" style="color: black;">{{i.product.name}}</h4>
<p class="ml-5">Size:{{i.product.size}} , color:{{i.product.color}}</p>
</div>
<div class="col-md-3 text-center mt-5">
{%if i.total_price < i.product.price%}
<del style="font-weight: bold; color: grey;" >${{i.product.price}}</del> $<p class="d-inline" style="font-weight: bold;" id="price{{i.product.id}}">{{i.total_price}}</p>
{% else %}
$<p class="d-inline" style="font-weight: bold;" id="price{{i.product.id}}">{{i.product.price}}</p>
{% endif %}
</div>
<div class="col-md-3 text-center">
<div class="form-group mt-4">
<div class="input-group">
<div class="input-group-btn ">
<button id="down" class="btn btn-default" onclick="change_quan('{{i.product.id}}','minus')" style="font-size: 25px;background: none;border: none;font-weight: bold;">-</button>
</div>
<input type="number" id="cart{{i.product.id}}" class="form-control text-center pt-3" value="{{i.quantity}}" style="width: 30px;border: none;font-weight: bold;background: none;">
<div class="input-group-btn">
<button id="up" class="btn btn-default" onclick="change_quan('{{i.product.id}}','plus')" style="font-size: 25px;background: none;border: none;font-weight: bold;">+</button>
</div>
</div>
</div>
</div>
<div class="col-md-3 mt-5 text-center">
{%if i.total_price < i.product.price %}
$<p class="d-inline" style="font-weight: bold;" id="total{{i.product.id}}">{{i.total_price}}</p>
{% else %}
$<p class="d-inline" style="font-weight: bold;" id="total{{i.product.id}}">{{i.product.price}}</p>
{% endif %}
</div>
</div>
<script>
$(function() {
$("#cross{{i.product.id}}").hover(function() {
$("#cross{{i.product.id}}").toggleClass("fas fa-times-circle").toggleClass("far fa-times-circle")
})
// to remove product from cart
$("#cross{{i.product.id}}").confirm({
title: 'Confirm',
content: 'Are you sure to remove this product from cart',
theme: 'modern',
buttons:{
confirm: function() {
$('#col{{i.product.id}}').remove()
},
cancel: function (){}
}
})
})
</script>
{% endfor %}
</div>
<script>
function grandTotal(){
$.ajax({
url:"{% url 'get_cart_data' %}",
type:'get',
success:function(data){
p = Math.round((data.offer/data.total)*100,2)
$('.item_total').html("$"+data.total)
$('#offer').html("$"+data.offer)
$('#per').html("("+p+"%)")
$('#quantity').html(data.quan)
c = (data.total)-(data.offer)
$('#grand_Total').html("$"+c)
}
})
}
grandTotal()
function change_quan(id,action){
let old = $("#cart"+id).val();
quan = 0
if(action=="plus"){
quan+=parseInt(old)+1
$('#total'+id).text( parseFloat($('#total'+id).text()) + parseFloat($('#price'+id).text()))
}
else{
quan+=parseInt(old)-1
$('#total'+id).text( parseFloat($('#total'+id).text()) - parseFloat($('#price'+id).text()))
}
$("#cart"+id).val(quan);
$.ajax({
url:"{% url 'change_quan' %}",
type:"get",
data:{cid:id,quantity:quan},
success:function(data){
alert(data)
}
});
}
</script>
<div class="col-md-5 text-center py-5" style="background-color: rgba(255, 176, 218, 0.397);">
<div id="cartt"></div>
<div class="row">
<img src="/static/Images/estore1.png" alt="" height="300px" style="margin: auto;">
</div>
<div class="pb-3 " style="font-size:30px;font-weight: bold;">--------------------</div>
<h4 class="pt-3" style="font-family: Arial, Helvetica, sans-serif;letter-spacing: 3px;text-transform: uppercase;">Total: <span style="font-size: 28px;" class="item_total"></span></h4>
<h4 class="pt-1" style="font-family: Arial, Helvetica, sans-serif;letter-spacing: 3px;text-transform: uppercase;">Quantity: <span style="font-size: 28px;" id="quantity"></span><span style="text-transform: none;"> Items</span></h4>
<h4 class="pt-1" style="font-family: Arial, Helvetica, sans-serif;letter-spacing: 3px;text-transform: uppercase;">You Saved: <span style="font-size: 28px;" id="offer"></span><span class='text-success'style="font-size: 20px;" id="per"></span></h4>
<h4 class="py-1" style="font-family: Arial, Helvetica, sans-serif;letter-spacing: 3px;text-transform: uppercase;">Grand Total: <del style="font-size: 25px; color:grey;" class="item_total"></del><span style="font-size: 28px;" id="grand_Total"></span></h4>
<h4 class="pt-3">Shipping charges will calculated at checkout</h4>
<form class="pt-3" action="" >
<!-- <input type="text" placeholder="Coupon code.." name="cod" class="mt-3 text-center" style="letter-spacing: 2px;font-size: 20px;border-radius: 25px;width: 250px;height: 47px;background-color: rgb(255, 255, 255);border:2px solid thistle;" >
<input type="submit" class="mt-3" value="Apply Code"name="acd" style="letter-spacing: 2px;font-size: 25px;border-radius: 25px;border: none;width: 250px;height: 45px;background-color: rgb(161, 158, 158);color: rgb(255, 255, 255);" > -->
<input type="submit" value="CHECKOUT" name="che" class="mt-5" style="letter-spacing: 2px;font-size: 25px;border-radius: 25px;border: none;width: 250px;height: 45px;background-color: black;color: rgb(255, 255, 255);" >
</form>
</div>
</div>
{% endif %}
</div>
{% endif %}
{% endblock %}
if data does not exist 'get_object_or_404' will throw 404 error, As per your request You are trying to retrieve data with primary key 1, but data is not available
That’s why you get this error. so please check you table or try with other pk value
def change_quan(request):
qty = request.GET["quantity"]
cid = request.GET["cid"]
print(request.GET)
cart_obj = get_object_or_404(cart,id=cid) # please check this cid value
cart_obj.quantity = qty
cart_obj.save()
return HttpResponse(1)
get_object_or_404 is not the correct choice here. Since object with id=cid was not found in database, 404 error was raised. This is the expected behaviour of get_object_or_404.
Did you mean to use get_or_create object incase the object that is trying to be fetched from database is not found?
I've seen other posts about this but still, I'm too dumb :/
So I have this site with products, each product has its unique page-detail where you can leave comments. And now I want to add the possibility to 'star-rate' the product when you write a comment, like in the picture.
Im guessing the first step is to add an Integer field on the "comments model" . But what are the steps from now on ? Im guessing a little JS is needed but i don't rlly know js :/
models.py
class CommentsModel(models.Model):
user = models.ForeignKey(User,on_delete=models.SET_NULL, null=True)
component = models.ForeignKey(ProductsModel,on_delete=models.SET_NULL, null=True)
text = models.TextField(null=False)
date = models.DateTimeField(default=timezone.now)
rating = models.IntegerField(default=0,
validators = [
MaxValueValidator(5),
MinValueValidator(0),
]
)
def __str__(self):
return '%s %s' % (self.component.name, self.user.username)
views.py
def comments_view(request, id):
component = get_object_or_404(ProductsModel, id = id)
comments = CommentsModel.objects.filter(component = component).order_by('-id')
if request.method == 'POST':
comment_form = CommentsForm(request.POST or None)
if comment_form.is_valid():
text = request.POST.get('text')
comment_form = CommentsModel.objects.create(component=component, user=request.user, text=text)
comment_form.save()
return HttpResponseRedirect(component.get_absolute_url())
else:
comment_form = CommentsForm()
context = {'object':component, 'object2':comments, 'comment_form':comment_form}
return render(request, 'templates/comments/comments.html', context)
this is my site with some stars in the template referring how I d like to look and work
forms.py
class CommentsForm(forms.ModelForm):
class Meta:
model = CommentsModel
fields = [
'text',
]
template(just the part with the comments) :
<div class="container">
<form method="post">
{% csrf_token %}
<button type="submit" class="fa fa-star fa-2x my-btn" id="first"></button>
<button type="submit" class="fa fa-star fa-2x my-btn" id="second"></button>
<button type="submit" class="fa fa-star fa-2x my-btn" id="third"></button>
<button type="submit" class="fa fa-star fa-2x my-btn" id="fourth"></button>
<button type="submit" class="fa fa-star fa-2x my-btn" id="fifth"></button>
<div>
{{ comment_form.text|as_crispy_field }}
</div>
{% if request.user.is_authenticated %}
<input type="submit" value="Posteaza" class="btn btn-primary" style="margin-top: 20px; background-color: white; color: black; border-color: white;">
{% else %}
<input type="submit" value="Submit" class="btn btn-outline-succes" style="margin-top: 20px; background-color: white; color: black; border-color: white;" disabled>
{% endif %}
</form>
<div class="main-comment-section" style="margin-top: 10px;">
{{ object2.count }} Comentarii
{% for index in object2 %}
<figure style="padding-top: 10px;">
<blockquote class="blockquote">
<p style="font-weight: 15px;">{{ index.text }}</p>
</blockquote>
<figcaption class="blockquote-footer">
postat de catre <cite title="Source Title">{{ index.user|capfirst}}</cite>
</figcaption>
</figure>
{% endfor %}
</div>
I am new in django. So i need a help for including a view function within Template. I am searching but i am tired for finding my expectation. i want to use only django template tag. Would you please help me?
{View.py
def singUpLunch(request):
query_results = Menu.objects.all()
form=SingUpForm(request.POST or None)
if form.is_valid():
save_it=form.save(commit=False)
save_it.save()
messages.success(request,'Thanks for your co-operation')
return render_to_response('singUp.html',locals(),context_instance=RequestContext(request))
}
{my model
class SingUp(models.Model):
employee_id = models.AutoField(unique=True,primary_key=True)
name = models.CharField(max_length=20,choices=STATUS_CHOICES)
email = models.EmailField()
date = models.DateField()
lunch = models.BooleanField()
class Meta:
unique_together = ["name", "email","date"]
ordering = ['-date']
USERNAME_FIELD = 'employee_id'
REQUIRED_FIELDS = ['mobile']
def __unicode__(self):
return smart_unicode(self.email)
}
class SingUp(models.Model):
employee_id = models.AutoField(unique=True,primary_key=True)
name = models.CharField(max_length=20,choices=STATUS_CHOICES)
email = models.EmailField()
date = models.DateField() # auto_now_add=True, blank=True default=date.today(),blank=True
lunch = models.BooleanField()
class Meta:
unique_together = ["name", "email","date"]
ordering = ['-date']
USERNAME_FIELD = 'employee_id'
REQUIRED_FIELDS = ['mobile']
def __unicode__(self):
return smart_unicode(self.email)
my Template
{% load url from future %}
{% block content %}
{% if not email %}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Log in</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style>
body
{
margin: 0;
padding: 0;
color: #555;
font: normal 12pt Arial,Helvetica,sans-serif;
background:#ffffff url(check2.jpg) repeat-x;
width: 130%;
height: 100%;
position: fixed;
top: 40px;
left: 480px
}
.span3.well {
min-height: 20px;
padding: 19px;
margin-bottom: 20px;
background-color: #f5f5ff;
border: 1px solid #e3e3e3;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
-moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
}
</style>
</head>
<body>
<head><div class='page-header pagination-centered'><img src=/static/logo.png class='img-rounded pagination-centere' /></div> </head>
{{ state }}
<div class="span3 well" style="height: auto;margin-left: 1.7%;width: 30%;">
<h2>Please Login
New User:  <a href="/signup/">
SignUp</a></h2>
<div class="leftpane">
<form action="" method="post"> {% csrf_token %}
{% if next %}
<input type="hidden" name="next" value="{{ next }}" />
{% endif %}
Email:
<input type="text" name="email" value="{{ email}}" /><br /><br />
password:
<input type="password" name="password" value="" /><br /><br />
<input type="submit" value="Log In" />
</form>
</div>
<div class="aboutus_portion">
</div>
</div>
<!-- <div id="rightcontent">
<li class=" dir"><h3>Admin</h3> </li>
</div>
-->
</body>
</html>
{% else %}
{% include 'singUpLunch' %} # here i want to call the view singUpLunch function
{% endif %}
{% endblock %}
You can see this Django custom template tags
Django expects template tags to live in a folder called 'templatetags' that is in an app module that is in your installed apps...
/my_project/
/my_app/
__init__.py
/templatetags/
__init__.py
my_tags.py
#my_tags.py
from django import template
register = template.Library()
#register.inclusion_tag('other_template.html')
def say_hello(takes_context=True):
return {'name' : 'John'}
#other_template.html
{% if request.user.is_anonymous %}
{# Our inclusion tag accepts a context, which gives us access to the request #}
<p>Hello, Guest.</p>
{% else %}
<p>Hello, {{ name }}.</p>
{% endif %}
#main_template.html
{% load my_tags %}
<p>Blah, blah, blah {% say_hello %}</p>
The inclusion tag renders another template, like you need, but without having to call a view function. Hope that gets you going.