0
我收到以下錯誤:的Django無法分配 「X'」: 「Y」 必須是一個「z.`
Internal Server Error: /change_chosenCharity/
ValueError at /change_chosenCharity/
Cannot assign "19L": "Profile.chosenCharity" must be a "Charity" instance.
從以下觀點:
@login_required
def change_chosenCharity(request):
if request.method == 'POST':
form = updateCharity(request.POST)
if form.is_valid():
currentUser = request.user
currentUserID = currentUser.id
chosenCharityQuery = Charity.objects.filter(id=request.POST['currentCharities'])
charity_id = chosenCharityQuery[0].id
created = Profile.objects.update_or_create(
user_id=currentUserID,
defaults={'chosenCharity': charity_id},
)
messages.success(request, 'Your chosen charity has been updated.')
return redirect(reverse('profile'))
else:
form = updateCharity()
return render(request, 'meta/changechosencharity.html', {'form': form})
的結果後從Django中顯示:
POST:
currentCharities = u'19'
19絕對是慈善事業的一個實例我有這個問題之前,總是解決它比較快...我已經尋找。在這裏,但無法找到解決我的問題。任何幫助,將不勝感激。
附加信息:
HTML表單:
<form class="form-horizontal" role="form" method="post" action="">
{% csrf_token %}
<fieldset>
<div class="form-group">
<label class="col-sm-4 control-label">{{ form.currentCharities.label }}:</label>
<div class="col-sm-8">
{{ form.currentCharities }}
<div class="text-danger">
{% for error in form.currentCharities.errors %}{{ error }}<br/>{% endfor %}
</div>
</div>
</div>
<div class="form-group">
<div class="text-right col-sm-12">
<button type="submit" class="btn btn-primary">Change Charity</button>
</div>
</div>
</fieldset>
</form>
的Django模型:
class Charity(models.Model):
name = models.CharField(max_length=50, unique=True)
website = models.URLField()
enabled = models.BooleanField(default=True)
def __unicode__(self):
return self.name
class Meta:
ordering = ['name']
verbose_name_plural = 'charities'
FORM:
class updateCharity(BootstrapForm):
currentCharities = forms.ModelChoiceField(queryset=Charity.objects.filter(enabled=1), empty_label=None,widget=forms.Select(attrs={"class": "select-format"}))
currentCharities.label = "Charity Options"
def clean(self):
cleaned_data = self.cleaned_data # individual field's clean methods have already been called
return cleaned_data