Form is never valid - python

Im trying to create a website
models.py
from django.db import models
from django.forms import ModelForm
class Calculator(models.Model):
parents = models.CharField(max_length=100, blank=False)
jobs = models.CharField(max_length=100, blank=False)
grants_bursaries_scholarships = models.CharField(max_length=100, blank=False)
student_loan = models.CharField(max_length=100, blank=False)
other_income = models.CharField(max_length=100, blank=False)
rent = models.CharField(max_length=100, blank=False)
travel = models.CharField(max_length=100, blank=False)
bills = models.CharField(max_length=100, blank=False)
other_outcome = models.CharField(max_length=100, blank=False)
def total_income(parents, jobs, grants_bursaries_scholarships, student_loan, other_income):
return self.parents + self.jobs + self.grants_bursaries_scholarships + self.student_loan + self.other_income
def fixed_outcome(rent, travel, bills, other_outcome):
return self.rent + self.travel + self.bills + self.other_outcome
def variable_outcomes(total_income, fixed_outcome):
return self.total_income - self.fixed_outcome
def food(variable_outcomes):
return (43.66 * variable_outcomes) / 100.0
def socialising(percent, whole):
return (22.54 * variable_outcomes) / 100.0
forms.py
from django import forms
class MyCalculator(forms.Form):
parents1 = forms.CharField(max_length=40, required=True)
jobs1 = forms.CharField(max_length=50)
grants_bursaries_scholarships1 = forms.CharField(max_length=40, required=True)
student_loan1 = forms.CharField(max_length=40, required=True)
other_income1 = forms.CharField(max_length=40, required=True)
rent1 = forms.CharField(max_length=40, required=True)
travel1 = forms.CharField(max_length=40, required=True)
bills1 = forms.CharField(max_length=40, required=True)
other_outcome1 = forms.CharField(max_length=40, required=True)
views.py
from django import forms
from .forms import MyCalculator
def formview(request):
if request.method == 'POST':
form = MyCalculator(request.POST)
if form.is_valid():
myform = MyCalculator()
myform.parents = form.cleaned_data.get(parents1)
myform.jobs = form.cleaned_data.get(jobs1)
myform.grants_bursaries_scholarships = form.cleaned_data.get(grants_bursaries_scholarships1)
myform.student_loan = form.cleaned_data.get(student_loan1)
myform.other_income = form.cleaned_data.get(other_income1)
myform.rent = form.cleaned_data.get(rent1)
myform.travel = form.cleaned_data.get(travel1)
myform.bills = form.cleaned_data.get(bills1)
myform.other_outcome = form.cleaned_data.get(other_outcome1)
myform.total_income(myform.parents, myform.jobs, myform.grants_bursaries_scholarships, myform.student_loan, myform.other_income)
myform.fixed_outcome(myform.rent, myform.travel, myform.bills, myform.other_outcome)
myform.variable_outcomes(myform.total_income, myform.fixed_outcome)
myform.save()
return render(request, 'Noteable_Budgeting/out.html')
else:
return HttpResponseRedirect('/calculator/fail')
else:
form = MyCalculator()
return render(request, 'Noteable_Budgeting/calculator_list.html', {'form':form})
def failview(request):
return render(request, 'Noteable_Budgeting/fail.html')
this is the main view of the website
{% block titleblock %}
<title>Noteable Budgeting</title>
{% endblock %}
{% block content %}
<div class="text2">
<h1>Budgeting Calculator</h1>
<h2>Noteable Budgeting</h2>
<br>
<h3>
Input your weekly incomes and fixed outcomes and our calculator will give you a recommended spending amount on food and social based on the average spent by students.
</h3>
<br>
<form action="/calculator/test/" method="post">{% csrf_token %}
<p>
<div class="ui-widget">
<label for="parents">Parents:</label>
<input id="parents" type="number" name="parents" maxlength="100" />
</div>
</p>
<p>
<div class="ui-widget">
<label for="jobs">Jobs:</label>
<input id="jobs" type="number" name="jobs" maxlength="100" />
</div>
</p>
<p>
<div class="ui-widget">
<label for="grants_bursaries_scholarship">Grants/Bursaries/Scholarships:</label>
<input id="grants_bursaries_scholarship" type="number" name="grants_bursaries_scholarships" maxlength="100" />
</div>
</p>
<p>
<div class="ui-widget">
<label for="student_loan">Student Loan:</label>
<input id="student_loan" type="number" name="student_loan" maxlength="100" />
</div>
</p>
<p>
<div class="ui-widget">
<label for="other_income">Other Income:</label>
<input id="other_income" type="number" name="other_income" maxlength="100" />
</div>
</p>
<p>
<div class="ui-widget">
<label for="rent">Rent:</label>
<input id="rent" type="number" name="rent" maxlength="100" />
</div>
</p>
<p>
<div class="ui-widget">
<label for="travel">Travel:</label>
<input id="travel" type="number" name="travel" maxlength="100" />
</div>
</p>
<p>
<div class="ui-widget">
<label for="bills">Bills:</label>
<input id="bills" type="number" name="bills" maxlength="100" />
</div>
</p>
<p>
<div class="ui-widget">
<label for="other_outcome">Other Outcome:</label>
<input id="other_outcome" type="number" name="other_outcome" maxlength="100" />
</div>
</p>
<input type="submit" value="Submit" />
</form>
<br>
<br>
</div>
{% endblock %}
Whenever I submit the form, with numbers or blank, it returns the "failview" page. I want it to return the out.html page when the form is submitted and return some figures which are calculated in the models.py.

