Not able to view static files on template - django

This project is working but unable to view uploaded files on template name upload.html.
This is storing uploaded files in control _ static folder, it works fine but when I click on view file in upload.html template, it is not displaying the uploaded file.
Please help me to solve this. Please
usermaster app:
views.py:
def control_upload(request):
if request.method == 'POST':
form = ControlForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['control_uploadfile'])
model_instance = form.save()
model_instance.save()
else:
form = ControlForm()
controlmachiness = Controlmachine.objects.all()
return render(request,'usermaster/control_uploadfile.html',{'form':form,'controlmachiness':controlmachiness})
def handle_uploaded_file(f):
with open('usermaster/control_static/control_files/'+f.name, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
def control_index(request):
controlmachines = Controlmachine.objects.all()
return render(request,"usermaster/control_show.html",{'controlmachines':controlmachines})
def control_destroy(request, id):
controlmachine = Controlmachine.objects.get(id=id)
controlmachine.delete()
return HttpResponseRedirect('/usermaster/controlfile/')
def upload(request):
cmachines = Controlmachine.objects.all()
return render(request,'usermaster/upload.html',{'cmachines':cmachines})
def save_machine(request):
if request.method == "POST":
machine_name = request.POST.get('machinename', '')
operation_no = request.POST.get('operationname','')
choiced_cmachine = Controlmachine.objects.filter(machine_name=machine_name, operation_no=operation_no)
cmachines = Controlmachine.objects.all()
return render(request,'usermaster/upload.html',{'cmachines':cmachines,'choiced_cmachine':choiced_cmachine})
models.py:
class Controlmachine(models.Model):
machine_name = models.CharField(max_length=100)
operation_no = models.IntegerField()
control_uploadfile = models.FileField(upload_to='control_files/')
class Meta:
db_table = "controlmachine"
forms.py:
class ControlForm(forms.ModelForm):
class Meta:
model = Controlmachine
fields = ['machine_name', 'operation_no', 'control_uploadfile'] #https://docs.djangoproject.com/en/3.0/ref/forms/widgets/
widgets = { 'machine_name': forms.TextInput(attrs={ 'class': 'form-control' }),
'operation_no': forms.TextInput(attrs={ 'class': 'form-control' }),
'control_uploadfile': forms.ClearableFileInput(attrs={ 'class': 'form-control' }),
}
Templates/usermaster/:
control_uploadfile.html:
{% extends "usermaster/home.html" %}
<html>
<head>
<title>Control File Upload</title>
</head>
{% block body %}
<body>
<p><h1>Control File Upload</h1></p>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button> <br><br>
</form>
</body>
{% endblock %}
</html>
upload.html:
{% extends 'dashboard/user_home.html' %}
{% block body %}
{% load control_static %}
<body>
<form action="{% url 'usermaster:save_machine' %}" method="post">
{% csrf_token %}
<label for="machinename">Select Machine Name:</label>
<select class="form-control form-control-md" name="machinename" id="machinename">
{% for machine in cmachines %}
<option value="{{ machine.machine_name }}">{{ machine.machine_name }}</option>
{% endfor %}
</select>
<br>
<br>
<label for="operationname">Select Operation Number:</label>
<select class="form-control" id="operationname" name="operationname">
{% for machine in cmachines %}
<option value="{{ machine.operation_no }}">{{ machine.operation_no }}</option>
{% endfor %}
</select>
<br>
<br>
<br>
<input class="btn btn-info" type="submit" value="Save">
</form>
<br>
<br>
<table class="table table-bordered table-dark width=50%">
<thead>
<tr>
<th scope="col">Machine Name</th>
<th scope="col">Operation Number</th>
<th scope="col">File</th>
</tr>
</thead>
<tbody>
<tr>
{% for choice in choiced_cmachine %}
<td>{{choice.machine_name}}</td>
<td>{{choice.operation_no}}</td>
<td>
{% for file in cmachines %}
<a class="btn btn-info" href="{% control_static 'usermaster/{{file.control_uploadfile}}' %}">view file</a>
{% endfor %}
</td>
{% endfor %}
</tr>
</tbody>
</table>
{% endblock %}
</body>
</html>
urls.py:
app_name = 'usermaster'
urlpatterns = [
path('controlfile/',views.control_index,name='control_index'),
path('cdelete/<int:id>',views.control_destroy),
path('controlupload/',views.control_upload,name='control_upload'),
path('upload/',views.upload,name='upload'),
path('save',views.save_machine,name='save_machine'),
]
urls.py:
urlpatterns = [
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
settings.py:
STATIC_URL = 'control_static/'
STATIC_ROOT=os.path.join(BASE_DIR,'control_static')
ROOT_PATH = os.path.dirname('control_static')
STATICFILES_DIRS = [os.path.join(ROOT_PATH,'usermaster')]

call the view from the upload.html
UPLOAD.HTML:
<a class="btn btn-info" href="{% url 'APPNAME:pdf_view' %}">view file</a>
views.py:
from django.http import FileResponse, Http404
from django.contrib.staticfiles.storage import staticfiles_storage
pdf_url = staticfiles_storage.url('YOUR_PDF_NAME.csv')
def pdf_view(request):
try:
return FileResponse(open('pdf_url', 'rb'), content_type='application/pdf')
except FileNotFoundError:
raise Http404()

Related

form doesn't submit productbacklogs to database

here is my project code .
I after posting data by form nothing happens.
#model.py
from django.db import models
from projectapp.models import Project
class Productbacklog(models.Model):
project=models.ForeignKey(Project,on_delete=models.CASCADE,default=None)
pbId=models.IntegerField(primary_key=True)
pbTitle=models.CharField(max_length=100)
pbPriority=models.IntegerField(blank=True, null=True)
class Meta:
unique_together=('project','pbId')
def __str__(self):
return self.pbTitle
#forms.py
from django import forms
from productbacklogapp.models import Productbacklog
from projectapp.models import Project
class ProductbacklogForm(forms.ModelForm):
class Meta:
model = Productbacklog
exclude=('pbId','project')
fields=['pbTitle']
#views.py
def productbacklogall(request):
if request.method == 'POST':
form = ProductbacklogForm(request.POST)
if form.is_valid():
form.instance.manage = Project.objects.get_or_create(cname=form.cleaned_data['manage_id'])
form.save()
messages.success(request, ('new productbacklog added'))
return redirect('productbacklogall')
else:
pb_all=Productbacklog.objects.all()
return render(request, 'productbacklogall.html', {'pb_all':pb_all})
I think that issue is on forms.py or views.py but I can't find it.
I'm so greatful if anyone can help me.
here is also my html code,when I submit something the method is post but I don't know why it doesn't go to data basse.
#productbacklogall.html
{%extends 'base.html'%}
{%block title%}
<title>backlog all</title>
{%endblock title%}
{%block content%}
</br>
{% if messages %}
{% for message in messages %}
<div class="alert alert-primary" role="alert">
{{ message }}
×
</div>
{% endfor %}
{% endif %}
<div class="container">
<form method="POST" class="row">
{% csrf_token %}
<label class="col-lg-4"></label>
<input type="text" class="form-control" name="Project" placeholder="project title?"/>
<input type="number" class="form-control" name="pbId" placeholder="backlog id?"/>
<input type="text" class="form-control" name="pbTitle" placeholder="pb title?"/>
<button type="submit" class="btn btn-primary col-lg-2">add project</button>
</form>
</div>
</br>
</br>
<table class="table table-bordered text-center">
<thead class="thead-dark">
<tr>
<th scope="col"> backlog-title</th>
<th scope="col">Edit</th>
<th scope="col">delivarable_task</th>
<th scope="col">related project</th>
</tr>
</thead>
<tbody>
{% load static %}
{% if pb_all %}
{% for obj in pb_all %}
<tr>
<td>{{ obj.pbTitle }}</td>
<td><a href='{% url "delete_productbacklog" obj.pbId %}'>delete</a></td>
<td> <a href=#> delivarabletask </a></td>
<td>{{ obj.project.pbTitle }}</td>
</tr>
{% endfor %}
{% endif %}
</tbody>
</table>
</div>
{%endblock content%}
Your form data are not valid, to see them, add this code to your views :
else:
messages.error(request, "Error")
like this :
def productbacklogall(request):
if request.method == 'POST':
form = ProductbacklogForm(request.POST)
if form.is_valid():
form.instance.manage = Project.objects.get_or_create(cname=form.cleaned_data['manage_id'])
form.save()
messages.success(request, ('new productbacklog added'))
else:
messages.error(request, "Error")
return redirect('productbacklogall')
else:
pb_all=Productbacklog.objects.all()
return render(request, 'productbacklogall.html', {'pb_all':pb_all})

Reverse for 'create_order' with no arguments not found. 1 pattern(s) tried: ['create_order/(?P<pk>[^/]+)/$']

I'm getting this error when I use
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
but there is no such error when path is..
path('create_order', views.createOrder, name="create_order"),
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('products/', views.products, name='products'),
path('customer/<str:pk_test>/', views.customer, name="customer"),
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
path('update_order/<str:pk>/', views.updateOrder, name="update_order"),
path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"),
]
views.py
def createOrder(request, pk):
OrderFormSet = inlineformset_factory(Customer, Order , fields=('product','status'), extra=9)
customer = Customer.objects.get(id=pk)
formset = OrderFormSet(queryset=Order.objects.none(), instance=customer)
#form = OrderForm(initial={'customer':customer})
if request.method == 'POST':
#print('printing post', request.POST)
formset = OrderFormSet(request.POST, instance=customer)
if formset.is_valid():
formset.save()
return redirect('/')
context = {'formset': formset}
#return redirect('accounts/order_form.html', context)
return render(request, 'accounts/order_form.html', context)
i also have tried redirect, that's not working the problem is with urls.py.
customer.html
{% extends 'accounts/main.html' %}
{% block content %}
<br>
<div class="row">
<div class="col-md">
<div class="card card-body">
<h5>Customer:</h5>
<hr>
<a class="btn btn-outline-info btn-sm btn-block" href="">Update Customer</a>
<a class="btn btn-outline-info btn-sm btn-block" href="{% url 'create_order' customer.id %}">Place Order</a>
</div>
</div>
<div class="col-md">
<div class="card card-body">
<h5>Contact Information</h5>
<hr>
<p>Email: {{customer.email}}</p>
<p>Phone: {{customer.phone}}</p>
</div>
</div>
<div class="col-md">
<div class="card card-body">
<h5>Total Order</h5>
<hr>
<h1 style="text-align: center;padding: 10px;">{{order_count}}</h1>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col">
<div class="card card-body">
<form method="POST">
<button class="btn btn-primary" type="submit">Search</button>
</form>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md">
<div class="card card-body">
<table class="table table-sm">
<tr>
<th>Product</th>
<th>Category</th>
<th>Date Ordered</th>
<th>Status</th>
<th>Update</th>
<th>Remove</th>
</tr>
{% for order in orders %}
<tr>
<td>{{order.product}}</td>
<td>{{order.product.category}}</td>
<td>{{order.date_created}}</td>
<td>{{order.status}}</td>
<td><a class="btn btn-outline-info btn-md " href="{% url 'update_order' order.id %}">Update</a></td>
<td><a class="btn btn-outline-danger btn-md " href="{% url 'delete_order' order.id %}">Delete</a></td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock %}
models.py
class Customer(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
phone = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.name
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<div class="col-md-6">
<div class="card card-body">
<form action="" method="POST">
{% csrf_token %}
{{formset.managment_form}} <!-- to remove the managmentForm data missing or has been tempered wiith , error -->
{% for form in formset %}
{{formset}} <!--in context of views.py -->
<hr>
{% endfor %}
<input class="btn btn-outline-success btn-md" type="submit" name="submit">
</form>
</div>
</div>
</div>
{% endblock %}
I have added the templates , and thanks to all but I think the only problem is with urls.py , because if I use
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
instead of
path('create_order', views.createOrder, name="create_order"),
then I get error, otherwise there is no such error for the above path.
I finally got the error.
So, error was here
the href which we have used id {% url 'create_order' customer.id %}
and this is in customer.html ,so the customer.id will get value provided by the views.customer
but if you see in your view.customer,
context = {'customers':customers,'orders': orders,'orders_count': orders_count}
because we followed a tutorial video, that guy did some changes which we didn't because it isn't shown in the video.
the changes he did was that
he changed 'customers' to 'customer' and now context of customer.html is good
because now it knows what the hell is customer.id
i know where the problem is
in the dashboard.html you should delete the line includes {% url 'create_order' %}
I don't know what is the problem but just replaced the file urls.py from GitHub with the same context and it's not showing that error.
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('products/', views.products, name='products'),
path('customer/<str:pk_test>/', views.customer, name="customer"),
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
path('update_order/<str:pk>/', views.updateOrder, name="update_order"),
path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"),
]
views.py
from django.forms import inlineformset_factory
def createOrder(request, pk):
OrderFormSet = inlineformset_factory(Customer, Order, fields=('product', 'status'), extra=10 )
customer = Customer.objects.get(id=pk)
formset = OrderFormSet(queryset=Order.objects.none(),instance=customer)
#form = OrderForm(initial={'customer':customer})
if request.method == 'POST':
#print('Printing POST:', request.POST)
#form = OrderForm(request.POST)
formset = OrderFormSet(request.POST, instance=customer)
if formset.is_valid():
formset.save()
return redirect('/')
context = {'form':formset}
return render(request, 'accounts/order_form.html', context)
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<div class="col-md-6">
<div class="card card-body">
<form action="" method="POST">
{% csrf_token %}
{{ form.management_form }}
{% for field in form %}
{{field}}
<hr>
{% endfor %}
<input type="submit" name="Submit">
</form>
</div>
</div>
</div>
{% endblock %}
Again I don't know why it was showing this error and where was the problem but just relapced it with the same code from GitHub and it worked.if someone know how it worked, that will be really helpful in near future.
in dashboard you should remove the line with create order
cause there is use of create_order url without id so there's an error

