1

我在保存带有实例的表单时遇到问题。我有一个带有外键的模型,但我想保存它 - 但表中没有出现任何内容,并且似乎没有任何错误消息。

型号为:

class AboutMe(models.Model):
    MyGender                   = models.CharField(max_length=50, choices = GENDER_CHOICES)


class Message(models.Model):
    MySubject     =  models.CharField(max_length=100)
    MyMessage     =  models.CharField(max_length=100)
    MyFromID      =  models.ForeignKey(AboutMe)

class ContactForm(ModelForm):
    class Meta:
        model = Message
        exclude = ('MyRead', 'MyDeleted', 'MySpam', 'MyDate', 'MyTime', 'MyFromID', 'MyToID')
    MyMessage = forms.CharField(widget=forms.Textarea)

def Contact(request):
        myid = request.session["AboutMe_id"]

        Sender = AboutMe.objects.get(pk=myid)
        if request.method == "POST":
            message = ContactForm(request.POST, instance=Sender)
            if message.is_valid():
                message.save(commit=False)
                #return HttpResponse(myid)
                message.MyRead = False
                message.MyDeleted = False
                message.MySpam = False
                message.MyDate = datetime.date.today()
                message.MyTime = timezone.now()
                message.MyToID = int(1)
                message.save()
                message.save_m2m()
                return redirect('/')
        else:
            message = ContactForm(request.POST, instance=Sender)
        return render(request, "contact.html", {'form': message,})

我也试过这个:

def Contact(request):
    myid = request.session["AboutMe_id"]

    Sender = AboutMe.objects.get(pk=myid)
    if request.method == "POST":
        messageForm = ContactForm(request.POST, instance=Sender)    
        if messageForm.is_valid():
            message = messageForm.save(commit=False)
            #message.save(commit=False)
            #return HttpResponse(myid)
            message.MyRead = False
            message.MyDeleted = False
            message.MySpam = False
            message.MyDate = datetime.date.today()
            message.MyTime = timezone.now()
            message.MyToID = int(1)
            message.save()
            #message.save_m2m()
            return redirect('/')
    else:
        messageForm = ContactForm( instance=Sender)
    return render(request, "contact.html", {'form': messageForm,})
4

1 回答 1

2

您将错误的实例传递给表单,因为表单是针对Message模型的,而不是您的AboutMe模型。

这是更正的版本,以及一些额外的检查:

  1. 您应该始终确保您有一个有效的会话。如果你有request.session["AboutMe_id"]并且会话已经过期,你会得到一个KeyError(因为密钥不会在会话中)。使用get字典的方法将抑制此错误。相反,如果键不存在,该方法将返回None。如果会话已过期,我们不应该继续前进 - 所以我们重定向到根。

  2. 即使会话有效 - 它可能不包含您的模型的有效值。在这种情况下,这AboutMe.objects.get(pk=myid)将引发异常。为了防止这种情况,我们将它包装在一个 try/except 块中。如果对象不存在,则表示会话中的值无效。我们删除密钥,然后将用户重定向到根目录。

  3. 最后,如果表单无效,您应该始终有一个条件;所以我也添加了该检查。

其余的变化主要是格式化。方法名称应以小写字母开头,普通名称也应如此。只有类名应该在 InitialCaps 中。

def contact(request):
    myid = request.session.get("AboutMe_id")
    if not myid:
        # session has expired
        return redirect('/')
    try:
        sender = AboutMe.objects.get(pk=myid)
    except AbouMe.DoesNotExist:
        # Invalid id in session
        del request.session['AboutMe_id']
        return redirect('/')

    messageForm = ContactForm(request.POST or {})
    if request.method == "POST":      
        if messageForm.is_valid():
            message = messageForm.save(commit=False)
            message.MyRead = False
            message.MyDeleted = False
            message.MySpam = False
            message.MyDate = datetime.date.today()
            message.MyTime = timezone.now()
            message.MyToID = 1
            message.MyFromID = sender
            message.save()
            return redirect('/')
        else:
            # form is not valid
            return render(request, "contact.html", {'form': messageForm})
     else:
         # return empty form
         return render(request, 'contact.html', {'form': messageForm}) 
于 2013-09-24T20:41:44.663 回答