Related

select not creating category entry in django database

I need to make it so that the select from the form is displayed in the database, None appears in its place in the database
everything is added except categories and stocks
I was told that I need to add value to option, but nothing happened
what's wrong
Here is my views.py :
def create_product(request):
user = request.user
category = user.category_set.all()
stock = user.stock_set.all()
if request.method == 'POST':
product = Product()
product.title = request.POST.get('title')
product.categories = user.category_set.get(id=request.POST.get('categories'))
product.price = request.POST.get('price')
product.user = request.POST.get('user')
product.amount = request.POST.get('amount')
product.stock = Stock.objects.get(id=request.POST.get('stock'))
product.user = request.user
product.save()
return redirect('index')
return render(request, 'main/create.html', {'category':category,'stocks':stock})
Here is my models.py :
class Product(models.Model):
title = models.CharField(verbose_name="Название товара", max_length=250)
categories = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True)
price = models.IntegerField(verbose_name="Цена")
user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='products')
amount = models.CharField(max_length=250,verbose_name='Количество')
user = models.ForeignKey(User, on_delete=models.PROTECT)
stock = models.ForeignKey(Stock, on_delete=models.PROTECT, blank=True, null=True)
def get_absolute_url(self):
return reverse("post_detail",kwargs={'pk':self.pk})
class Meta:
verbose_name = 'Товар'
verbose_name_plural = 'Товары'
def __str__(self):
return self.title
My create template :
<div class="" style="width: 600px; margin:0 auto; transform: translate(0, 10%);">
<h1 class="display-6">Создайте товар</h1>
<form action="{% url 'create_product' %}" method="POST" class="form-control" style="background:rgba(0, 0, 0, 0.1); height: 500px;">
{% csrf_token %}
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Название</label>
<input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Название товара" name="title">
</div>
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Цена</label>
<input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Цена товара" name="price">
</div>
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Количество товара</label>
<input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Кол-во" name="amount">
</div>
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Категория</label>
<select class="form-select" aria-label="Default select example" name="category">
{% for categories in categories %}
<option value="">{{ categories.title }}</option>
{% endfor %}
</select>
</div>
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Склад</label>
<select class="form-select" aria-label="Default select example" name="stock">
{% for stocks in stocks %}
<option value="{{ stocks.pk }}" >{{ stocks.title }}</option>
{% endfor %}
</select>
</div>
<div class="mb-3">
<button class="btn btn-success">Создать</button>
Выйти
</div>
</form>
</div>

my form not updating database, it sends GET instead of POST

