My order is not being saved. forms in django - django

Here you can see my models.py.
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name = 'customer', null=True, blank=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200)
tel = models.CharField(max_length=200)
def __str__(self):
return self.name
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
imya = models.CharField(max_length=200, null=False)
familiya = models.CharField(max_length=200, null=False)
tel = models.CharField(max_length=200, null=False)
address = models.CharField(max_length=200, null=False)
city = models.CharField(max_length=200, null=False)
state = models.CharField(max_length=200, null=False)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False)
transaction_id = models.CharField(max_length=100, null=True)
def __str__(self):
return str(self.id)
Here you can see my forms.py. Here I just created forms, but, the data should be got from template inputs.
from django import forms
from django.forms import ModelForm
from .models import *
class OrderForm(forms.ModelForm):
class Meta:
model = Order
fields = '__all__'
views.py
def checkout(request):
data = cartData(request)
cartItems = data['cartItems']
order = data['order']
items = data['items']
form = OrderForm()
if request.method == 'POST':
name = request.POST.get('name')
surname = request.POST.get('surname')
email = request.POST.get('email')
number = request.POST.get('number')
address = request.POST.get('address')
city = request.POST.get('city')
state = request.POST.get('state')
form = OrderForm(request.POST)
if form.is_valid():
Order.object.create(
imya=name,
familiya=surname,
tel=number,
adres=address,
city=city,
state=state,
)
form.save()
return HttpResponse('Заказ отправлен', safe=False)
context = {'items':items, 'order':order, 'cartItems':cartItems, 'form':form}
return render(request, 'store/checkout.html', context)
My template:
<section class="shop checkout section">
<div class="container">
<div class="row">
<div class="col-lg-8 col-12">
<div class="checkout-form">
<h2>Make Your Checkout Here</h2>
<p>Please register in order to checkout more quickly</p>
<!-- Form -->
<form class="form" method="post" action="#">
{% csrf_token %}
<div class="row">
<div class="col-lg-6 col-md-6 col-12">
<div class="form-group">
<label>First Name<span>*</span></label>
<input type="text" name="name" placeholder="" required="required">
</div>
</div>
<div class="col-lg-6 col-md-6 col-12">
<div class="form-group">
<label>Last Name<span>*</span></label>
<input type="text" name="surname" placeholder="" required="required">
</div>
</div>
<div class="col-lg-6 col-md-6 col-12">
<div class="form-group">
<label>Email Address<span>*</span></label>
<input type="email" name="email" placeholder="" required="required">
</div>
</div>
<div class="col-lg-6 col-md-6 col-12">
<div class="form-group">
<label>Phone Number<span>*</span></label>
<input type="number" name="number" placeholder="" required="required">
</div>
</div>
<div class="col-lg-6 col-md-6 col-12">
<div class="form-group">
<label>Address<span>*</span></label>
<input type="text" name="adress" placeholder="" required="required">
</div>
</div>
<div class="col-lg-6 col-md-6 col-12">
<div class="form-group">
<label>City<span>*</span></label>
<input type="text" name="city" placeholder="" >
</div>
</div>
<div class="col-lg-6 col-md-6 col-12">
<div class="form-group">
<label>State<span>*</span></label>
<input type="text" name="state" placeholder="" required="required">
</div>
</div>
<div class="col-12">
<div class="form-group create-account">
<input id="cbox" type="checkbox">
<label>Create an account?</label>
</div>
</div>
<input type="submit" value="Продолжить">
</div>
</form>
In my views, I want to create an object for my order model. I tried this code, It's not giving any errors, but it's not working. PLease, help with saving the order.

Related

Why the changes I made in the Django model not being reflected in the html form?

