Обновление или сохранение поля формы с помощью clean_data в Django не работает
Это просто, но я не знаю, почему это не работает! Я просто хочу установить в поле TOTAL из формы значение PRE-TOTAL. Это обновляет мою FORM_DATA (экземпляр, использующий clean_data), но не сохраняет! Он все еще приходит со значением по умолчанию!!! Кто-нибудь скажет мне, почему?
Вот коды:
MODELS.PY
from django.db import models
from django.utils import timezone
class av_pomades(models.Model):
cod_prod = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100)
price = models.FloatField(default=0)
pic = models.ImageField(default='default.jpg', blank=True)
def __str__(self):
return self.name
pomades_to_chose = (
('Suavecito - water based','Suavecito - water based'),
('Reuzel Blue - water based','Reuzel Blue - water based'),
('Layrite - water based','Layrite - water based'),
('Suavecito - oil based','Suavecito - oil based'),
('Reuzel Pink - Oil Based','Reuzel Pink - Oil Based'),
('Layrite - oil based','Layrite - oil based')
)
class order_form(models.Model):
pomade = models.CharField(max_length=100, choices=pomades_to_chose)
amount = models.PositiveIntegerField()
ord_date = models.DateField(default=timezone.now)
total = models.FloatField(default=0)
def __str__(self):
return self.pomade
FORMS.PY
from dataclasses import fields
from tabnanny import verbose
from django import forms
from . import models
class order_forms(forms.ModelForm):
class Meta:
# model that the fields will come from
model = models.order_form
# chosing the fields to be displayed
fields = ['pomade', 'amount', 'total']
VIEWS.PY
from django.shortcuts import render, redirect
from .models import av_pomades, order_form
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from . import forms
@login_required(login_url='accounts:login')
def purchase(request):
if request.method == 'POST':
form = forms.order_forms(request.POST)
if form.is_valid():
# creating a cleanned data instace
form_data = form.cleaned_data
ch_pomade = str(form_data['pomade'])
# retrieving the right price from the selected product
pomades_prices = av_pomades.objects.all().values('name','price')
for pomades_data in pomades_prices:
if ch_pomade in pomades_data['name']:
ch_pomade_price = pomades_data['price']
# setting the total price
famount = int(form_data['amount'])
pre_total = ch_pomade_price * famount
# updating the price in the for to be recorded in DB
**# HERE IS THE PROBLEMATIC PART I GUESS**
form_data['total'] = pre_total
print(form_data)
form.save()
return redirect('products:order_success')
else:
form = forms.order_forms()
return render(request,'basquet.html', {'order_form':form})
Просмотрите ответы в этом вопросе Как передать переменную по ссылке? , чтобы понять специфику того, с чем вы столкнулись.
В вашем случае вы обновляете не данные формы, а переменную, которая является независимой копией данных формы
WRONG
form_data['total'] = pre_total
ПРАВИЛЬНО
form.cleaned_data['total'] = pre_total