Django没有将ModelChoiceField保存到base

时间:2016-04-16 19:07:54

标签: django

这是我的模特:

class User(models.Model):
    name = models.CharField(max_length=50)
    mail = models.CharField(max_length=50)
    nickname = models.CharField(max_length=50)
    def __str__ (self):
        return self.name

class Post(models.Model):

    title = models.CharField(max_length=200)
    lead = models.CharField(max_length=10, default='default')
    text = models.TextField()
    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(
            blank=True, null=True)  
    user = models.ForeignKey(User, related_name="User", null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

这是我的观点:

def post_new(request):
if request.method == "POST":
    form = PostForm(request.POST)
    if form.is_valid():
        post = form.save(commit=False)
        post.published_date = timezone.now()
        post.save()
        return redirect('post_detail', pk=post.pk)
else:
    form = PostForm()
return render(request, 'post_new.html', {'form': form})

这是我的forms.py:

class PostForm(forms.ModelForm):
selectuser = forms.ModelChoiceField(queryset=User.objects.all())
class Meta:
    model = Post
    fields = ('title','lead', 'text',)      

class UserForm(forms.ModelForm):

class Meta:
    model = User
    fields = ('name','nickname','mail')

我的问题是ModelChoiceField中的选定值是保存到base而没有值只是空字段。你可以帮我解决这个问题吗?

  

我的问题是ModelChoiceField中的选定值正在保存   base没有值只是空字段。你可以帮我解决这个问题   问题

1 个答案:

答案 0 :(得分:1)

模型字段为Post.user,但您的表单字段为PostForm.selectuser。尝试使用user中的PostForm

class PostForm(forms.ModelForm):
    user = forms.ModelChoiceField(queryset=User.objects.all())
    ...