i'm new trying to learn Django by building my e-commerce website.
In my terminal i'm getting GET and POST, although i specified action to POST
image result in my terminal
this code works great before i add translation to my website, but after adding Internationalization to my project, the form is no longer working(the form is not translated because it is comment section)
models.py:
class Comment(models.Model):
STATUS = (
('New', 'New'),
('True', 'True'),
('False', 'False'),
)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
subject = models.CharField(max_length=50, blank=True)
comment = models.CharField(max_length=250, blank=True)
rate = models.IntegerField(default=1)
ip = models.CharField(max_length=20, blank=True)
status = models.CharField(max_length=10, choices=STATUS, default='New')
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.subject
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ['subject', 'comment', 'rate']
views.py:
def addcomment(request, id):
url = request.META.get('HTTP_REFERER') # get last url
# return HttpResponse(url)
if request.method == 'POST': # check post
form = CommentForm(request.POST)
if form.is_valid():
data = Comment() # create relation with model
data.subject = form.cleaned_data['subject']
data.comment = form.cleaned_data['comment']
data.rate = form.cleaned_data['rate']
data.ip = request.META.get('REMOTE_ADDR')
data. product_id = id
current_user = request.user
data.user_id = current_user.id
data.save() # save data to table
messages.success(request, "Your review has ben sent. Thank you for your interest.")
return HttpResponseRedirect(url)
return HttpResponseRedirect(url)
html code:
<div class="collapse" id="reviewForm">
<form class="review-form"
action="/cart/addcomment/{{ product.id }}" method="post">
{% csrf_token %}
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="sr-only" for="reviewEmail">subject:</label>
<input class="form-control form-control-sm" name="subject" type="text" placeholder="Your subject" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label class="sr-only" for="reviewText">Review:</label>
<textarea class="form-control form-control-sm" name="comment" rows="5" placeholder="Your review " required></textarea>
</div>
</div>
<div class="row">
<div class="col-md-6 d-flex justify-content-between">
<div class="p-2">
<div class="form-group">
<div class="input-rating">
<strong class="">Please rate: </strong>
<div class="stars">
<input type="radio" id="star5" name="rate" value="5" /><label for="star5"></label>
<input type="radio" id="star4" name="rate" value="4" /><label for="star4"></label>
<input type="radio" id="star3" name="rate" value="3" /><label for="star3"></label>
<input type="radio" id="star2" name="rate" value="2" /><label for="star2"></label>
<input type="radio" id="star1" name="rate" value="1" /><label for="star1"></label>
</div>
</div>
</div>
</div>
<div class="p-2 d-flex justify-content-between">
{% if user.id is not None %}
<button class="btn btn-outline-dark" type="submit">
Post Review
</button>
{% else %}
You must be logged in to post a review
{% endif %}
</div>
</div>
</div>
</form>
</div><br>
urlpatterns:
path('addcomment/int:id', views.addcomment, name='addcomment'),
admin.py:
#admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
list_display = ['subject', 'comment', 'status', 'create_at']
list_filter = ['status']
readonly_fields = ('subject', 'comment', 'user', 'product', 'rate', )
thanks
Here is the code in one codeblocks
models.py
class Comment(models.Model):
STATUS = (
('New', 'New'),
('True', 'True'),
('False', 'False'),
)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
subject = models.CharField(max_length=50, blank=True)
comment = models.CharField(max_length=250, blank=True)
rate = models.IntegerField(default=1)
ip = models.CharField(max_length=20, blank=True)
status = models.CharField(max_length=10, choices=STATUS, default='New')
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.subject
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = ['subject', 'comment', 'rate']
views.py
def addcomment(request, id):
url = request.META.get('HTTP_REFERER') # get last url
# return HttpResponse(url)
if request.method == 'POST': # check post
form = CommentForm(request.POST)
if form.is_valid():
data = Comment() # create relation with model
data.subject = form.cleaned_data['subject']
data.comment = form.cleaned_data['comment']
data.rate = form.cleaned_data['rate']
data.ip = request.META.get('REMOTE_ADDR')
data. product_id = id
current_user = request.user
data.user_id = current_user.id
data.save() # save data to table
messages.success(request, "Your review has ben sent. Thank you for your interest.")
return HttpResponseRedirect(url)
return HttpResponseRedirect(url)
urlpatterns
urlpatterns = [
path('addcomment/<int:id>', views.addcomment, name='addcomment')]
html
<div class="collapse" id="reviewForm">
<form class="review-form"
action="/cart/addcomment/{{ product.id }}" method="post">
{% csrf_token %}
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="sr-only" for="reviewEmail">subject:</label>
<input class="form-control form-control-sm" name="subject" type="text" placeholder="Your subject" required>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<label class="sr-only" for="reviewText">Review:</label>
<textarea class="form-control form-control-sm" name="comment" rows="5" placeholder="Your review " required></textarea>
</div>
</div>
<div class="row">
<div class="col-md-6 d-flex justify-content-between">
<div class="p-2">
<div class="form-group">
<div class="input-rating">
<strong class="">Please rate: </strong>
<div class="stars">
<input type="radio" id="star5" name="rate" value="5" /><label for="star5"></label>
<input type="radio" id="star4" name="rate" value="4" /><label for="star4"></label>
<input type="radio" id="star3" name="rate" value="3" /><label for="star3"></label>
<input type="radio" id="star2" name="rate" value="2" /><label for="star2"></label>
<input type="radio" id="star1" name="rate" value="1" /><label for="star1"></label>
</div>
</div>
</div>
</div>
<div class="p-2 d-flex justify-content-between">
{% if user.id is not None %}
<button class="btn btn-outline-dark" type="submit">
Post Review
</button>
{% else %}
You must be logged in to post a review
{% endif %}
</div>
</div>
</div>
</form>
</div><br>
Create Forms.py file and add the form fields below with proper indentation like this:
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['subject', 'comment', 'rate']

