OneToOneField也不相关

时间:2017-12-23 13:16:41

标签: django django-models django-forms

再次这个我。我的代码有些麻烦。我从ModelForm制作了一个具有8个属性的模型的表单,但我想用户只填写其中一个,一个来自系统。用户填写的那个是好的,但填充系统的那个没有用。

  

models.py

class SeminarProposal(md.Model):
    # diisi oleh mahasiswa
    fileProposal = models.FileField()

    # This is the one is filled with system
    proposal = models.OneToOneField(Proposal,
                                    on_delete=models.CASCADE,
                                    related_name="propSid",
                                    unique=True, blank=True, null=True)
    masabimbingan = models.BooleanField(default=True)

    # disi oleh admin
    tanggal = models.DateField(default=timezone.now, blank=True,null=True)
    tempat = models.CharField(max_length=30, blank=True, null=True)

    # diisi oleh dosen pembimbing
    dospemsetuju = models.BooleanField(default=False, blank=True)

    # diisi oleh kaprodi
    penguji1 = models.ForeignKey(Dosen,
                                 on_delete=models.CASCADE,
                                 related_name="penguji1",
                                 blank=True, null=True)
    penguji2 = models.ForeignKey(Dosen,
                                 on_delete=models.CASCADE,
                                 related_name="penguji2",
                                 blank=True, null=True)


    def __str__(self):
        return "Sidang untuk " + self.proposal.judul
  

view.py

def daftarSeminar(request):
    if request.method == 'POST':
        form = FormSeminar(request.POST, request.FILES)
        print(request.user)
        if form.is_valid():
            form.save(commit=False)
            form.cleaned_data['proposal']
            print(request.user)
            prop = Proposal.objects.get(akun=request.user)
            form.proposal = prop
            print(form.proposal) #to confirm that this is not None
            form.save()
            return redirect('proposal:bimbingan')
        else:
            return render(request, 'sidprop.html' , {'oke': 'oke'})
        return redirect('proposal:index')
  

form.py

class FormSeminar(forms.ModelForm):

    class Meta:
        model = SeminarProposal
        fields = ['fileProposal','proposal']

提前致谢。 Terimakasih。

1 个答案:

答案 0 :(得分:0)

不是更改表单数据,而是从表单中获取对象并更改对象的数据:

if form.is_valid():
    obj = form.save(commit=False)
    prop = Proposal.objects.get(akun=request.user)
    obj.proposal = prop
    obj.save()
    return redirect('proposal:bimbingan')