Cannot resolve NoReverseMatch at / error in Django - python

I am trying to make an auction website (for a project). And we need to have an option to add each product to the "watchlist". However, I keep getting error when clicking on "watchlist" button. This is in Python using Django.
This is the exact error I'm getting:
NoReverseMatch at /viewlisting/3/addwatchlist
Reverse for 'addwatchlist' with arguments '('',)' not found. 1 pattern(s) tried: ['viewlisting/(?P<listing_id>[0-9]+)/addwatchlist$']
Here is a summary of my code:
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("create_listing", views.create_listing, name="create_listing"),
path("viewlisting/<int:listing_id>", views.viewlisting, name="viewlisting"),
path("viewlisting/<int:listing_id>/addwatchlist", views.addwatchlist, name="addwatchlist")
]
views.py:
def viewlisting(request,listing_id):
productname= listings.objects.get(id=listing_id)
name= productname.name
description = productname.description
image = productname.image
price= productname.price
seller = productname.seller
category = productname.category
date = productname.date
productid= productname.id
return render(request, "auctions/viewlisting.html",{
"name":name,
"description":description,
"image":image,
"price":price,
"seller":seller,
"category":category,
"date":date,
"id":productid
})
def addwatchlist(request,listing_id):
if request.method == "POST":
item_exists= watchlist.objects.filter(
id = listing_id, user= request.user.username
)
if item_exists:
show_watchlist = watchlist.objects.all()
exist_alert= "This item already exists in your watchlist!"
return render(request,"auctions/viewlisting.html",{
"alert":exist_alert,
"show_watchlist":show_watchlist
})
else:
new_item = watchlist()
new_item.user = request.user.username
new_item.listing = listings.objects.get(id=listing_id).name
new_item.save()
success_alert = "This item was added to your watchlist!"
show_watchlist = watchlist.objects.all()
return render(request,"auctions/viewlisting.html",{
"alert": success_alert,
"show_watchlist":show_watchlist,
})
else:
return render(request,"auctions/viewlisting.html")
And this is my viewlisting html page which renders different product detials and allows the user to add the product to their watchlist.
viewlisting.html:
{% extends "auctions/layout.html" %}
{% block body%}
<div class="container-fluid">
<div class="row">
<div class="col-md-4"><img src={{image}} style="max-width: 350px;"></div>
<div class="col-md-4"><strong>{{ name }}</strong><br> {{description}}
</div>
<div class="col-md-4">
<strong>Current Price:</strong> <sup>CAD$</sup>{{price}}
<br>
<strong>Category:</strong> {{ category }}
<br>
<br>
<form action="{% url 'addwatchlist' id %}" method="POST">
{% csrf_token %}
<button style="color:ghostwhite" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
Add to Watchlist
</button>
</form>
</div>
</div>
<div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">{{alert}}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<h6>Your Watchlist:</h6>
{% for i in show_watchlist %}
<li>{{i.listing}</li>
{% endfor %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
And this is models.py:
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
pass
def __str__ (self):
return f"username:{self.username}, email:{self.email}, password:{self.password}"
class listings(models.Model):
name = models.CharField(max_length=70, null= True, unique=True)
seller = models.CharField(max_length=100)
price = models.IntegerField(null= True)
category = models.CharField(max_length=100, null=True)
date = models.DateTimeField(auto_now=True)
description= models.CharField(max_length=500)
image= models.URLField()
def __str__ (self):
return f"{self.name} by {self.seller}: {self.price}, {self.category}, {self.date}, {self.description}, {self.date}, {self.image} "
class bids(models.Model):
bidder = models.ForeignKey(User, on_delete= models.CASCADE, related_name="bidder", null=True)
bid_price = models.IntegerField(null= True)
product= models.ForeignKey(listings, on_delete= models.CASCADE, to_field= "name", null=True)
bid_date = models.DateTimeField(auto_now=True, null=True)
def __str__(self):
return f"{self.bidder} bid {self.bid_price} on {self.product}: posted on {self.bid_date}"
class comments(models.Model):
commenter = models.ForeignKey(User, on_delete= models.CASCADE, related_name="commenter", null=True)
content = models.CharField(max_length=500, null=True)
post_date = models.DateTimeField(auto_now=True)
listing = models.ForeignKey(listings, on_delete= models.CASCADE, to_field= "name",null=True)
def __str__(self):
return f"{self.commenter} commented {self.content} on listing: {self.listing} ({self.post_date})"
class watchlist(models.Model):
user=models.CharField(max_length=500)
listing = models.CharField(max_length=500)
def __str(self):
return f"User: {self.user}, Product: {self.listing}"
I would really appreciate any help or hints.
Also, let me know if you need more explanations.

This is because you are passing id in form url and listing_id in urls.py
change <form action="{% url 'addwatchlist' id %}" method="POST"> to <form action="{% url 'addwatchlist' listing_id=id %}" method="POST">

Related

Passing CHOICES to as an ID to template

As you can see the photo above, I have displayed all "CATEGORY_CHOICES" (in forms of (Groceries, Groceries) in category.html.
views.py
def category(request):
context = {'CATEGORY_CHOICES': Category.CATEGORY_CHOICES}
return render(request, 'category.html', context)
def view_category(request, category_id):
category = Category.objects.get(category_id=category_id)
return render(request, 'view_category.html', {'category':category})
models.py
class Category(models.Model):
CATEGORY_CHOICES = [
('Groceries', 'Groceries'),
('Salary', 'Salary'),
('Bills', 'Bills'),
('Rent', 'Rent'),
('Gym', 'Gym'),
('Restaurant', 'Restaurant'),
('Vacation', 'Vacation'),
('Travel', 'Travel'),
('Gift', 'Gift'),
('Investments', 'Investments'),
('Savings', 'Savings'),
('Entertainment', 'Entertainment'),
('Internet', 'Internet'),
('Healthcare', 'Healthcare'),
('Lifestyle', 'Lifestyle'),
('Insurance', 'Insurance'),
('Other', 'Other'),
]
category_choices = models.CharField(max_length=50, blank=False, choices=CATEGORY_CHOICES)
budget = models.DecimalField(max_digits=10, decimal_places=2)
start_date = models.DateField(blank=False)
end_date = models.DateField(blank=False)
spending_limit = models.DecimalField(max_digits=10, decimal_places=2)
category.html
{% extends 'base_content.html' %}
{% block content %}
<div class="container">
<div class="row justify-content-center">
<div class="row" style="width:90%">
<div class="col-sm-4 text-center my-3">
<div class="card card-block" style="height : 300px">
<div class="card-body align-items-center d-flex justify-content-center">
<h5 class="card-title">Overall</h5>
</div>
</div>
</div>
{% for item in CATEGORY_CHOICES %}
<div class="col-sm-4 text-center my-3">
<div class="card card-block" style="height : 300px">
<div class="card-body align-items-center d-flex justify-content-center">
<h5 class="card-title">{{ item.1 }}</h5>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
{% endblock %}
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.home_page, name ='home_page'),
path('feed/',views.feed, name ='feed'),
path('sign_up/', views.SignUpView.as_view(), name='sign_up'),
path('log_in/', views.LogInView.as_view(), name='log_in'),
path('log_out/', views.log_out, name='log_out'),
path('profile/', views.ProfileUpdateView.as_view(), name='profile'),
path('new_transaction/',views.new_transaction, name ='new_transaction'),
path('category',views.category, name = 'category'),
path('category/view/<str:???***confused this part too***>/',views.view_category, name
= 'view_category'),
As you can see in the code, I'm trying to pass category name to make url to be category/view/'category_name'. However, this category name is not a field of Category model but from category_choices. I need to fetch the exact category_choices to pass into url. Two things are confusing to me. First, how am I going to extract category choice into url as an ID? Second is how am I going to configure the url for 'view_category'?
error message
NoReverseMatch at /category
Reverse for 'view_category' with arguments '(('Groceries', 'Groceries'),)' not found.
1 pattern(s) tried: ['category/view/(?P<category_id>[0-9]+)/\\Z']
Of course the error is found at

Django error: NoReverseMatch at : I get this error

I have the following conceptual error which I am not undertstanding:
Please have a look at the thrown error:
NoReverseMatch at /watchlist
Reverse for 'auction' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<auction_id>[0-9]+)$']
Request Method: GET
Request URL: http://127.0.0.1:8000/watchlist
This is my urls.py file:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("<int:auction_id>", views.auction, name="auction"),
path("new", views.newItem, name="newItem"),
path("watchlist", views.watchlist, name="watchlist"),
path("addwatchList/<int:auction_id>", views.add_watchlist, name="add_watchlist"),
path("remwatchList/<int:auction_id>", views.rem_watchlist, name="rem_watchlist"),
]
And the views.py file fragment where the errors occurs is this:
#login_required
def watchlist(request):
u = User.objects.get(username=request.user)
return render(request, "auctions/watchlist.html", {
"watcher": u.watchingAuction.all()
})
Assigning the "watcher" variable makes the application brake and show the error message.
Can you please help me out? Where is the conceptual mistake?
Thnkass
This is my Watchlist.html file:
{% extends "auctions/layout.html" %}
{% block body %}
<h2 style="text-align: center;">My Watchlist!</h2>
<hr>
{% if watcher%}
<div class="row">
{% for item in watcher %}
<div class="card" style="width: 18rem;">
<img src="{{item.watchingAuction.url}}" class="card-img-top" alt="..." style="max-height: 200px; min-height: 200px; max-width: 180px; min-width: 180px;">
<div class="card-body">
<h5 class="card-title">{{item.watchingAuction.name}}</h5>
<h6 class="card-title">Price: ${{item.watchingAuction.startBid}}</h6>
<h6 class="card-title">{{item.watchingAuction.owner}}</h6>
<p class="card-text">{{item.watchingAuction.description}}</p>
To Auction
</div>
</div>
{% endfor %}
{% else %}
<h3 style="text-align: center; color:darkslateblue;">No auctions watched so far</h3>
{% endif %}
</div>
{% endblock %}
This is my models.py file:
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
pass
class Auction(models.Model):
NOCAT = 'NO'
SURF = 'SU'
KITESURF = 'KI'
WINDSURF = 'WI'
SKI = 'SK'
BASE = 'BA'
CATEGORY_CHOICES = [
(NOCAT, 'Nocat'),
(SURF, 'Surf'),
(KITESURF, 'Kitesurf'),
(WINDSURF, 'Windsurf'),
(SKI, 'Ski'),
(BASE, 'Base'),
]
owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="auctionOwner")
name = models.CharField(max_length=64)
description = models.TextField(max_length=200)
startBid = models.FloatField()
currentBid = models.FloatField(blank=True, null=True)
url = models.URLField(blank=True)
watching = models.ManyToManyField(User, blank=True, related_name="watchingAuction")
category = models.CharField(
blank=True,
max_length=2,
choices=CATEGORY_CHOICES,
default=SURF )
def __str__(self):
return f"{self.name} {self.startBid} {self.category}"
def snippet(self):
return self.description[:25] + "..."
class Bids(models.Model):
item = models.ForeignKey(Auction, on_delete=models.CASCADE, related_name="itemBid")
bidder = models.ForeignKey(User, on_delete=models.CASCADE, related_name="bidMan")
bid = models.FloatField()
def __str__(self):
return f"{self.bidder} {self.bid}"
class Comments(models.Model):
comment = models.TextField(max_length=300)
commenter = models.ForeignKey(User, on_delete=models.CASCADE, related_name="userComment")
item = models.ManyToManyField(Auction,blank=True, related_name="speech")
def __str__(self):
return f"{self.commenter} says: {self.comment}"
I found the bug, I was accessing the wrong attributes of each element in the for loop. Now it is solved

