Django不能分配" x'":" y"必须是" z

时间:2017-05-29 20:50:41

标签: python django

我收到以下错误:

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

1 个答案:

答案 0 :(得分:3)

您可以更新相关的对象实例:

charity = chosenCharityQuery[0]
created = Profile.objects.update_or_create(
            user_id=currentUserID,
            defaults={'chosenCharity': charity},
        )

或者更新相关字段的ID:

charity_id = chosenCharityQuery[0].id
created = Profile.objects.update_or_create(
            user_id=currentUserID,
            defaults={'chosenCharity_id': charity_id},
        )