Django Forms posting not working - Django simply renders the page again

Basically I have set up a form to create organizations. When I hit the Save button, it simply renders the page again - the POST is not working.
See my code below:
models.py
from django.db import models
from accounts.models import User
from datetime import datetime, date
#// ------------ FUNCTIONS -------------//
# Generate Organisation IDs for each organisation
def org_id_generate():
last_org = Organization.objects.all().order_by('org_id').last()
if not last_org:
return 'ORG_001'
else:
last_org_id = last_org.org_id
number_in_id = int(last_org_id[4:7])
new_number_in_id = number_in_id + 1
new_org_id = 'ORG_' + str(new_number_in_id).zfill(3)
return new_org_id
#// ------------ MODELS -------------//
class Organization(models.Model):
org_id = models.CharField(primary_key=True, max_length=7, default=org_id_generate, editable=False)
organization_code = models.CharField(max_length=20)
company_name = models.CharField(verbose_name="Company Name", max_length=60)
legal_name = models.CharField(verbose_name="Legal Name", max_length=100)
industry_distribution = models.BooleanField(verbose_name="Distribution", default=False)
industry_education = models.BooleanField(verbose_name="Education", default=False)
industry_healthcare = models.BooleanField(verbose_name="Healthcare", default=False)
industry_manufacturing = models.BooleanField(verbose_name="Manufacturing", default=False)
industry_retail = models.BooleanField(verbose_name="Retail", default=False)
industry_services = models.BooleanField(verbose_name="Services", default=False)
business_registration_no = models.CharField(verbose_name="Business Registration Number", max_length=15, blank=True)
vat_registration_no = models.CharField(verbose_name="VAT Registration Number", max_length=15, blank=True)
created_date = models.DateTimeField(default=datetime.now)
created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="Created_By", verbose_name="Created By")
effective_start_date = models.DateField(auto_now_add=False)
effective_end_date = models.DateField(auto_now_add=False, blank=True, null=True)
update_date = models.DateTimeField(default=datetime.now)
last_updated_by = models.ForeignKey(User, on_delete=models.DO_NOTHING, related_name="Last_Updated_By", verbose_name="Last Updated By")
def __str__(self):
return self.company_name
forms.py
from django import forms
from organizations.models import Organization
class OrganizationAddForm(forms.ModelForm):
class Meta:
model = Organization
exclude = ['created_date', 'update_date', ]
views.py
from django.shortcuts import get_object_or_404, render, redirect
from organizations.models import Organization
from forms import OrganizationAddForm
from accounts.models import User
from django.contrib.auth.decorators import login_required
#login_required()
def settings(request):
return render(request, 'settings/settings.html')
#login_required()
def organizations_settings(request):
orgs = Organization.objects.all()
context = {
'orgs': orgs,
}
return render(request, 'settings/settings_organizations.html', context)
#login_required
def organization_add(request):
if request.method == 'POST':
user_email = request.user.email
form = OrganizationAddForm(request.POST)
if form.is_valid():
form.organization_code = form.cleaned_data['organization_code']
form.company_name = form.cleaned_data['company_name']
form.legal_name = form.cleaned_data['legal_name']
form.business_registration_no = form.cleaned_data['brn']
form.vat_registration_no = form.cleaned_data['vat']
form.industry_distribution = form.cleaned_data['industry_distribution']
form.industry_education = form.cleaned_data['industry_education']
form.industry_healthcare = form.cleaned_data['industry_healthcare']
form.industry_manufacturing = form.cleaned_data['industry_manufacturing']
form.industry_retail = forms.cleaned_data['industry_retail']
form.industry_services = form.cleaned_data['industry_services']
form.effective_start_date = form.cleaned_data['effective_start_date']
form.effective_end_date = form.cleaned_data['effective_end_date']
form.created_by = form.cleaned_data[user_email]
form.last_updated_by = form.cleaned_data[user_email]
form.save()
return redirect('organizations_settings')
else:
form = OrganizationAddForm()
return render(request, 'settings/add_organization.html', {'form': form})
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.settings, name="settings"),
path('organizations/', views.organizations_settings, name='organizations_settings'),
path('organization_create', views.organization_create, name="organization_create"),
path('organizations/add/', views.organization_add, name="organization_add"),
]
Page Source Code
<!-- Add Organization Form -->
<div class="container form-style">
<i class="fas fa-arrow-left"></i> Back
<div class="form-header">
<h3>Add Organization</h3>
</div>
<form action="{% url 'organization_add' %}" method="POST">
{% csrf_token %}
<div class="container">
<!-- Row 1 -->
<div class="row">
<div class="col-md-4">
<label for="organization_code">Organization Code<span class="star-red">*</span></label>
<input type="text" name="organization_code" class="form-control" required>
</div>
<div class="col-md-4">
<label for="company_name">Organization Name<span class="star-red">*</span></label>
<input type="text" name="company_name" class="form-control" required>
</div>
<div class="col-md-4">
<label for="legal_name">Legal Name<span class="star-red">*</span></label>
<input type="text" name="legal_name" class="form-control" required>
</div>
</div>
<!-- Row 2 -->
<div class="row mt-4">
<!-- <div class="col-md-4">
<label for="industry">Industry<span class="star-red">*</span></label>
<select name="industry" class="selectpicker">
<option value="distribution">Distribution</option>
<option value="education">Education</option>
<option value="healthcare">Healthcare</option>
<option value="manufacturing">Manufacturing</option>
<option value="retail">Retail</option>
<option value="services">Services</option>
</select>
</div> -->
<div class="col-md-6">
<label for="brn">Business Registration No.</label>
<input type="text" name="brn" class="form-control">
</div>
<div class="col-md-6">
<label for="vat">VAT Registration No.</label>
<input type="text" name="vat" class="form-control">
</div>
</div>
<!-- Row 3 -->
<h5 class="mt-4">Industry</h5>
<div class="row">
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_distribution" class="form-check-input">
<label for="industry_distribution" class="form-check-label">Distribution</label>
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_education" class="form-check-input">
<label for="industry_education" class="form-check-label">Education</label>
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_healthcare" class="form-check-input">
<label for="industry_healthcare" class="form-check-label">Healthcare</label>
</div>
</div>
</div>
<div class="row mt-2">
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_manufacturing" class="form-check-input">
<label for="industry_manufacturing" class="form-check-label">Manufacturing</label>
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_retail" class="form-check-input">
<label for="industry_retail" class="form-check-label">Retail</label>
</div>
</div>
<div class="col-md-4">
<div class="form-check">
<input type="checkbox" name="industry_services" class="form-check-input">
<label for="industry_services" class="form-check-label">Services</label>
</div>
</div>
</div>
<!-- Row 4 -->
<div class="row mt-4">
<div class="col-md-6">
<label for="effective_start_date">Effective Start Date<span class="star-red">*</span></label>
<input type="date" name="effective_start_date" class="form-control" required>
</div>
<div class="col-md-6">
<label for="effective_end_date">Effective End Date:</label>
<input type="date" name="effective_end_date" class="form-control">
</div>
</div>
<!-- Hidden Input - User -->
<input type="hidden" name="user_email" />
<div class="float-right mt-3">
<button type="submit" class="btn btn-custom save">Save and Close</button>
</div>
</div>
</form>
</div>
Any help would be greatly appreciated. If you need any additional info, let me know and I will edit the post.
I did not find any code to show the errors in html.
According to the function in views, if the form is not valid, then it renders the page with the form.
Try to add {{form.errors}} to you the html file to see if it has errors?
I managed to solve it.
views.py
#login_required
def organization_add(request):
if request.method == 'POST':
form = OrganizationAddForm(request.POST)
if form.is_valid():
form.organization_code = form.cleaned_data['organization_code']
form.company_name = form.cleaned_data['company_name']
form.legal_name = form.cleaned_data['legal_name']
form.business_registration_no = form.cleaned_data['business_registration_no']
form.vat_registration_no = form.cleaned_data['vat_registration_no']
form.industry_distribution = form.cleaned_data['industry_distribution']
form.industry_education = form.cleaned_data['industry_education']
form.industry_healthcare = form.cleaned_data['industry_healthcare']
form.industry_manufacturing = form.cleaned_data['industry_manufacturing']
form.industry_retail = form.cleaned_data['industry_retail']
form.industry_services = form.cleaned_data['industry_services']
form.effective_start_date = form.cleaned_data['effective_start_date']
form.effective_end_date = form.cleaned_data['effective_end_date']
org = form.save(commit=False)
org.created_by = request.user
org.last_updated_by = request.user
org.save()
return redirect('organizations_settings')
else:
form = OrganizationAddForm()
return render(request, 'settings/add_organization.html', {'form': form})
The issue was that it was not able to capture the user email for the Created By and Last Updated By fields.
This is resolved by using:
org = form.save(commit=False)
org.created_by = request.user
org.last_updated_by = request.user
Note that the following two posts helped me:
Using request.user with Django ModelForm
Cannot assign "42": "Event.user_id" must be a "User" instance