Store multiple inputs values of form in single json to store in model field. - Django

I am working on a project which is online printing ordering service.
Here on the order page I am getting different attributes of product in radio button list in the form, and all the attributes I want to store in a single json in database.
models.py
class Product(models.Model):
prod_ID = models.AutoField("Product ID", primary_key=True)
prod_Name = models.CharField("Product Name", max_length=30, null=False)
prod_Desc = models.CharField("Product Description", max_length=2000, null=False)
prod_Price = models.IntegerField("Product Price/Piece", default=0.00)
prod_img = models.ImageField("Product Image", null=True)
def __str__(self):
return "{}-->{}".format(self.prod_ID,
self.prod_Name)
# this is the order table , there is a "attribute_field" I wantto store the attributes in this field
# as JSON.
class Order(models.Model):
order_id = models.AutoField("Order ID", primary_key=True)
user_id = models.ForeignKey(User, on_delete=models.CASCADE, null=False, verbose_name="Customer ID")
prod_id = models.ForeignKey(Product, on_delete=models.CASCADE, null=False, verbose_name="Product ID")
quantity = models.ImageField('Product Quantity', max_length=10, default=500)
attribute_value = models.CharField("Item Details JSON", max_length=2000, null=False)
order_date = models.DateField("Order Date", auto_now_add=True, null=False)
order_job_title = models.CharField("Name of Company/Business", max_length=100, null=False)
order_desc = models.CharField("Details for Product", max_length=1000, null=False)
product_img = models.ImageField("Template Image", null=False)
address = models.CharField("Customer Address ", max_length=100, null=False)
state = models.CharField("Customer State", max_length=30, null=False)
city = models.CharField("Customer City", max_length=30, null=False)
postal_code = models.IntegerField("Area Pin Code", null=False)
order_price = models.DecimalField(max_digits=8, decimal_places=2, default=0000.00)
class Size(models.Model):
size_id = models.AutoField("Size ID", primary_key=True, auto_created=True)
prod_size = models.CharField("Product Size", max_length=20, null=False)
def __str__(self):
return "{size_id}-->{prod_size}".format(size_id=self.size_id,
prod_size=self.prod_size)
class Color(models.Model):
color_id = models.AutoField("Color ID", primary_key=True, auto_created=True)
prod_color = models.CharField("Product Color", max_length=50, null=False)
def __str__(self):
return "{color_id}-->{prod_color}".format(color_id=self.color_id,
prod_color=self.prod_color)
class PaperChoice(models.Model):
paper_id = models.AutoField("Paper Choice ID", primary_key=True, auto_created=True)
paper_choices_name = models.CharField("Paper Choices", max_length=50, null=False)
def __str__(self):
return "{}-->{}".format(self.paper_id,
self.paper_choices_name)
class SizeProductMapping(models.Model):
size_p_map_id = models.AutoField("Size & Product Map ID", primary_key=True, auto_created=True)
size_id = models.ForeignKey(Size, null=False, on_delete=models.CASCADE, verbose_name="Size ID")
prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")
class ColorProductMapping(models.Model):
color_p_map_id = models.AutoField("Color & Product Map ID", primary_key=True, auto_created=True)
color_id = models.ForeignKey(Color, null=False, on_delete=models.CASCADE, verbose_name="Color ID")
prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")
class PaperChoiceProductMapping(models.Model):
paper_p_map_id = models.AutoField("Paper Choices & Product Map ID", primary_key=True, auto_created=True)
paper_id = models.ForeignKey(PaperChoice, null=False, on_delete=models.CASCADE, verbose_name="Paper ID")
prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")
this is my views.py and it is incomplete , I want to store the forms data in the model using this
view.
views.py
#here in thi view method I am only getting data from models but not getting template data to store in the the model,
# I know I haven't taken inputs from the form here
# I haven't done because I don't know what logic I should use here.
def order(request, id):
products = Product.objects.all()
sizesList = []
ColorsList = []
PaperChoiceProductsList = []
try:
sizesMap = SizeProductMapping.objects.filter(prod_id=id)
sizesList = [data.size_id.prod_size for data in sizesMap]
except AttributeError:
pass
try:
colorMap = ColorProductMapping.objects.filter(prod_id=id)
ColorsList = [data.color_id.prod_color for data in colorMap]
except AttributeError:
pass
try:
PaperChoiceProductMap = PaperChoiceProductMapping.objects.filter(prod_id=id)
PaperChoiceProductsList = [data.paper_id.paper_choices_name for data in PaperChoiceProductMap]
except AttributeError:
pass
context = {'products': products,
'sizesList': sizesList,
"ColorsList": ColorsList,
"PaperChoiceProductsList": PaperChoiceProductsList,
}
return render(request, 'user/order.html', context)
order.html
{% extends 'user/layout/userMaster.html' %}
{% block title %}Order{% endblock %}
{% block css %}
form
{
position:relative;
}
.tasksInput
{
margin-right:150px;
}
label
{
vertical-align: top;
}
{% endblock %}
{% block header %}
{% endblock %}
{% block main %}
<div class="container">
<div>
<div class="row rounded mx-auto d-block d-flex justify-content-center">
<button class="btn btn-secondary my-2 mr-1">Custom</button>
<button class="btn btn-secondary my-2 ml-1">Package</button>
</div>
<div class="row">
<div class="col-4">
<div class="card border border-secondary">
<div class="card body mx-2 mt-4 mb-2">
{% for product in products %}
<a id="{{ product.prod_ID }}" class="card-header" style="font-size:5vw;color:black;"
href="{% url 'user-order' product.prod_ID %}">
<h5 class="h5">{{ product.prod_ID }}. {{ product.prod_Name }}</h5></a>
<div class="dropdown-divider"></div>
{% endfor %}
</div>
</div>
</div>
<div class="col-8">
<form>
<div class="card mx-2 my-2 border border-secondary">
<div class="my-2">
<!-- The data I want to store in JSON starts from here -->
{% if sizesList %}
<div class="form-group">
<div class="form-group row mx-2">
<label for="sizeList"
class="form-control-label font-weight-bold card-header col-4 ml-4"
style="background-color:#e3e4e6"><h5>Sizes : </h5></label>
<div id="sizeList">
{% for s in sizesList %}
<input id="{{s}}" class="mx-2 my-auto" type="radio" name="size">
<label for="{{s}}">{{s}}</label><br>
{% endfor %}
</div>
</div>
</div>
{% endif %}
{% if ColorsList %}
<div class="form-group">
<div class="form-group row mx-2">
<label for="ColorsList"
class="form-control-label font-weight-bold card-header col-4 ml-4"
style="background-color:#e3e4e6"><h5>Colors : </h5></label>
<div id="ColorsList">
{% for c in ColorsList %}
<input id="{{c}}" class="mx-2 my-auto" type="radio" name="Color">
<label for="{{c}}">{{c}}</label><br>
{% endfor %}
</div>
</div>
</div>
{% endif %}
{% if PaperChoiceProductsList %}
<div class="form-group">
<div class="form-group row mx-2">
<label for="ColorsList"
class="form-control-label font-weight-bold card-header col-4 ml-4"
style="background-color:#e3e4e6"><h5>Paper Choice : </h5></label>
<div id="PaperChoiceProductsList">
{% for pc in PaperChoiceProductsList %}
<input id="{{pc}}" class="mx-2 my-auto" type="radio" name="PaperChoice">
<label for="{{pc}}">{{pc}}</label><br>
{% endfor %}
</div>
</div>
</div>
{% endif %}
<!-- The Data I want to store in the JSON ends here -->
</div>
</div>
</div>
</form>
</div>
</div>
<div class="row rounded mx-auto d-block d-flex justify-content-center">
<button class="btn btn-success my-2">Place Order</button>
</div>
</div>
</div>
{% endblock %}
As mentioned in above template comment I want to store that data in single JSON.
Can you please help me to create a view for it.
urls.py
path('order/<int:id>', views.order, name="user-order"),
I used jason dump method to store value in single json object and then passed it to the field and it is working for me.
views.py
import json
def order(request, id):
products = Product.objects.all()
sizesList = []
ColorsList = []
PaperChoiceProductsList = []
value = {}
try:
sizesMap = SizeProductMapping.objects.filter(prod_id=id)
sizesList = [data.size_id.prod_size for data in sizesMap]
except AttributeError:
pass
try:
colorMap = ColorProductMapping.objects.filter(prod_id=id)
ColorsList = [data.color_id.prod_color for data in colorMap]
except AttributeError:
pass
try:
PaperChoiceProductMap = PaperChoiceProductMapping.objects.filter(prod_id=id)
PaperChoiceProductsList = [data.paper_id.paper_choices_name for data in PaperChoiceProductMap]
except AttributeError:
pass
if request.method == 'POST':
if request.method == 'POST':
customer_id = request.user
product = Product.objects.get(prod_ID=id)
product_id = product
try:
quantity = request.POST['quantity']
print(quantity)
except MultiValueDictKeyError:
pass
try:
size = request.POST['size']
value.update(size=size)
except MultiValueDictKeyError:
pass
try:
Colour = request.POST['Color']
value.update(Colour=Colour)
except MultiValueDictKeyError:
pass
try:
Paper_Choice = request.POST['PaperChoice']
value.update(Paper_Choice=Paper_Choice)
except MultiValueDictKeyError:
pass
attribute_value = json.dumps(value)
order_store = Order(user_id=customer_id, prod_id=product_id, quantity=quantity, attribute_value=attribute_value,
order_job_title=Job_title, order_desc=Order_Detail, address=User_Address, state=State,
city=City, postal_code=Postal_Code, product_img=TemplateValue)
order_store.save()
context = {'products': products,
'sizesList': sizesList,
"AqutousCoatingProductList": AqutousCoatingProductList,
"ColorsList": ColorsList,
"PaperChoiceProductsList": PaperChoiceProductsList,
}
return render(request, 'user/order.html', context)