I have a field named 'amount' of type Floatfield.
I changed it to DecimalField and ran makemigrations and migrate commands and it successfully generated 0002_alter_expense_amount.py file.
This change is reflected in the database.
But in the html form when I try to add new amount It's showing this message.
When I tried the same from the admin panel it was successful
What should I do to make the html form accept the decimal value? Is there anything I'm missing?
models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils.timezone import now
class Expense(models.Model):
amount = models.DecimalField(decimal_places=2, max_digits=10)
date = models.DateField(default=now)
description = models.TextField()
owner = models.ForeignKey(to=User, on_delete=models.CASCADE)
category = models.CharField(max_length=255)
def __str__(self):
return self.category
class Meta:
ordering = ['-date']
class Category(models.Model):
name = models.CharField(max_length=255)
class Meta:
verbose_name_plural = 'Categories'
def __str__(self):
return self.name
views.py
#login_required(login_url="/authentication/login")
def add_expenses(request):
categories = Category.objects.all()
context = {
'categories': categories,
'values': request.POST
}
if request.method == 'POST':
amount = request.POST['amount']
description = request.POST['description']
date = request.POST['expense_date']
category = request.POST['category']
Expense.objects.create(owner=request.user, amount=amount, date=date, category=category, description=description)
messages.success(request, 'Expense saved successfully')
return redirect('expenses')
else:
return render(request, 'expenses/add-expenses.html', context)
html form
<form action="{% url 'add-expenses' %}" method="post">
{% include 'partials/messages.html' %}
{% csrf_token %}
<div class="form-group mb-3">
<label for="">Categories</label>
<select class="form-control form-control" name="category" required>
{% for category in categories%}
<option name="category" value="{{category.name}}">
{{category.name}}
</option>
{% endfor %}
</select>
</div>
<div class="form-group mb-3">
<label for="">Amount</label>
<input type="number" class="form-control form-control-sm" name="amount" required />
</div>
<div class="form-group mb-3">
<label for="">Description</label>
<input type="text" class="form-control form-control-sm" name="description" value="{{values.description}}">
</div>
<div class="form-group mb-3">
<label for="">Date</label>
<div class="d-grid gap-2 col-3">
<input type="date" class="form-control form-control-sm" name="expense_date" required>
</div>
</div>
<div class="d-grid gap-2 col-3">
<input type="submit" value="Add" class="btn btn-outline-dark" />
</div>
</form>

How to get value in Dropdown list on edit in Django template

I have a form (edit_city.html) where I want to edit my record, there is also one dropdown
field in which data is retrieving from another model name Country. How can I get the exact
value in dropdown field, when I click on edit.
Here is my Code
class Country(models.Model):
CountryID = models.AutoField(primary_key=True)
CountryName = models.CharField(max_length=125, verbose_name="Country Name")
def __str__(self):
return self.CountryName
class City(models.Model):
CityID = models.AutoField(primary_key=True)
CityName = models.CharField(max_length=125, verbose_name='City Name')
Country = models.ForeignKey(Country, verbose_name='Country Name',
on_delete=models.CASCADE)
def __str__(self):
return self.CityName
views.py
def Edit_City(request, id):
city = City.objects.get(CityID=id)
country = Country.objects.all()
context = {
'city':city,
'country':country,
}
return render(request, 'City/edit_city.html', context)
edit_city.html
<form method="post" action="{% url 'update_city' %}">
{% csrf_token %}
<div class="row">
<div class="col-12">
<h5 class="form-title"><span>Edit City</span></h5>
</div>
{% include 'includes/messages.html' %}
<div class="col-12 col-sm-6">
<div class="form-group">
<label for="">Country</label>
<select class="form-control" name="country_id" required>
<option>Select Country</option>
{% for con in country %}
<option value="{{con.CountryID}}">{{con.CountryName}}</option>
{% endfor %}
</select>
</div>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label>City Name</label>
<input type="text" class="form-control" name="city_name" value="{{city.CityName}}" required>
<input type="text" class="form-control" name="city_id" value="{{city.CityID}}" required hidden>
</div>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary">Update City</button>
</div>
</div>
</form>

Error: No file was submitted. Check the encoding type on the form

