我在保存带有实例的表单时遇到问题。我有一个带有外键的模型,但我想保存它 - 但表中没有出现任何内容,并且似乎没有任何错误消息。
型号为:
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,})