Get Absolute Url keeps directing to one particular id

Good day, I have a Django project where I want to display an order list and detail. All seems to work perfectly but the link only links to one particular id ( for instance id 66). I have tried deleting the particular order id from the admin panel, thinking maybe the URL would just reset, but I get the URL id incremented, now it's no longer id 66 but 67. Pls how can I fix this? here are my codes:
models.py
class Order(models.Model):
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
address = models.CharField(max_length=250)
phone_number = models.CharField(max_length=20)
city = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
paid = models.BooleanField(default=False)
braintree_id = models.CharField(max_length=150, blank=True)
coupon = models.ForeignKey(Coupon, related_name='orders', null=True, blank=True, on_delete=models.SET_NULL)
discount = models.IntegerField(default=0, validators=[
MinValueValidator(0),
MaxValueValidator(100)
])
class Meta:
ordering = ('-created',)
def __str__(self):
return self.first_name
def get_absolute_url(self):
return reverse('orders:orderdetail', args=[self.id])
views.py
def order_list(request):
orders = Order.objects.all()
current_user = request.user
success = Order.objects.filter(user=current_user.id).filter(paid=True)
fail = Order.objects.filter(user=current_user.id).filter(paid=False)
return render(request, 'orders/order/order_list.html', {
'success': success,
'fail': fail,
'current_user': current_user,
'orders':orders,
})
def order_detail(request, order_id):
order = get_object_or_404(Order, id=order_id)
return render(request, 'orders/order/order_detail.html', {'order': order})
urls.py
from django.urls import path
from . import views
app_name = 'orders'
urlpatterns = [
path('create/', views.order_create, name='order_create'),
path('admin/order/<int:order_id>/', views.admin_order_detail, name='admin_order_detail'),
path('admin/order/<int:order_id>/pdf/', views.admin_order_pdf, name='admin_order_pdf'),
path('addtocart/<int:id>', views.addtocart, name='addtocart'),
path('myorder/', views.order_list, name='orderlist'),
path('myorder/detail/<int:order_id>/', views.order_detail, name='orderdetail'),
]
html
{% for order in orders %}
<a href="{{ order.get_absolute_url }}" style="position: absolute; top: 5px; right: 5px;">
View Details
</a>
{% endfor %}
full html
<div class="col-md-9">
{% for od in success %}
<div class="card mb-3" style="max-width: 540px;">
<div class="row no-gutters">
<div class="col-md-3">
<img alt="product img" class="card-img" src="...">
</div>
<div class="col-md-9">
<div class="card-body" style="position: relative;">
<h5 class="card-title">Product {{ od.id }}</h5>
{% for order in orders %}
<a href="{{ order.get_absolute_url }}" style="position: absolute; top: 5px; right: 5px;">
View Details
</a>
{% endfor %}
<p class="card-text">
<mark style="color: whitesmoke; background-color: brown;border-radius: 3px;font-weight: bold;">{{transaction}}</mark>
</p>
<p class="card-text"><small class="text-muted">Delivered at
{{od.reference_id}}</small></p>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
The URL I get is like this /orders/myorder/detail/66/
I'm gonna add pictures to make it less abstract
Thanks.
Just like #EricMartin said, it was the context of the order
I realized I had {% for od in success %} and {% for order in orders %}
I guess they're not on good terms with each other and since orders is in success, I removed the {% for order in orders %} loop and all seems peaceful again :)

