问题描述
我一直在从事一个项目,在该项目中我必须指出公司员工的支出.
I have been working on a project in which I have to point out the expenses that the workers of a company have.
为此,我创建了两个模型:工作人员和费用,其中费用对工作人员具有外键:"nomTreballador".
For this I have created two models, workers and expenses, in which expenses has a foreign key to workers, in the field: "nomTreballador".
当我尝试将其保存在数据库中时,出现错误:无法分配"u'Joan Manel'":"despesa.nomTreballador"必须是"treballador"实例."
When I try to save it in the db I get the error: "Cannot assign "u'Joan Manel'": "despesa.nomTreballador" must be a "treballador" instance."
我的模型.py:
from __future__ import unicode_literals
from django.db import models
from django.core.validators import RegexValidator
KILOMETRATGE = 'KM'
DINAR = 'DIN'
AUTOPISTA = 'AP'
MANTENIMENTPC = 'PC'
GASTOS = (
(KILOMETRATGE, 'Kilometres'),
(DINAR, 'Dinar'),
(AUTOPISTA, 'Autopista peatge'),
(MANTENIMENTPC, 'Manteniment de pc')
)
NIF = 'NIF'
NIE = 'NIE'
DNI = 'DNI'
TIPUSDOC = (
(DNI, 'DNI'),
(NIF, 'NIF'),
(NIE, 'NIE')
)
class treballador(models.Model):
nom = models.CharField(max_length=150, null=False, unique=True)
cognom = models.CharField(max_length=150, null=False)
tipusDocID = models.CharField(max_length=3, choices=TIPUSDOC, null=False)
docId = models.CharField(max_length=9, null=False)
tlf_regex = RegexValidator(regex=r'^\d{9,9}$',message="Phone number must be entered in the format: '+999999999'. Up to 9 digits allowed.")
tlf = models.CharField(validators=[tlf_regex], blank=True, max_length=9) # validators should be a list
correu = models.EmailField(max_length=254)
ciutat = models.CharField(max_length=150)
dataDAlta = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return unicode(self.nom) or 'u'
class despesa(models.Model):
nomTreballador = models.ForeignKey(treballador, to_field='nom')
tipusDeGast = models.CharField(max_length=3, choices=GASTOS)
quantia = models.DecimalField(max_digits=5, decimal_places=2)
data = models.DateTimeField()
def __unicode__(self):
return unicode(self.nomTreballador) or 'u'
我的forms.py:
My forms.py:
from django import forms
from functools import partial
from .models import despesa, treballador
DateInput = partial(forms.DateInput, {'class':'datepicker'})
class desModelForm(forms.ModelForm):
data = forms.DateField(widget=DateInput(format='%d/%m/%Y'), label="Data de la despesa", input_formats=['%d/%m/%Y'])
iquery = treballador.objects.values_list('nom', flat=True).distinct()
iquery_choices = [('','None')] + [(treballador,treballador) for treballador in iquery]
nomTreballador = forms.ChoiceField(choices=iquery_choices)
class Meta:
model= despesa
fields= ["nomTreballador","tipusDeGast","quantia","data"]
def clean_despesa(self):
despeses = self.cleaned_data.get("tipusDeGast")
return despeses
def clean_date(self):
date = self.cleaned_data.get("data")
return date
def clean_quantia(self):
quantia = self.cleaned_data.get("quantia")
return quantia
def clean_nom(self):
nomTreballador = self.cleaned_data.get("nomTreballador")
return nomTreballador
我的views.py:
My views.py:
from django.shortcuts import render
from .forms import desModelForm, treballadorForm
from .models import treballador, despesa
def home(request):
form = desModelForm(request.POST or None)
context = {
"gast_form": form
}
if form.is_valid():
desp = form.save(commit=False)
desp.save()
return render(request, "imputacioDespeses.html", context)
我已经尝试过类似问题的解决方案,但是我没有解决
I've tried solutions of similar questions but I have not managed to solve it
谢谢!
推荐答案
出现此错误的原因是,当您传递一个文本字符串用作 nomTreballador
外键时, treballador
实例.
You are getting this error because you are passing a text string to be used as the nomTreballador
foreign key, while you should be passing a treballador
instance.
您似乎正在尝试通过使用 forms.ChoiceField
将可用选项限制为一组不同的 trebellador
,但这是一种更好的方法使用ModelForm来更改 nomTreballador
字段的 queryset
属性.您可以通过表单的 init
方法执行此操作:
It looks like you're trying to restrict the available choices to a set of distinct trebellador
s by using a forms.ChoiceField
, but a better way to do this with a ModelForm is to change the queryset
attribute of the nomTreballador
field. You do this in the form's init
method:
self.fields ['nomTreballador'].queryset = treballador.objects.all().distinct()
此外,您还应该检查已实现的 clean
方法,因为并非所有方法都映射到现有字段.
Also you should check the clean
methods you've implemented because not all of them map to an existing field.
这篇关于django-无法分配"u'Joan Manel'":"despesa.nomTreballador"必须是"treballador"实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!