Please I’m having issue with register vendor, all was working fine before, so I just decided to retest everything have done, to my surprise the code thats working perfectly before is no more working. please help me out guys.............................................................................................................................................................
views.py
def registerRestaurant(request):
# this restrict user from going to Vendor Registration Page after Logged in
if request.user.is_authenticated:
messages.warning(request, "You are already logged in!")
return redirect('dashboard')
if request.method == 'POST':
form = UserForm(request.POST, request.FILES)
v_form = vendorForm(request.POST, request.FILES or None)
if form.is_valid() and v_form.is_valid():
password = form.cleaned_data['password'] # clean_data will return 'dict value'
user = form.save(commit=False)
user.set_password(password)
user.role = User.VENDOR
user.save()
vendor = v_form.save(commit=False)
vendor.user = user
user_profile = UserProfile.objects.get(user=user)
vendor.user_profile = user_profile
vendor.save()
mail_subject = 'Please Activate your Account'
email_template = 'accounts/emails/account_verification_email.html'
send_verification_email(request, user, mail_subject, email_template) #send_verification_email is function created in utils.py
messages.success(request, "Your Account has been Registered Successfully, Please Wait for Approval")
return redirect('registervendor')
else:
messages.error(request, 'An Error occurred during registration!')
else:
form = UserForm()
v_form = vendorForm()
context = {
'form': form,
'v_form': v_form,
}
return render(request, 'vendor/registervendor.html', context)
model.py (vendor)
class Vendor(models.Model):
user = models.OneToOneField(User, related_name='user', on_delete=models.CASCADE)
user_profile = models.OneToOneField(UserProfile, related_name='userprofile', on_delete=models.CASCADE)
vendor_name = models.CharField(max_length=50)
vendor_lincense = models.ImageField(upload_to='vendor/lincense')
is_approved = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.vendor_name
model.py (UserProfile)
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True)
profile_picture = models.ImageField(upload_to='users/profile_pictures', blank=True, null=True)
cover_photo= models.ImageField(upload_to='users/cover_photos', blank=True, null=True)
address = models.CharField(max_length=250, blank=True, null=True)
country = models.CharField(max_length=20, blank=True, null=True)
state= models.CharField(max_length=20, blank=True, null=True)
city = models.CharField(max_length=20, blank=True, null=True)
pin_code = models.CharField(max_length=6, blank=True, null=True)
latitude = models.CharField(max_length=20, blank=True, null=True)
longitude = models.CharField(max_length=20, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now_add=True)
# # Concatenate Address 1 and Address 2
# def full_address(self):
# return f'{self.address_line_1}, {self.address_line_2}'
def __str__(self):
return self.user.email
template
<div id="restaurant-sets-holder">
<form class="form-fields-set foodbakery-dev-restaurant-form" action = "{% url 'registervendor' %}" method = 'post' enctype = 'multipart/form-data'>
{% csrf_token %}
<ul class="register-add-restaurant-tab-container restaurant-information-tab-container">
<li>
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="row">
<ul >
<li>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="field-holder">
<label>First name</label>{{form.first_name}}
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="field-holder">
<label>Last name</label>{{form.last_name}}
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="field-holder">
<label>Restaurant name</label>{{v_form.vendor_name}}
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="field-holder">
<label>Restaurant lincense</label>{{v_form.vendor_lincense}}
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="field-holder">
<label>Email Address</label>{{form.email}}
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="field-holder">
<label>Username</label>{{form.username}}
</div>
</div>
</li>
<li>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
<div class="field-holder">
<label>Password</label>
{{form.password}}
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
<div class="field-holder">
<label>Confirm Password</label>
{{form.confirm_password}}
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</li>
<li>
<ul class="errorlist">
<!-- Fields Error -->
{% for field in form %}
{% if field.errors %}
{% for error in field.errors %}
<li style="color: red">{{error}}</li>
{% endfor %}
{% endif %}
{% endfor %}
<!-- Non Field Error -->
<li style="color: red">{{form.non_field_errors}}</li>
</ul>
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="field-holder">
<div class="payment-holder">
<input type="submit" value="Submit" id="btn-next-restaurant-information" class="bgcolor">
</div>
</div>
</div>
</div>
<!-- Success Message Display -->
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<!-- Load Message -->
{% include 'alerts.html' %}
</div>
</div>
</li>
</ul>
</form>

My form does not send data to the db django