Django- Form does not save the given argument

I do not why but the line recording.component=component in my views.py does not save the component which is given as an argument and I do not understand the reason. The only think that I have in mind is that I am using smart_select. Here is what I have:
My views.py file:
def create_recording(request, slug, inspection_id, component_id):
inspection = get_object_or_404(Inspection, pk=inspection_id)
plant = get_object_or_404(Plant, slug=slug)
component=get_object_or_404(Component, pk=component_id)
if request.method == "POST":
form = RecordingForm(request.POST)
if form.is_valid():
recording = form.save(commit=False)
recording.user = request.user
recording.plant = plant
recording.inspection=inspection
recording.component=component
recording.save()
return redirect('data:inspection_detail', slug=plant.slug, inspection_id=inspection.id)
else:
form = RecordingForm()
context = {'form': form, 'plant':plant,'inspection':inspection,}
template = 'data/create_recording.html'
return render(request, template, context)
my models.py:
class Recording(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
plant = models.ForeignKey(Plant, on_delete=models.CASCADE)
inspection = models.ForeignKey(Inspection, on_delete=models.CASCADE)
component = models.ForeignKey(Component)
group = ChainedForeignKey(Group, chained_field="component", chained_model_field="component", show_all=False, auto_choose=True, sort=True)
failure = ChainedForeignKey(Failure, chained_field="group", chained_model_field="group", show_all=False, auto_choose=True, sort=True)
def __str__(self):
return str(self.failure)
my forms.py:
class RecordingForm(forms.ModelForm):
class Meta:
model = Recording
fields = ['group', 'failure',]
my html:
<a href="{% url 'data:create_recording' slug=plant.slug inspection_id=inspection.id component_id=1 %}">
<button type="button" class="btn btn-success">
<span class="glyphicon glyphicon-plus"></span> Chair
</button>
</a>
<a href="{% url 'data:create_recording' slug=plant.slug inspection_id=inspection.id component_id=2 %}">
<button type="button" class="btn btn-success">
<span class="glyphicon glyphicon-plus"></span> Table
</button>
</a>
and the html for for my form:
<div class = "col-sm-7">
<div class="panel panel-primary">
<div class="panel-heading">
<h4>Add new recording</h4>
</div>
<div class="panel-body">
<form method='POST'>
{% csrf_token %}
{{ form|crispy }}
<button type = 'submit' class="btn btn-success">Save</button>
</form>
</div>
</div>
</div>
and my url:
url(r'^plants/(?P<slug>[-\w]+)/inspection(?P<inspection_id>[0-9]+)/create_recording/(?P<component_id>[0-9]+)$', views.create_recording, name='create_recording'),
please let me know if I need to add some more information.

Categories

Resources