Reverse for 'post' with keyword arguments '{'pk': 8}' not found. 1 pattern(s) tried: ['Loader/post/$'] "DANGO"

urls.py
app_name = 'Loader'
urlpatterns = [
path('post_detail/', views.Loader_post_view.as_view(), name="post_detail"),
path('post/', views.post.as_view(), name="post"),
path('my_job/', views.Loader_post_list.as_view(), name="my_job"),
path('delete/<int:pk>', views.Loader_post_delete.as_view(), name="Delete"),
path('update/<int:pk>', views.Loader_post_update.as_view(template_name="post_detail.html"),
name="Update")
]
this is my models.py
class Loader_post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Loader")
pick_up_station = models.CharField(max_length=150)
destination_station = models.CharField(max_length=150)
sender_name = models.CharField(max_length=150)
phone_number = PhoneNumberField(null=False, blank=False, unique=True)
receiver_name = models.CharField(max_length=150)
sending_item = models.CharField(max_length=150)
#image_of_load = models.ImageField(default='',upload_to='static/img')
weight = models.CharField(max_length=150)
metric_unit = models.CharField(max_length=30, default='')
quantity = models.PositiveIntegerField()
pick_up_time = models.DateField()
drop_time = models.DateField()
paid_by = models.CharField(max_length=150)
created_at = models.DateTimeField(auto_now=True)
published_date = models.DateField(blank=True, null=True)
def __str__(self):
return self.user.username
def get_absolute_url(self):
return reverse("Loader:post", kwargs={'pk': self.pk})
this if my views.py
class Loader_post_view(CreateView,LoginRequiredMixin):
form_class = forms.Loader_post_form
model = Loader_post
template_name = "post_detail.html"
def form_valid(self, form):
print(form.cleaned_data)
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
this is my post form in html
<form method="POST">
{% csrf_token %}
<div class="container">
<div class="form-row">
<div class="col">{% render_field form.pick_up_station class="form-control" placeholder="Enter pick_up_station"%}</div>
<div class="col">{% render_field form.destination_station class="form-control" placeholder="Enter destination_station"%}</div>
</div>
<div class="form-row">
<div class="col">{% render_field form.sender_name class="form-control" placeholder="Enter sender_name"%}</div>
<div class="col">{% render_field form.phone_number class="form-control" placeholder="Enter phone_number"%}</div>
</div>
<div class="form-row">
<div class="col">{% render_field form.receiver_name class="form-control" placeholder="Enter receiver name"%}</div>
<div class="col">{% render_field form.sending_item class="form-control" placeholder="Enter sending_item"%}</div>
</div>
<div class="form-row">
<div class="col">{% render_field form.weight class="form-control" placeholder="Enter weight"%}</div>
<div class="col">{% render_field form.metric_unit class="form-control" placeholder="Enter metric_unit"%}</div>
</div>
<div class="form-row">
<div class="col">{% render_field form.quantity class="form-control" placeholder="Enter quantity"%}</div>
<div class="col">{% render_field form.pick_up_time class="form-control" placeholder="Enter pick_up_time"%}</div>
</div>
<div class="form-row">
<div class="col">{% render_field form.drop_time class="form-control" placeholder="Enter drop_time"%}</div>
<div class="col">{% render_field form.paid_by class="form-control" placeholder="Enter paid_by"%}</div>
</div>
<button class="btn btn-full" type="submit">submit</button>
</div>
now my question is when i click on submit it shows that error and sometime when i put 'post' by replacing self it will work fine 'pk':self.pk however, if new user logged in and try to post the data it will not store onto the database please help me to find out this error
Your post url has no pk url parameter. You need to add one:
app_name = 'Loader'
urlpatterns = [
path('post_detail/', views.Loader_post_view.as_view(), name="post_detail"),
path('post/<int:pk>', views.post.as_view(), name="post"),
path('my_job/', views.Loader_post_list.as_view(), name="my_job"),
path('delete/<int:pk>', views.Loader_post_delete.as_view(), name="Delete"),
path('update/<int:pk>', views.Loader_post_update.as_view(template_name="post_detail.html"),
name="Update")
]

