Django用户外键在View和model.save()方法中

时间:2015-10-31 16:59:09

标签: python django django-models django-views

我有以下模型(简化):

class Candidate(models.Model):
    """ Model for candidate clients """

    # fields
    general_category = models.ForeignKey('GeneralCategory',
                                         related_name='candidate',
                                         null=True,
                                         blank=True,
                                         # default=1,
                                         verbose_name='Γενική Κατηγορία',)

    brand_name = models.CharField(max_length=160,
                                  blank=True,
                                  verbose_name='Επωνυμία')

    creation_date = models.DateTimeField(null=True, blank=True, verbose_name='Πρώτη καταχώρηση')
    last_edited = models.DateTimeField(null=True, blank=True, verbose_name='Τελευταία επεξεργασία')

    first_edited_by = models.ForeignKey(User,
                                        related_name='first_edited_candidates',
                                        blank=True,
                                        null=True,
                                        verbose_name='Πρώτη επεξεργασία από',)

    last_edited_by = models.ForeignKey(User,
                                       related_name='last_edited_candidates',
                                       blank=True,
                                       null=True,
                                       verbose_name='Τελευταία επεξεργασία από',)

    def save(self, *args, **kwargs):
        """ On save, update timestamps and user fields """
        if 'request' in kwargs:
            request = kwargs.pop('request')
        else:
            request = None

        if not self.id:
            self.creation_date = timezone.now()
        self.last_edited = timezone.now()

        if request is not None:
            if not self.first_edited_by:
                self.first_edited_by = request.user
            self.last_edited_by = request.user

        log.info(self)
        return super(Candidate, self).save(*args, **kwargs)

    def __str__(self):
        return self.brand_name + '[' + str(self.__dict__) + ']'

如果我在PyCharm中启动调试器,我可以看到在我的详细视图中按预期填充了两个User外键,但在model.save()方法中它们是None。另一个外键(general_category)按预期填充。

为什么?是否与self关键字有关?

我的观点(再次,简化)是:

@login_required
@require_http_methods(["GET", "POST"])
def candidate_detail(request, candidate_id):
    candidate = get_object_or_404(Candidate, pk=candidate_id)
    original_http_referrer = request.GET.get('next')
    if request.method == 'GET':
        form = CandidateForm(instance=candidate)
    elif request.method == 'POST':
        form = CandidateForm(request.POST, instance=candidate)
        if form.is_valid():
            candidate.save(request=request)
            return HttpResponseRedirect(original_http_referrer)
        # else:
            # TODO: show some error message ?

    context = {'candidate': candidate,
               'form': form,
               'original_http_referrer': original_http_referrer}
    return render(request, 'candidates/candidate_detail.html', context)

我正在使用 Django 1.8 Python 3.4

更新:似乎外键的值在行

中丢失
form = CandidateForm(request.POST, instance=candidate)

奇怪的是,如果我逐步调试并逐行调试,我的程序最终会按预期工作! (我也尝试使用manage.py runserver来确保它不是PyCharm服务器实现中的错误而且不是)

我会尝试在明天的每一步都记录我的模型,以缩小有问题的代码。只是为了确保,这是我的表单代码(未简化):

from django.forms import ModelForm
from candidates.models import Candidate


class CandidateForm(ModelForm):
    class Meta:
        model = Candidate
        fields = '__all__'

1 个答案:

答案 0 :(得分:0)

您没有保存表单。

    if form.is_valid():
        candidate = form.save(commit=False)
        candidate.save(request=request)

请注意,save方法的前四行可以简化为一行:

request = kwargs.pop('request', None)