I am creating a project using Python and Django in which I keeping track of all the products in my store, once I sell a particular product I need to update the number of units of that product remaining
Here is my Models.py file
from django.db import models
class Product(models.Model):
prod_name=models.CharField(max_length=100, blank=False)
company=models.CharField(max_length=100, blank=False)
quantity=models.IntegerField()
price=models.IntegerField()
prod_type=models.CharField(max_length=100)
units=models.IntegerField()
def __str__(self):
return('Name:{0} Company: {1} Qty:{2} Price: {3} Type:{4} Units: {5}'.format(self.prod_name, self.company,self.quantity, self.price, self.prod_type, self.units))
Here is my views.py file
from django.shortcuts import render, redirect, get_object_or_404
from .models import *
from .forms import *
def index(request):
return render(request, 'index.html')
def display_product(request):
items=Product.objects.all()
context={
'items':items
}
return render(request, 'index.html', context)
def add_product(request):
if request.method == "POST":
form = ProductForm(request.POST)
if form.is_valid():
form.save()
return redirect('index')
else:
form =ProductForm(request.POST)
return render(request, 'add_new.html', {'form':form})
def edit_product(request, pk):
item = get_object_or_404(Product, pk=pk)
if request.method == 'POST':
form = ProductForm(request.POST, instance=item)
if form.is_valid():
form.save()
return redirect('index')
else:
form = ProductForm(instance=item)
return render(request, 'edit_product.html', {'form':form})
def sell_product(request, pk):
item = get_object_or_404(Product, pk=pk)
if request.method == 'POST':
form = ProductForm(request.POST, instance=item)
if form.is_valid():
form.save()
return redirect('index')
else:
form = ProductForm(instance=item)
return render(request, 'sell_product.html', {'form':form})
Here is my sell_product.html
{% extends 'base.html' %}
{% block body %}
<div class="container">
<form method="POST">
<br>
{% csrf_token %}
<div class ="form-form row">
<label for="UpdateSold">Units Sold</label>
<input type="Units Sold" class="form-control" id="UpdateSold" aria-describedby="emailHelp" placeholder="Units Sold">
</div>
</div>
<button type="submit" class="btn btn-primary" name="button">Update Product</button>
</form>
</div>
{% endblock %}
So here is a snippet of front end
I have 25 Oreo cookies I sell 3 of them and I enter 3 in Units Sold so I want the Units value of Oreo cookies to be updated to 22Snippet
Related
When I send an image to the bank to save, it always returns this message "This field is required." but I fill the field with an image but it always returns this error.
Views
def criar (request):
form = forms_user()
if request.method == 'GET':
return render(request, 'create.html', {'form': form})
if request.method == 'POST':
form = forms_user(request.POST, request.FILES )
if form.is_valid():
form.save()
messages.add_message(request, constants.SUCCESS, 'Cadastro realizado com sucesso.')
form_clean = forms_user()
return render(request, 'create.html', {'form': form_clean})
else:
print(form.errors)
messages.add_message(request, constants.ERROR, f'{form.errors}')
return render(request, 'create.html', {'form': form})
Models
class items(models.Model):
titulo:models.CharField(max_length=30, blank=False)
descricao = models.TextField(max_length=50, blank=False)
usuario = models.CharField(max_length=20, blank=False)
Preco = models.BooleanField(blank=False)
royalties = models.PositiveIntegerField(blank=False)
image = models.ImageField(upload_to='image/', null=True, blank=True)
Forms
class forms_user (forms.ModelForm):
class Meta:
model = items
fields = '__all__'
HTML
<form id="contact" action="" method="post" enctype="multipart/form-data">
<fieldset>
<label for="file">Seu arquivo</label>
{% render_field form.image type="file" id="file" name="myfiles[]" %}
</fieldset>
</form>
Here in the forms I just put the form and the IMG field so it doesn't get too big but the other fields I put everything right.
At first there's a typo in model field titulo it should be = not :.
Secondly, you should always return an HttpResponseRedirect after dealing with POST data, the tip is not specific to Django, it's a good web practice in general, so use following view:
def criar(request):
if request.method == 'GET':
return render(request, 'create.html', {'form': forms_user()})
else:
form = forms_user(request.POST, request.FILES )
if form.is_valid():
form.save()
messages.add_message(request, constants.SUCCESS, 'Cadastro realizado com sucesso.')
return redirect("success")
else:
print(form.errors)
messages.add_message(request, constants.ERROR, f'{form.errors}')
return render(request, 'create.html', {'form': forms_user()})
If you have created modelform then render image field as below, and you can also remove the action attribute as Django by default takes current page route.
Html:
<form id="contact" method="POST" enctype="multipart/form-data">
<fieldset>
<label for="file">Seu arquivo</label>
{{form.image}}
</fieldset>
</form>
urls.py
urlpatterns=[
path("success/", views.success, name="success")
...
]
success.html:
<body>
<h1> The form has been successfully submitted </h1>
</body>
i have an issue on csrf token incorrect or invalid . i write the {% csrf_token %} above my form still I am getting that issue . can anyone help me in this ??
my HTML file code.
<h4>register page</h4>
<form method="POST" action="">
{% csrf_token %}
{{form.as_p}}
<input type="submit" name="Create User">
</form>
my view.py code
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.forms import inlineformset_factory
from django.contrib.auth.forms import UserCreationForm
from .models import *
from .forms import OrderForm
from .filters import OrderFilter
def registerPage(request):
form = UserCreationForm
if request.method=='POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
context={'form':form}
return render(request, 'accounts/register.html', context)
def loginPage(request):
context={}
return render(request, 'accounts/login.html', context)
def home(request):
orders = Order.objects.all()
customers = Customer.objects.all()
total_customers= customers.count()
total_orders = orders.count()
delivered = orders.filter(status='Delivered').count()
pending = orders.filter(status='Pending').count()
context = {'orders':orders,'customers':customers, 'total_customers': total_customers,
'total_orders':total_orders,'delivered':delivered,'pending':pending }
return render(request, 'accounts/index.html', context)
def products(request):
products = Product.objects.all()
return render(request, 'accounts/products.html', {'products':products})
def customers(request, pk):
customer = Customer.objects.get(id=pk)
orders = customer.order_set.all()
orders_count =orders.count()
myFilter= OrderFilter(request.GET, queryset=orders)
orders = myFilter.qs
context={'customer': customer, 'orders': orders, 'orders_count':orders_count,'myFilter':myFilter}
return render(request, 'accounts/customers.html', context)
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)
def updateOrder(request, pk):
order=Order.objects.get(id=pk)
form = OrderForm(instance=order)
if request.method == 'POST':
form= OrderForm(request.POST, instance=order)
if form.is_valid():
form.save()
return redirect('/')
context={'form':form}
return render(request,'accounts/order_form.html', context)
def deleteOrder(request, pk):
order=Order.objects.get(id=pk)
if request.method=="POST":
order.delete()
return redirect('/')
context={'item':order}
return render(request, 'accounts/delete.html', context)
enter code here
These are are my file any other files needed than I can provide you after applying csrf token still I am getting that error form is not being submitted.
Your action attribute is empty within your form:
action=""
You need to include an action, eg:
action="/somefolder/someviewname/"
or:
action="{% url 'name_of_app:name_of_view' %}"
So i want to do a edit existing comment, but it gives me this error
ValueError at /episode/Dragon-Ball-Super/edit/11
The view home.views.edit_comment didn't return an HttpResponse object. It returned None instead.
edit_comment
def edit_comment(request, slug, id):
anime = get_object_or_404(Anime, slug=slug)
comment = get_object_or_404(Comment, id=id)
form = CommentForm(request.POST, instance=comment.user)
if request.method == 'POST' or 'NONE':
if form.is_valid():
form.save()
return redirect('anime_title', slug=slug)
else:
form = CommentForm()
context = {'form': form}
return render(request, 'home/edit-comment.html', context)
urls.py
urlpatterns = [
path('', views.index, name='index'),
re_path(r'^episode/(?P<slug>[\w-]+)/$', views.anime_title, name='anime_title'),
re_path(r'^episode/(?P<slug>[\w-]+)/comment/$', views.add_comment, name='add_comment'),
re_path(r'^episode/(?P<slug>[\w-]+)/edit/(?P<id>\d+)/?', views.edit_comment, name='edit_comment'),
]
link under existing comment
{% if comment.user == request.user.userprofile %}
<h6 class="small comment-meta">
Edit
Delete</h6>
{% endif %}
models.py
class Comment(models.Model):
anime = models.ForeignKey(Anime, on_delete=models.CASCADE)
user = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
edit-comment.html
{% extends 'base/base.html' %}
{% block head %}
<title>Edit Comment</title>
{% endblock %}
{% block content %}
<h2>Edit Comment</h2>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}
You are handling only the POST request. GET request will be placed the first time when you load the form.
def edit_comment(request, slug, id):
anime = get_object_or_404(Anime, slug=slug)
comment = get_object_or_404(Comment, id=id)
form = CommentForm()
if request.method == 'POST':
form = CommentForm(request.POST, instance=comment.user)
if form.is_valid():
form.save()
return redirect('anime_title', slug=slug)
return render(request, 'home/edit-comment.html', {'form':form})
I need to get value from tag and redirect to '/value/' by submit.
Now I'm getting:
'ApartmentForm' object has no attribute 'cleaned_data'
I'm totally missing something.
forms.py
class ApartmentForm(ModelForm):
class Meta:
model = Apartment
fields = ['title']
views.py
def index(request):
context = {}
context['apartments'] = get_list_or_404(Apartment)
if request.method == 'POST':
form = ApartmentForm(request.POST or None)
context = {'form': form,}
id = form.cleaned_data.get('id', None)
return redirect(id)
else:
context['apartment_form'] = ApartmentForm
return render(request, 'main/main.html', context)
template
<form action="/{{ apartment.id }}" method="post">
{% csrf_token %}
<p><select size="10">
<option disabled>Chose apartment</option>
{% for apartment in apartments %}
<option value="{{ apartment.id }}">{{ apartment.title }}</option>
{% endfor %}
</select></p>
<input type="submit" value="Chose">
</form>
Update
Thanks Daniel!
It was such a fail not to call form in the template. I fixed that, but it still passing None to url (http://127.0.0.1:8000/None). Can't figure out why.
view.py
def index(request):
context = {}
context['apartments'] = get_list_or_404(Apartment)
if request.method == 'POST':
form = ApartmentForm(request.POST or None)
if form.is_valid():
id = form.cleaned_data.get('id', None)
return redirect(id)
else:
context['apartment_form'] = ApartmentForm
return render(request, 'main/main.html', context)
forms.py
APARTMENTS = ()
for apartment in Apartment.objects.all():
APARTMENTS += ((apartment.id, apartment.title),)
class ApartmentForm(Form):
apartment = ChoiceField(label='', widget=Select, choices=APARTMENTS)
template
<form action="." method="post">
{% csrf_token %}
{{ apartment_form }}
<input type="submit" value="Chose">
form.cleaned_data comes from form.is_valid(), so you sould change your views.py like this:
def index(request):
[...]
if request.method == 'POST':
form = ApartmentForm(request.POST or None)
if form.is_valid():
[...]
id = form.cleaned_data.get('id', None)
return redirect(id)
I want to insert multiple row into my database from form2. Below are my codes
first model.py
class DataPribadiSiswa(models.Model):
SiswaID = models.AutoField(primary_key=True)
WaliKelasID=models.CharField(max_length=5,blank=True,null=True)
second model.py
class RiwayatSekolah(models.Model):
SekolahID=models.AutoField(primary_key=True)
SiswaID_FK=models.ForeignKey(DataPribadiSiswa,blank=True, null=True)
SekolahNama=models.CharField(max_length=50,blank=True,null=True)
SekolahThMasuk=models.CharField(max_length=4,blank=True,null=True)
SekolahThKeluar=models.CharField(max_length=4,blank=True,null=True)
SekolahKet=models.TextField(blank=True,null=True)
views.py
def tambah_siswa(request):
form = datasiswa(request.POST)
form2 = riwayatsekolah(request.POST)
FormSet2 = inlineformset_factory(DataPribadiSiswa, RiwayatSekolah, extra=2, fields=('SekolahID','SiswaID_FK','SekolahNama','SekolahThMasuk','SekolahThKeluar','SekolahKet'))
if request.method == 'POST':
if form.is_valid():
siswa_instance = form.save()
form2 = FormSet2(request.POST, instance=siswa_instance)
if form2.is_valid():
form2.save()
return redirect('index')
else:
formall={}
formall['form'] = datasiswa()
formall['form2'] = riwayatsekolah()
return render(request, 'siswa/tambah_siswa.html', formall)
and this is my template
<form action="" method="post">
{% csrf_token %}
<table >
{{ form2.management_form }}
{{ form2.as_table }}
</table>
</form>
How to insert multiple row from form2 into database? when i run this code, it just insert one row.
To simplify working with related objects you can use Inline formsets
You can implement it this way:
from django.forms import inlineformset_factory
FormSet2 = inlineformset_factory(DataPribadiSiswa, RiwayatSekolah, extra=2)
Now in view try this:
def tambah_siswa(request):
form = datasiswa(request.POST or None)
FormSet2 = inlineformset_factory(DataPribadiSiswa, RiwayatSekolah, extra=2, fields=('SekolahID','SiswaID_FK','SekolahNama','SekolahThMasuk','SekolahThKeluar','SekolahKet'))
if request.method == 'POST':
if form.is_valid():
siswa_instance = form.save()
form2 = FormSet2(request.POST or None, instance=siswa_instance)
if form2.is_valid():
form2.save()
return redirect('index')
form2 = FormSet2(request.POST or None)
formall={}
formall['form'] = form
formall['form2'] = form2
return render(request, 'siswa/tambah_siswa.html', formall)
And in template:
{{ form2.management_form }}
{{ form2.as_table }}
or
{{ form2.management_form }}
{% for frm in form2 %}
{{ frm.as_table }}
{% endfor %}