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()
Related
I'm searching for this issue for days... And, unfortunately, couldn't find the answer.
I have a view (Buildings) and I want to add/edit a Building with a modal. With my current code, I can add new Building. However, because I can't pass the id (pk) of an existing Building, I can't update it.
I've two views: one for the table, other for the form. I noticed that, when I POST, my Building view posts, not the newBuilding view.
I tried to get pk from kwargs in newBuilding view, but I can't get it in the post method.
The only thing left is to update..
Let me share my code.
Thanks in advance!
urls.py
path('app/buildings/', login_required(views.Buildings.as_view()), name='buildings'),
path('app/buildings/<int:pk>', login_required(views.NewBuilding.as_view()), name='buildings-pk'),
models.py
class Buildings(TemplateView):
template_name = 'main_app/buildings.html'
model = models.Building
def get_context_data(self, **kwargs):
context = super(Buildings, self).get_context_data(**kwargs)
# Get selected site from cache
active_site = models.Site.objects.filter(id=self.request.session.get('active_site')).get()
context['active_site'] = active_site
filtered_buildings = models.Building.objects
context['buildings'] = filtered_buildings.all()
return context
def get_form_kwargs(self):
kwargs = super(Buildings, self).get_form_kwargs()
kwargs.update({'active_site': self.request.session.get('active_site'), 'edited_building_id': None})
return kwargs
def post(self, request, *args, **kwargs):
if request.method == 'POST':
NewBuilding.post(self, request=request, slug=None)
return HttpResponseRedirect(reverse_lazy('main_app:buildings'))
else:
print("error")
...
class NewBuilding(FormView):
template_name = 'main_app/new/new_building.html'
form_class = forms.NewBuildingForm
active_site = None
def get_context_data(self, **kwargs):
context = super(NewBuilding, self).get_context_data(**kwargs)
# Get selected site from cache
self.active_site = models.Site.objects.filter(id=self.request.session.get('active_site')).get()
context['active_site'] = self.active_site
context['edited_building_id'] = self.kwargs['pk']
return context
def get_form_kwargs(self):
kwargs = super(NewBuilding, self).get_form_kwargs()
kwargs.update({'active_site': self.request.session.get('active_site'),
'edited_building_id': self.kwargs['pk']})
return kwargs
def post(self, request, slug=None, *args, **kwargs):
if request.method == 'POST':
# HERE, I need to assign the building to be edited.
# if kwargs['edited_building_id']:
# new_building = models.Building.objects.get(id=self.kwargs['edited_building'])
# else:
new_building = models.Building()
new_building.site = models.Site.objects.filter(id=self.request.session.get('active_site')).get()
if new_building.name != request.POST.get('name'):
new_building.name = request.POST.get('name')
if new_building.address != request.POST.get('address'):
new_building.address = request.POST.get('address')
new_building.save()
else:
print("error")
buildings.html
<div class="portlet box blue">
<div class="portlet-title">
<div class="tools">
<a href="javascript:;" class="collapse">
</a>
</div>
</div>
<div class="portlet-body">
<div class="table-toolbar">
<div class="row">
<div class="col-md-12">
<div class="btn-group pull-right">
<button id="sample_editable_1_new" class="btn green" data-target="#full-width" data-toggle="modal" href="{% url "main_app:buildings-pk" pk=0%}">
Add New <i class="fa fa-plus"></i>
</button>
</div>
</div>
</div>
</div>
{# modal for new and edited entry#}
<div id="full-width" class="modal container fade" tabindex="-1">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">Add Building</h4>
</div>
<div class="modal-body">
{# modal body#}
</div>
</div>
<table class="table table-striped table-hover table-bordered" id="sample_editable_1">
<thead>
<tr>
<th class="text-center">
Name
</th>
<th class="text-center">
Address
</th>
<th class="text-center">
Type
</th>
<th class="text-center">
Edit
</th>
</tr>
</thead>
<tbody>
{% for building in buildings %}
<tr>
<td>
{{ building.name }}
</td>
<td>
{{ building.address }}
</td>
<td>
{{ building.type | default_if_none:"-" }}
</td>
<td>
<a class="edit" data-target="#full-width" data-toggle="modal" href="{% url "main_app:buildings-pk" pk=building.id%}">
Edit </a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
new_building.html
<form class="form-horizontal" method="POST">
{% csrf_token %}
<div class="form-body">
<div class="form-group last">
<label class="col-md-3 control-label">Site</label>
<div class="col-md-4">
<span class="form-control-static">{{ active_site.name }}</span>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Name</label>
<div class="col-md-4">
{{ form.name }}
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn blue">Submit</button>
<button type="button" class="btn default" data-dismiss="modal">Cancel</button>
</div>
</form>
forms.py
class NewBuildingForm(forms.ModelForm):
active_site = None
edited_building_id = 0
class Meta:
model = models.Building
fields = ["name", "address", "type", "site", "public_area",
"electricity_utility_meter", "water_utility_meter", "gas_utility_meter", "hot_water_utility_meter"]
def __init__(self, *args, **kwargs):
self.active_site = kwargs.pop('active_site')
self.edited_building_id = kwargs.pop('edited_building_id')
super(NewBuildingForm, self).__init__(*args, **kwargs)
edited_building = models.Building.objects.filter(id=self.edited_building_id)
self.fields['name'] = forms.CharField(
widget=forms.TextInput(attrs={'placeholder': 'Name', 'class': 'form-control input-circle'}))
self.fields['address'] = forms.CharField(
widget=forms.TextInput(attrs={'placeholder': 'Address', 'class': 'form-control input-circle'}),
required=False)
if edited_building:
self.fields['name'].initial = edited_building.get().name
self.fields['address'].initial = edited_building.get().address
I try to update kwargs on FormView (because I can get edited_building_id there), but I can't access kwargs on POST https://imgur.com/G7UcmLo
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 am working on a project in Python Djnago 3.1.2, and developing a custom admin side, where admin can perform different functionalities.
At the admin site I want to add functionality to add user and I have created a function but there is some error but I could not get it.
Here is My models.
models.py
class User(AbstractUser):
GENDER = (
(True, 'Male'),
(False, 'Female'),
)
USER_TYPE = (
('Admin', 'Admin'),
('Designer', 'Designer'),
('Customer', 'Customer'),
)
user_id = models.AutoField("User ID", primary_key=True, auto_created=True)
avatar = models.ImageField("User Avatar", null=True, blank=True)
gender = models.BooleanField("Gender", choices=GENDER, default=True)
role = models.CharField("User Type", max_length=10, choices=USER_TYPE, default='Customer')
def __str__(self):
return "{}".format(self.user_id)
This is the function I have created and I think error is in my views.
views.py
def addUser(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('/admin1/addUser')
else:
addUser_show = User.objects.all()
# start paginator logic
paginator = Paginator(addUser_show, 3)
page = request.GET.get('page')
try:
addUser_show = paginator.page(page)
except PageNotAnInteger:
addUser_show = paginator.page(1)
except EmptyPage:
addUser_show = paginator.page(paginator.num_pages)
# end paginator logic
return render(request, 'admin1/addUser.html',
{'addUser_show': addUser_show, "form":form})
urls.py
path('addUser/', views.addUser, name="admin-add-user"),
Form I am using to get the create user form.
forms.py
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'avatar', 'email', 'password1', 'password2', 'gender', 'role']
addUser.html
{% extends 'admin1/layout/master.html' %}
{% block title %}Add User{% endblock %}
{% block main %}
<div class="container">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10">
<button type="button" class="btn btn-primary mt-2" data-toggle="modal" data-target="#modal-primary">Add
User
</button>
<div class="modal fade" id="modal-primary">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add User</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
</div>
<div class="modal-body mt-2">
<form action="{% url 'admin-add-user'%}" method="POST"
enctype="multipart/form-data">
{% csrf_token %}
<table border="1" class="table table-bordered border border-info">
{{form.as_p}}
<div class="modal-footer justify-content-right">
<input type="Submit" name="Submit" value="Submit"
class="btn btn-outline-success">
<button type="button" class="btn btn-outline-danger" data-dismiss="modal">Close
</button>
</div>
</table>
</form>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<br>
<div class="container-fluid ">
<div class="row">
<div class="card mt-2 border border-secondary">
<div class="card-header">
<h3 class="card-title ">Product Table</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<table class="table table-bordered border border-info">
<thead>
<tr>
<th>User Id</th>
<th>User Name</th>
<th>User First Name</th>
<th>User Last Name</th>
<th>User Email</th>
<th>User Gender</th>
<th>User Avatar</th>
<th>Role</th>
<th>Action</th>
</tr>
</thead>
<tbody class="justify-content-center">
{% for x in addUser_show %}
<tr>
<td>{{x.user_id}}</td>
<td>{{x.username}}</td>
<td>{{x.first_name}}</td>
<td>{{x.last_name}}</td>
<td>{{x.email}}</td>
<td>{{x.gender}}</td>
<td><img src="{{x.avatar.url}}" alt="{{x.avatar}}" height="100" width="100">
</td>
<td>{{x.role}}</td>
<td><a href="#"
class="btn btn-outline-primary mt-2"><i
class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
<a href="#"
class="btn btn-outline-danger mt-2"><i
class="fa fa-trash" aria-hidden="true"></i></a>
<a href="#"
class="btn btn-outline-warning mt-2"><i
class="fa fa-eye" aria-hidden="true"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- /.card-body -->
<div class="card-footer clearfix ">
<ul class="pagination pagination-sm m-0 justify-content-center">
{% if addUser_show.has_previous %}
<li class="page-item"><a class="page-link"
href="?page={{product_show.previous_page_number}}">
Previous </a>
</li>
{% endif%}
{% for x in addUser_show.paginator.page_range %}
{% if addUser_show.number == x %}
<li class="page-item active"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% else%}
<li class="page-item"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% endif %}
{% endfor %}
{% if addUser_show.has_next %}
<li class="page-item"><a class="page-link"
href="?page={{addUser_show.next_page_number}}"> Next </a>
</li>
{% endif %}
</ul>
</div>
</div>
<!-- /.card -->
</div>
</div>
</div>
</div>
</div>
{% endblock %}
Here I want to make admin able to create new user. but I am getting error shown below while submission of
form. My form works proper till it display the form , but when I fill up details and submit the form it shows the following error.
If possible please write the answer.
I have tried something and its working for me but I don't know that it is right way to do it or not.
view.py
def addUser(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('/admin1/addUser')
addUser_show = User.objects.all()
# start paginator logic
paginator = Paginator(addUser_show, 3)
page = request.GET.get('page')
try:
addUser_show = paginator.page(page)
except PageNotAnInteger:
addUser_show = paginator.page(1)
except EmptyPage:
addUser_show = paginator.page(paginator.num_pages)
# end paginator logic
return render(request, 'admin1/addUser.html',
{'addUser_show': addUser_show,"form":form})
I have my django app which searches youtube and return result as a dictionary which i render them in template, one of the returned value is link , now I have a download button they way i wish it to function is whenever you click a button it should take the url for the clicked result and pass it to another download function as an argument. How do I accomplish that ?
Here is my view.py
def index(request):
if request.method == 'POST':
query = request.POST['video_name']
n = 12
search = SearchVideos(str(query), offset = 1, mode = "json", max_results = n)
ytresults = search.result()
result_dict = json.loads(ytresults)
context = {
"result" : result_dict,
}
template_name = "youloader/results.html"
return render(request, template_name, context)
else:
query = "no copyright sound"
n = 12
search = SearchVideos(str(query), offset = 1, mode = "json", max_results = n)
index_results = search.result()
result_dict = json.loads(index_results)
context = {
"result" : result_dict
}
template_name = "youloader/index.html"
return render(request, template_name, context)
def downloading_video(request):
try:
with youtube_dl.YoutubeDL(video_opts) as ydl:
ydl.download(link)
except:
pass
here are my template.html
<div class="my-4" >
<div style="padding-top: 20px">
<div class="row" >
{% for result in result.search_result %}
<div class="col-12 col-sm-6 col-md-4 col-lg-4">
<div class="card shadow-sm border-0 my-2">
<img src="{{ result.thumbnails.1 }}" alt="{{ result.channelId }}">
<div class="card-body">
<h5 class="card-title">{{ result.link }}</h5>
<div class="d-flex flex-wrap justify-content-between card-subtitle my-2 text-muted small">
<a href="{{ result.link }}" class="text-secondary font-weight-bold">
<i class="fa fa-tablet mr-1"></i>{{ result.channel }}
</a>
<span><i class="fa fa-stopwatch mr-1"></i>{{ result.duration }}</span>
<span><i class="fa fa-eye mr-1"></i>{{ result.views }}</span>
<button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown">Download</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="#">Audio</a>
<a class="dropdown-item" href="#">Video</a>
</div>
<br>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
and here is the sample of the template rendered.
in the index function you can use redirect instead of render
index function:
def index(request):
if request.method == 'POST':
.
.
.
result_dict = json.loads(index_results)
link = result_dict.link
return redirect('youtubedl:download', link ) # first arg is your url route to downloading_video function like 'appname:urlname' and second is the link that coming from result_dic
else:
.
.
downloading_video function:
def downloading_video(request, link):
try:
with youtube_dl.YoutubeDL(video_opts) as ydl:
ydl.download(link)
except:
pass
this is the way i think you should use because your download function is in a separate template