Update in django

I am new to django and I want to make an update view but I can't succeed.
I have this page that shows information about a user, and when I press the 'Update My Profile' button I want to update or save(i.e if I change 'Laszlo' with 'Lucy' I want to update it and if I write in the 'nickname' input: 'NICKNAME' I want to save that infomartion into de dababase so next time when I access this page to show me all the information about the user)
My models: 'UserProfile'(which is the 'User') and 'User_Details'(they are in 1-1 relationship)
class UserProfile(AbstractUser):
pass
class User_Details(models.Model):
user = models.OneToOneField(UserProfile, on_delete=models.CASCADE)
first_name = models.CharField(max_length=50, blank = True)
last_name = models.CharField(max_length=50, blank=True)
gender = models.CharField(max_length=6, blank=True, default='')
image = models.ImageField(upload_to='avatar_image', blank=True, null=True)
public_info=models.CharField(max_length=100, blank=False, default='')
nickname=models.CharField(max_length=100,blank=True,default="")
website=models.CharField(max_length=100,blank=True,default="")
My view to show the information:
class ShowProfile(APIView):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'profile.html'
def get(self, request, pk, format=None):
details = UserProfile.objects.get(id=pk)
serializer = UserProfileSerializer(details)
pprint.pprint(json.loads(JSONRenderer().render(serializer.data)))
return Response({'seri':serializer.data})
Serializers:
class UserDetailsSerializer(serializers.ModelSerializer):
class Meta:
model = User_Details
fields = (
'first_name',
'last_name',
'gender',
'public_info',
'nickname',
'website'
)
class UserProfileSerializer(serializers.ModelSerializer):
user_details = UserDetailsSerializer()
lookup_field = 'username'
class Meta:
model = UserProfile
fields = ('id', 'user_details')
Template:
{% extends 'base2.html' %}
{% load rest_framework %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-md-3 ">
<div class="list-group ">
Profile
My Posts
</div>
</div>
<div class="col-md-9">
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12">
<h4>Your Profile</h4>
<hr>
</div>
</div>
<div class="row">
<div class="col-md-12">
<form>
<div class="form-group row">
<label for="username" class="col-4 col-form-label">User Name*</label>
<div class="col-8">
<input id="username" name="username" placeholder="" class="form-control here" required="required" type="text">
</div>
</div>
<div class="form-group row">
<label for="name" class="col-4 col-form-label">First Name</label>
<div class="col-8">
<input id="name" name="first_name" placeholder= {{ seri.user_details.first_name }} class="form-control here" type="text">
</div>
</div>
<div class="form-group row">
<label for="lastname" class="col-4 col-form-label">Last Name</label>
<div class="col-8">
<input id="lastname" name="last_name" placeholder={{ seri.user_details.last_name}} class="form-control here" type="text">
</div>
</div>
<div class="form-group row">
<label for="text" class="col-4 col-form-label">Nick Name*</label>
<div class="col-8">
<input id="text" name="nickname" placeholder="{{ seri.user_details.nickname}}" class="form-control here" required="required" type="text">
</div>
</div>
<div class="form-group row">
<label for="website" class="col-4 col-form-label">Website</label>
<div class="col-8">
<input id="website" name="website" placeholder="{{seri.user_details.website}} " class="form-control here" type="text">
</div>
</div>
<div class="form-group row">
<label for="publicinfo" class="col-4 col-form-label">Public Info</label>
<div class="col-8">
<textarea id="publicinfo" name="public_info" cols="40" rows="4" class="form-control" placeholder='{{seri.user_details.public_info}}'></textarea>
</div>
</div>
<div class="form-group row">
<div class="offset-4 col-8">
<button name="submit" type="submit" class="btn btn-primary">Update My Profile</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
I tried to make this(into the 'ShowProfile' view) :
def put(self, request,pk):
serializer = ProfileUpdateSerializer()
post = request.POST.copy()
serializer.update(validated_data=dict(post))
return HttpResponseRedirect('/account/login.html')
Serializer
class ProfileUpdateSerializer(serializers.HyperlinkedModelSerializer):
first_name = serializers.CharField(source='User_Details.first_name')
last_name = serializers.CharField(source='User_Details.last_name')
gender = serializers.CharField(source='User_Details.gender')
public_info = serializers.CharField(source='User_Details.public_info')
# image=serializers.ImageField(source='User_Details.image')
nickname = serializers.CharField(source='User_Details.nickname')
website = serializers.CharField(source='User_Details.website')
class Meta:
model = User_Details
fields = ('first_name', 'last_name', 'gender', 'public_info', 'nickname', 'website')
def update(self, validated_data, uid):
user = UserProfile.objects.get(id=uid)
firstname = validated_data.pop('user_details.firstname')[0]
lastname = validated_data.pop('user_details.lastname')[0]
user.user_details.firstname = firstname
user.user_details.lastname = lastname
# if avatar:
# user.user_details.avatar = avatar
# if password != '':
# user.set_password(password)
user.user_details.save()
user.save()
return user
And in template I change the '' with this:
<form action="{% url 'show_profile' pk=user.id %}" method="PUT" enctype="multipart/form-data">
I don't know how to make to work?How can I do it?Thank you!
The problem is in <form action="{% url 'show_profile' pk=user.id %}" method="PUT" enctype="multipart/form-data">. There is no method PUT in html tag form. You have to use javascript to send such request.
P.S. it is possible to send put-like request using form, but it will look ugly and it wont be REST

Categories