My form does not send data to the database.
I have a form that after entering data and clicking 'Order' should send information to the database. However, this does not happen.
It is a 'cart' which, after sending the data, should save in the Order table information provided by the user as well as data on ordered products.
cart/views.py
def cart_detail(request, total=0, counter=0, cart_items = None):
try:
cart = Cart.objects.get(cart_id=_cart_id(request))
cart_items = CartItem.objects.filter(cart=cart, active=True)
for cart_item in cart_items:
total += (cart_item.product.price * cart_item.quantity)
counter += cart_item.quantity
except ObjectDoesNotExist:
pass
if request.method == 'POST':
total = request.POST['total']
billingName = request.POST['billingName']
billingAddress1 = request.POST['billingAddress1']
billingCity = request.POST['billingCity']
billingPostcode = request.POST['billingPostcode']
billingCountry = request.POST['billingCountry']
shippingName = request.POST['shippingName']
shippingAddress1 = request.POST['shippingAddress1']
shippingCity = request.POST['shippingCity']
shippingPostcode = request.POST['shippingPostcode']
shippingCountry = request.POST['shippingCountry']
order_details = Order.objects.create(total=total, billingName=billingName, billingAddress1=billingAddress1, billingCity=billingCity, billingPostcode=billingPostcode,billingCountry=billingCountry, shippingName=shippingName, shippingAddress1=shippingAddress1, shippingCity=shippingCity, shippingPostcode=shippingPostcode, shippingCountry=shippingCountry)
order_details.save()
for order_item in cart_items:
oi = OrderItem.objects.create(
product = order_item.product.name,
quantity = order_item.quantity,
price = order_item.product.price,
order = order_details
)
oi.save()
'''Reduce stock when order is placed or saved'''
products = Product.objects.get(id=order_item.product.id)
products.stock = int(order_item.product.stock - order_item.quantity)
products.save()
order_item.delete()
'''The terminal will print this message when the order is saved'''
print('The order has been created')
return redirect('cart:cart_detail')
return render(request, 'cart/cart.html', dict(cart_items = cart_items, total = total, counter = counter))
orders/models.py
from django.db import models
class Order(models.Model):
total = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='GBP Order Total')
created = models.DateTimeField(auto_now_add=True)
billingName = models.CharField(max_length=250, blank=True)
billingAddress1 = models.CharField(max_length=250, blank=True)
billingCity = models.CharField(max_length=250, blank=True)
billingPostcode = models.CharField(max_length=10, blank=True)
billingCountry = models.CharField(max_length=200, blank=True)
shippingName = models.CharField(max_length=250, blank=True)
shippingAddress1 = models.CharField(max_length=250, blank=True)
shippingCity = models.CharField(max_length=250, blank=True)
shippingPostcode = models.CharField(max_length=10, blank=True)
shippingCountry = models.CharField(max_length=200, blank=True)
class Meta:
db_table = 'Order'
ordering = ['-created']
def __str__(self):
return str(self.id)
class OrderItem(models.Model):
product = models.CharField(max_length=250)
quantity = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='GBP Price')
order = models.ForeignKey(Order, on_delete=models.CASCADE)
class Meta:
db_table = 'OrderItem'
def sub_total(self):
return self.quantity * self.price
def __str__(self):
return self.product
templates/cart/cart.html
<button class="btn send-click btn-md my-1 btn-block" data-toggle="modal" data-target="#inquiryModal">Complete Order</button>
<!-- Inquiry Modal -->
<div class="modal fade" id="inquiryModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="inquiryModalLabel">Complete Order</h5>
<button type="button" class="close" data-dismiss="modal">
<span>×</span>
</button>
</div>
<div class="modal-body">
<form action="{% url 'cart:cart_detail' %}" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="billingName" class="col-form-label">Name:</label>
<input type="text" name="billingName" class="form-control"
value="" required>
</div>
<div class="form-group">
<label for="billingAddress1" class="col-form-label">Adress:</label>
<input type="text" name="billingAddress1" class="form-control"
value="" required>
</div>
<div class="form-group">
<label for="billingCity" class="col-form-label">City:</label>
<input type="text" name="billingCity" class="form-control"
value="" required>
</div>
<div class="form-group">
<label for="billingPostcode" class="col-form-label">Post code:</label>
<input type="text" name="billingPostcode" class="form-control"
value="" required>
</div>
<div class="form-group">
<label for="billingCountry" class="col-form-label">Country:</label>
<input type="text" name="billingCountry" class="form-control"
value="" required>
</div>
<div class="form-group">
<label for="shippingName" class="col-form-label">Shop name:</label>
<input type="text" name="shippingName" class="form-control"
value="" required>
</div>
<div class="form-group">
<label for="shippingAddress1" class="col-form-label">Shop adress:</label>
<input type="text" name="shippingAddress1" class="form-control"
value="" required>
</div>
<div class="form-group">
<label for="shippingCity" class="col-form-label">Shop City:</label>
<input type="text" name="shippingCity" class="form-control"
value="" required>
</div>
<div class="form-group">
<label for="shippingPostcode" class="col-form-label">Shop Post code:</label>
<input type="text" name="shippingPostcode" class="form-control"
value="" required>
</div>
<div class="form-group">
<label for="shippingCountry" class="col-form-label">Shop Country:</label>
<input type="text" name="shippingCountry" class="form-control"
value="" required>
</div>
<hr>
<input type="submit" value="Order" class="btn send-click btn-md my-0 btn-block">
</form>
</div>
</div>
</div>
cart/urls.py
app_name='cart'
urlpatterns = [
path('add/<int:product_id>/', views.add_cart, name='add_cart'),
path('', views.cart_detail, name='cart_detail'),
path('remove/<int:product_id>/', views.cart_remove, name='cart_remove'),
path('full_remove/<int:product_id>/', views.full_remove, name='full_remove'),
]