Unable to edit/delete existing formets

I am new here. I have been working on this issue for the past couple of days. Could someone help me, please?
Problem: Unable to edit/delete existing formsets
I have 1 form and 2 formsets in a view. I can create all 3, successfully.
Template rendering 1 form and 2 formsets
Also, I can edit/delete the form, but can't with the 2 formsets.
models.py
class Component(models.Model):
...
class ComponentImage(models.Model):
component = models.ForeignKey(Component, on_delete=models.CASCADE, related_name='componentimage')
image = models.ImageField(upload_to='component_pics')
caption = models.CharField(max_length=100, null=True, blank=True)
class ComponentWeblink(models.Model):
component = models.ForeignKey(Component, on_delete=models.CASCADE, related_name='componentweblink')
url = models.URLField()
caption = models.CharField(max_length=100, null=True, blank=True)
views.py
def component_create(request):
template = 'component/component_add.html'
if request.method == 'GET':
form = ComponentForm()
images = ImageFormset(queryset=ComponentImage.objects.none(), prefix='images')
links = WeblinkFormset(queryset=ComponentWeblink.objects.none(), prefix='links')
elif request.method == 'POST':
form = ComponentForm(request.POST)
images = ImageFormset(request.POST, request.FILES, prefix='images')
links = WeblinkFormset(request.POST, prefix='links')
if form.is_valid() and images.is_valid() and links.is_valid():
component = form.save(commit=False)
component.updated_by = request.user
component.save()
for form in images:
if form.has_changed():
componentimage = form.save(commit=False)
componentimage.component = component
componentimage.updated_by = component.updated_by
try:
componentimage.save()
except ValueError:
pass
for form in links:
if form.has_changed():
componentweblink = form.save(commit=False)
componentweblink.component = component
componentweblink.updated_by = component.updated_by
componentweblink.save()
messages.success(request, 'Component successfully created.')
return HttpResponseRedirect(reverse_lazy('component:component_detail', args=(component.pk,)))
return render(request, template, {
'form': form,
'images': images,
'links': links,
})
def component_update(request, pk):
obj = get_object_or_404(Component, id=pk)
template = 'component/component_update.html'
if request.method == 'GET':
form = ComponentForm(instance=obj)
images = ImageFormset(instance=obj, prefix='images')
links = WeblinkFormset(instance=obj, prefix='links')
elif request.method == 'POST':
form = ComponentForm(request.POST or None, instance=obj)
images = ImageFormset(request.POST or None, request.FILES or None, instance=obj, prefix='images')
links = WeblinkFormset(request.POST, instance=obj, prefix='links')
if form.is_valid() and images.is_valid() and links.is_valid():
component = form.save(commit=False)
component.updated_by = request.user
component.save()
for form in images:
if form.has_changed():
componentimage = form.save(commit=False)
componentimage.component = component
componentimage.updated_by = component.updated_by
try:
componentimage.save()
except ValueError:
pass
for form in links:
if form.has_changed():
componentweblink = form.save(commit=False)
componentweblink.component = component
componentweblink.updated_by = component.updated_by
componentweblink.save()
messages.warning(request, 'Component successfully updated.')
return HttpResponseRedirect(reverse_lazy('component:component_detail', args=(component.pk, ))) #trailing comma is required for single-item tuples to disambiguate defining a tuple or an expression surrounded by parentheses
return render(request, template, {
'form': form,
'images': images,
'links': links,
})
template.html (for update view)
{% block content %}
<script type="text/javascript" src="{% static 'js/jquery.formset.js' %}"></script>
<script type="text/javascript">
$(function() {
$('#images tbody tr').formset({
prefix: '{{ images.prefix }}',
formCssClass: 'dynamic-images'
});
$('#links tbody tr').formset({
prefix: '{{ links.prefix }}',
formCssClass: 'dynamic-links'
});
})
</script>
<div class="row justify-content-center">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend style="text-align:center" class="border-bottom mb-4">
Update Component
</legend>
<h5 style="text-align:center" >Data</h5>
{% include 'snippets/form.html' %}
<hr>
<h5 style="text-align:center" >Images</h5>
<table class="col col-md-12" id="images">
<tbody>
{{ images.management_form }}
{{ images.non_form_errors }}
{% for form in images.forms %}
<tr>
<td class="px-0 py-0 form-control{% if form.image.errors %} is-invalid{% else %} border-0{% endif %}">{{ form.image }}</td>
<td class="border-0 px-0 py-0 form-control" style="color:red">{{ form.image.non_field_errors }}</td>
<td class="border-0 px-0 py-0 form-control" style="color:red">{{ form.image.errors }}</td>
<td class="px-0 py-0 form-control{% if form.image.errors %} is-valid{% else %} border-0{% endif %}">{{ form.caption }}</td>
<td class="border-0 px-0 py-0 form-control" style="color:red">{{ form.caption.non_field_errors }}</td>
<td class="border-0 px-0 py-0 form-control" style="color:red">{{ form.caption.errors }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<hr>
<h5 style="text-align:center" >Weblinks</h5>
<table class="col col-md-12" id="links" border="0" cellpadding="0">
<tbody>
{{ links.management_form }}
{{ links.non_form_errors }}
{% for form in links.forms %}
<tr>
<td class="px-0 py-0 form-control{% if form.url.errors %} is-invalid{% else %} border-0{% endif %}">{{ form.url }}</td>
<td class="border-0 px-0 py-0 form-control" style="color:red">{{ form.url.errors }}</td>
<td class="border-0 px-0 py-0 form-control" style="color:red">{{ form.url.non_field_errors }}</td>
<td class="px-0 py-0 form-control{% if form.url.errors %} is-valid{% else %} border-0{% endif %}">{{ form.caption }}</td>
<td class="border-0 px-0 py-0 form-control" style="color:red">{{ form.caption.errors }}</td>
<td class="border-0 px-0 py-0 form-control" style="color:red">{{ form.caption.non_field_errors }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<br>
<button class="btn btn-primary" type="submit">
Update
</button>
<a class="btn btn-outline-secondary" href="{% if request.GET.next %}{{ request.GET.next }}{% else %}{% url 'component:components_list' %}{% endif %}">
Cancel
</a>
</fieldset>
</form>
</div>
{% endblock content %}
Please help. Thank you
Used VSCode debugger, as per a friend's suggestion. The problem was with not adding id (hidden_fields).
I added this in the update template:
{% for form in images.forms %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for form in links.forms %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
Also added the image.has_changed() to views.py to avoid accepting empty image fields.
for image in images:
if image.is_valid() and image.has_changed():
try:
image.save()
except ValueError:
pass

I want to add products to my cart and display the cart details..I am not able to understand why the code is not showing the details on the page?

class Cart(object):
def __init__(self, request):
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart
def add(self, product, quantity=1, update_quantity=False):
product_id = str(product.id)
if product_id not in self.cart:
self.cart[product_id] = {'quantity': 0, 'price': str(product.price)}
if update_quantity:
self.cart[product_id]['quantity'] = quantity
else:
self.cart[product_id]['quantity'] += quantity
self.save()
def save(self):
self.session[settings.CART_SESSION_ID] = self.cart
self.session.modified = True
def remove(self, product):
product_id = str(product.id)
if product_id in self.cart:
del self.cart[product_id]
self.save()
def __iter__(self):
product_ids = self.cart.keys()
products = Product.objects.filter(id__in=product_ids)
for product in products:
self.cart[str(product.id)]['product'] = product
for item in self.cart.values():
item['price'] = Decimal(item['price'])
item['total_price'] = item['price'] * item['quantity']
yield item
def __len__(self):
return sum(item['quantity'] for item in self.cart.values())
def get_total_price(self):
return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())
def clear(self):
del self.session[settings.CART_SESSION_ID]
self.session.modified = True
This is my cart.py file...
{% load static %}
{% block title %}
Your Shopping Cart
{% endblock %}
{% block content %}
<div class="container">
<div class="row" style="margin-top: 6%">
<h2>Your Shopping Cart
<span class="badge pull-right">
{% with totail_items=cart|length %}
{% if cart|length > 0 %}
My Shopping Order:
<a href="{% url "cart:cart_detail" %}" style="color: #ffffff">
{{ totail_items }} item {{ totail_items|pluralize }}, Kshs. {{ cart.get_total_price }}
</a>
{% else %}
Your cart is empty.
{% endif %}
{% endwith %}
</span>
</h2>
<table class="table table-striped table-hover">
<thead style="background-color: #5AC8FA">
<tr>
<th>Image</th>
<th>Product</th>
<th>Quantity</th>
<th>Remove</th>
<th>Unit Price</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{% for item in cart %}
{% with product=item.product %}
<tr>
<td>
<a href="{{ product.get__absolute_url }}">
<img src="{% if product.image %} {{ product.image.url }} {% else %} {% static 'img/default.jpg' %} {% endif %}" alt="..." style="height: 130px; width: auto">
</a>
</td>
<td>{{ product.name }}</td>
<td>
<form action="{% url "cart:cart_add" product.id %}" method="post">
{% csrf_token %}
{{ item.update_quantity_form.quantity }}
{{ item.update_quantity_form.update }}
<input type="submit" value="Update" class="btn btn-info">
</form>
</td>
<td>
Remove
</td>
<td>kshs. {{ item.price }}</td>
<td>kshs. {{ item.total_price }}</td>
</tr>
{% endwith %}
{% endfor %}
<tr style="background-color: #5AC8FA">
<td><b>Total</b></td>
<td colspan="4"></td>
<td colspan="num"><b>kshs. {{ cart.get_total_price }}</b></td>
</tr>
</tbody>
</table>
<p class="text-right">
Continue Shopping
Checkout
</p>
</div>
</div>
{% endblock %}
This is my detail.html page in the cart/templates/cart
<div class="row">
{% for product in products %}
<div class="col-sm-12 col-md-6 col-lg-4 p-b-50">
<!-- Block2 -->
<div class="block2">
<div class="block2-img wrap-pic-w of-hidden pos-relative">
<img src="{{ MEDIA_URL }}{{ product.image.url }}" alt="IMG-PRODUCT" height="290" width="190">
<div class="block2-overlay trans-0-4">
<a href="#" class="block2-btn-addwishlist hov-pointer trans-0-4">
<i class="icon-wishlist icon_heart_alt" aria-hidden="true"></i>
<i class="icon-wishlist icon_heart dis-none" aria-hidden="true"></i>
</a>
<div class="block2-btn-addcart w-size1 trans-0-4">
<!-- Button -->
<form action="{% url "cart:cart_add" product.id %}" method="post">
{% csrf_token %}
{{ cart_product_form }}
<input type="submit" value="add to cart" class="flex-c-m size1 bg4 bo-rad-23 hov1 s-text1 trans-0-4">
</form>
</div>
</div>
</div>
<div class="block2-txt p-t-20">
<a href="" class="block2-name dis-block s-text3 p-b-5">
{{ product.description }}
</a>
<span class="block2-price m-text6 p-r-5">
{{ product.price }}
</span>
</div>
</div>
</div>
{% endfor %}
</div><!--end row-->
This is my product/detail.html page from where my all products are listed and also a form and a buttom from where i want to submit my products details and add them to a cart.
from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST
from product.models import Product
from .cart import Cart
from .forms import CartAddProductForm
#require_POST
def cart_add(request, product_id):
cart = Cart(request)
product = get_object_or_404(Product, id=product_id)
form = CartAddProductForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update'])
return redirect('cart:cart_detail')
def cart_remove(request, product_id):
cart = Cart(request)
product = get_object_or_404(Product, id=product_id)
cart.remove(product)
return redirect('cart:cart_detail')
def cart_detail(request):
cart = Cart(request)
for item in cart:
item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'], 'update': True})
return render(request, 'cart/detail.html', {'cart': cart})
# Create your views here.
This is my cart/views.py file
from django.conf.urls import url
from . import views
app_name = 'cart'
urlpatterns = [
url(r'^$', views.cart_detail, name='cart_detail'),
url(r'^add/(?P<product_id>\d+)/$', views.cart_add, name='cart_add'),
url(r'^remove/(?P<product_id>\d+)/$', views.cart_remove, name='cart_remove'),
]
This is my cart/urls.py file
Your detail page isn't working because your template expects products, but you are only passing cart in your context. To fix it, just add products to your context before you render the template:
def cart_detail(request):
cart = Cart(request)
products = []
for item in cart:
item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'], 'update': True})
products.append(item)
context = { 'cart': cart }
context['products'] = products
return render(request, 'cart/detail.html', context)

using ModelForm Wizards with User Image Upload - can't get user.PK

I've been trying to create a photo upload system that allows users to upload an image and then write in a title and comment for that image. I was originally using a ModelForm when I made the image upload functionality but switched to a Form Wizard for the upload & comment functionality based on previous stackoverflow answers. I'm really confused on getting my site's user id system to work with this approach (I keep getting the error user id cannot be null when I attempt to upload pictures) and can't find any good resources -- any suggestions on whether this approach is valid and how I can fix the user_id issue?
Views.py:
def showScrapbookPage(request,userID):
if request.method == 'POST':
image = ImageUploadForm(request.POST, request.FILES)
user = User.objects.get(pk=userID)
if image.is_valid():
image.save()
scrapbook_gen = Pictures.objects
url = Pictures.objects.filter(user=User.objects.get(pk=userID))
return render(request, 'scrapbook/scrapbook.html', {'scrapbook_gen':scrapbook_gen, 'url':url, 'form': ImageUploadForm(),'userID':userID})
class PhotoWizard(SessionWizardView):
file_storage = FileSystemStorage(location = os.path.join(settings.MEDIA_ROOT, ''))
def done(self, form_list, **kwargs):
do_something_with_the_form_data(form_list)
return HttpResponseRedirect('/page-to-redirect-to-when-done/')
Models.py:
class Pictures(models.Model):
user = models.ForeignKey(User)
picture = models.ImageField(upload_to = 'scrapbook_uploads', default = 'static/scrapbook/images/no_pic_uploaded.jpg');
date = models.DateTimeField('date published', auto_now=True)
caption = models.TextField(blank = True)
title = models.CharField(max_length = 100, blank = True) #New
def __unicode__(self):
return self.caption
Forms.py:
class ImageUploadForm(ModelForm):
class Meta:
model = Pictures
fields = ['picture']
user = ['userID']
class TitleCommentForm(ModelForm):
class Meta:
model = Pictures
field = ["caption", "title"]
urls:
url(r'^(?P<userID>[-\w]+)/scrapbook/',views.showScrapbookPage, name='showScrapbook'),
url(r'^contact/$', PhotoWizard.as_view([ImageUploadForm, TitleCommentForm])),
Relevant section in template:
{% load i18n %}
{% block head %}
{{ wizard.form.media }}
{% endblock %}
{% block content %}
<p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
<form action="" method="post">{% csrf_token %}
<table>
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form }}
{% endfor %}
{% else %}
{{ wizard.form }}
{% endif %}
</table>
{% if wizard.steps.prev %}
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button>
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button>
{% endif %}
<input type="submit" value="{% trans "submit" %}"/>
</form>
{% endblock %}
<!--Grid -->
<div id='frame'>
<table id = "frame-table">
<tr>
<td id = "left">
<span class="glyphicon glyphicon-chevron-left" alt = "left"></span>
</td>
<td id = "right">
<span class = "glyphicon glyphicon-chevron-right" alt = "right"/>
</td>
</tr>
</table>
<img id = "main" src="" alt=""/>
</div>
<div id = "wrapper" class="showpiece">
<ul id = "portfolio">
{% for x in url %}
{{ x.picture }}
<li><img src = '{{ MEDIA_URL }}{{ x.picture }}' ></li>
{% endfor %}
</ul>
</div>
Thanks!
Completely remove your added UserID stuff and use user = request.userinstead in your views.