django - Django - 此表单中“无法设置属性”错误的原因是什么?
问题描述
在我的 Django 项目中,当加载如下所示的 CreateView 时,我在运行时收到“无法设置属性”错误:
class DonationCreateView(InventoryEditingPermissionMixin, CreateView):
model = Donation
template_name = 'inventories/donation/donation_form.html'
form_class = DonationForm
success_url = reverse_lazy('donations_list')
success_message = 'Donación creada correctamente'
def form_valid(self, form):
obj = form.save()
amount = obj.amount
autotank = obj.auto_tank
tank = SaleWarehouseTank.objects.filter(
warehouse__id=autotank.pk).last()
tank.current_level -= amount
tank.save(update_fields=['current_level'])
self.object = obj
return HttpResponseRedirect(self.get_success_url())
def get_context_data(self, **kwargs):
context = super(DonationCreateView, self).get_context_data(**kwargs)
context['autotanks'] = SaleWarehouse.objects.filter(type=0)
context['user_type'] = self.request.user.user_type
context['clients'] = Client.objects.all()
context['initial_client_name'] = ''
context['is_update'] = False
return context
def get_form_kwargs(self):
form_kwargs = super(DonationCreateView, self).get_form_kwargs()
form_kwargs['user'] = self.request.user
return form_kwargs
“捐赠表格”看起来像这样:
class DonationForm(forms.ModelForm):
client_name = forms.CharField(required=False, label='Cliente')
region = forms.ModelChoiceField(queryset=Region.objects.all(), required=False, label='Región')
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
self.user_type = user.user_type
super(DonationForm, self).__init__(*args, **kwargs)
self.fields['auto_tank'].required = False
self.fields['client'].required = False
self.fields['client'].widget = forms.HiddenInput()
if user.user_type == 'region_admin':
self.fields['auto_tank'].queryset = SaleWarehouse.objects.filter(type=0, region__id=user.region_id)
elif user.user_type == 'admin':
self.fields['auto_tank'].queryset = SaleWarehouse.objects.filter(type=0)
def clean(self):
cleaned_data = self.cleaned_data
client_name = cleaned_data['client_name']
if client_name.strip() == '':
cleaned_data['client'] = None
else:
if Client.objects.filter(social_reason__icontains=client_name).count() > 0:
cleaned_data['client'] = Client.objects.filter(social_reason__icontains=client_name).last()
else:
raise forms.ValidationError('Por favor, elige un cliente de la lista, o deja el espacio en blanco')
region = cleaned_data['region']
auto_tank = cleaned_data['auto_tank']
if self.user_type == 'admin':
if str(region) in ['', 'None']:
self._errors['region'] = self.error_class(['Por favor, selecciona una región.'])
else:
if str(auto_tank) in ['', 'None']:
self._errors['auto_tank'] = self.error_class(['Por favor, selecciona un autotanque.'])
elif self.user_type == 'region_admin':
if str(auto_tank) in ['', 'None']:
self._errors['auto_tank'] = self.error_class(['Por favor, selecciona un autotanque'])
return cleaned_data
class Meta:
model = Donation
fields = ('region', 'auto_tank', 'client', 'client_name', 'amount', 'admin_confirm', 'observations')
当我加载 CreateView 时,为什么会在运行时触发此错误?我应该查看哪些其他信息来找出错误的原因?
解决方案
我发现了问题,它既不在Form也不在View上,而是在我的模型上。我的模型看起来像这样:
class Donation(Expense):
client = models.ForeignKey(Client, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Cliente')
date_time = models.DateTimeField(verbose_name='Fecha y hora', auto_now_add=True)
auto_tank = models.ForeignKey(SaleWarehouse,
on_delete=models.SET_NULL, null=True, blank=False, verbose_name='Autotanque') admin_confirm = models.BooleanField(verbose_name="Gasto autorizado", default=False, blank=True)
它继承的模型“费用”有这个:
class Expense(models.Model):
amount = models.FloatField(verbose_name='Cantidad', null=False, blank=False, validators=[MinValueValidator(0.0), MaxValueValidator(300000.0)])
time = models.TimeField(verbose_name='Hora', auto_now_add=True)
date = models.DateField(verbose_name='Tiempo', auto_now_add=True)
observations = models.CharField(verbose_name='Observaciones', null=True, blank=True, max_length=200)
@property
def date_time(self):
return datetime.datetime.combine(date=self.date, time=self.time)
Donation 中的“date_time”字段与 Expense 中的“date_time”属性发生冲突。从 Expense 类中删除该属性解决了该问题。
推荐阅读
- python - 我的 __init__ 中的 for 循环没有按预期工作
- node.js - 在单独的文件中续集关联
- python - 是否可以从模块中导入变量以与 Selenium 一起使用?
- python-2.7 - 如何拆分代码以便在两台计算机上运行
- apache-flink - Apache Flink Tumbling Window 延迟结果
- javascript - Styled-components:如何引用相同的组件但具有不同的道具?
- java - 如何在水平标签滚动上制作固定横幅?
- wordpress - wordpress 多语言 slug 翻译
- machine-learning - IBM Watson NLC - 使用超过 20,000 个文本示例进行培训?
- django - 根据管理站点中的用户输入批量更新模型字段