How to store many to many fields with checkbox values in databse using django

With this code i want to store multiple courses to the student table.But this code is not working.Neither it throws any error neither saves any data.The main problem is while clicking submit button the submit button does not perform any action at all.It does not load the submit button.How can i solve this??
I think the problem is in add_student.html template.When i return form.error it throws course.Is there anything i have to change??but i want to keep my design like this
models.py
class Course(models.Model):
title = models.CharField(max_length=250)
basic_price = models.CharField(max_length=100)
advanced_price = models.CharField(max_length=100)
basic_duration = models.CharField(max_length=50)
advanced_duration = models.CharField(max_length=50)
def __str__(self):
return self.title
class Student(models.Model):
name = models.CharField(max_length=100)
course = models.ManyToManyField(Course)
address = models.CharField(max_length=200)
email = models.EmailField()
phone = models.CharField(max_length=15)
image = models.ImageField(upload_to='Students',blank=True)
joined_date = models.DateField()
def __str__(self):
return self.name
views.py
def addstudent(request):
courses = Course.objects.all()
if request.method == 'POST':
form = AddStudentForm(request.POST,request.FILES)
if form.is_valid():
student = form.save()
student.save()
# student.course.set(courses)
messages.success(request, 'student saved.')
return redirect('students:add_student')
else:
return HttpResponse(form.errors) # it returns course.i think the problem is while saving the course
else:
form = AddStudentForm()
return render(request,'students/add_student.html',{'form':form,'courses':courses})
forms.py
class AddStudentForm(forms.ModelForm):
course = forms.ModelMultipleChoiceField( queryset=Course.objects.all(), widget=forms.CheckboxSelectMultiple)
class Meta:
model = Student
fields = ['name','course','email','address','phone','image','joined_date']
add_student.html
<form action="{% url 'students:add_student' %}"
method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<h5>Full Name <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="name" class="form-control" required data-validation-required-message="This field is required"> </div>
</div>
<div class="form-group">
<h5>Courses <span class="text-danger">*</span></h5>
<div class="controls">
{% for course in courses %}
<input name ="course" type="checkbox" id="{{course.title}}" required value="{{course.id}}">
<label for="{{course.title}}">{{course.title}}</label>
{% endfor %}
</div>
</div>
<div class="form-group">
<h5>Address<span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="address" class="form-control" required data-validation-required-message="This field is required"> </div>
</div>
<div class="form-group">
<h5>Phone Number <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="phone" data-validation-required-message="This field is required" class="form-control" required> </div>
</div>
<div class="form-group">
<h5>Email <span class="text-danger">*</span></h5>
<div class="controls">
<input type="email" name="email" data-validation-required-message="This field is required" class="form-control" required> </div>
</div>
<div class="form-group">
<h5>Joined Date <span class="text-danger">*</span></h5>
<div class="controls">
<input type="date" name="joined_date" data-validation-required-message="This field is required" class="form-control" required> </div>
</div>
<div class="form-group">
<h5>Image <span class="text-danger">*</span></h5>
<div class="controls">
<input type="file" name="image" class="form-control" > </div>
</div>
<div class="text-xs-right">
<button type="submit" class="btn btn-info">Submit</button>
</div>
</form>
I'd recommend this solution:
courses = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset= Course.objects.all())
in views.py
if form.is_valid():
student = form.save(commit=False)
courses = form.cleaned_data['courses']
student.course = courses
student.save()
ps. it's a good practice to name m2m fields in plural:
courses = models.ManyToManyField(Course)
here's what I meant with templates:
in add_student.html
Comment out whole <form> block and replace it with Django's {{ form }} and see how it'd render
You have a queryset of courses passed in context to template. Try to change it from:
{% for course in courses %}
<input name ="course" type="checkbox" id="{{course.title}}" required value="{{course.title}}">
<label for="{{course.title}}">{{course.title}}</label>
{% endfor %}
to just:
{{ form.cource }}
Try a Class Based View
class CreateStudent(CreateView):
model = Student
form_class = AddStudentForm
template_name = "add_student.html"