Django用户外键在View vs中,在model.save()方法中 [英] Django User foreign key in View vs in model.save() method

查看:102
本文介绍了Django用户外键在View vs中,在model.save()方法中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下模型(简化):

I have the following model (simplified):

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中启动调试器,我可以看到两个用户外键在我的详细视图中按预期填充,但在 model.save()方法是。另一个外键( general_category )按预期填充。

If I fire up the debugger in PyCharm I can see that the two User foreign keys are populated as expected in my detail view, but inside the model.save() method they are None. The other foreign key (general_category) is populated as expected.

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

Why is that? Does it have something to do with the self keyword?

我的观点(再次简化)是这样的: / p>

My view (again, simplified) is this:

@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 em> Python 3.4 。

I'm using Django 1.8 with Python 3.4.

更新:外键的价值似乎丢失了

UPDATE: It seems that the value of the foreign keys is lost in the line

form = CandidateForm(request.POST, instance=candidate)

奇怪的是,如果我和调试器一步一步地走下去,我的程序最终会按预期工作! (我也尝试使用 manage.py runserver ,以确保它不是PyCharm的服务器实现中的错误,而不是)

The weird thing is that, if I step-in and go line-by-line with the debugger, my program ends up working as expected! (I have also tried this using manage.py runserver to make sure it is not a bug in the PyCharm's server implementation and it's not)

我将在明天的每一步尝试登录我的模型,以缩小违规代码。只是为了确保,这里是我的表单的代码(不是简化):

I'll try logging my model at each step tomorrow to narrow down the offending code. Just to make sure, here is my form's code (not simplified):

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


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


推荐答案

您没有保存表单。

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

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

Note that the first four lines of the save method can be simplified to one:

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

这篇关于Django用户外键在View vs中,在model.save()方法中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