如何从Django身份验证表单中获取价值并将该值用作另一个表单的输入?

时间:2015-02-18 16:09:24

标签: python django forms python-2.7 forms-authentication

我有一个用于在博客中创建新帖子的表单,该表单中的一个字段是所有者,这意味着谁发布了它,但是当用户提供他/她的登录时应该从登录视图中获取信息我不希望用户从列表中选择谁是所有者,它应该自动填充并用他的用户名修复。我尝试了不同的方法,修复了我的forms.py上的值,但没有工作,它无法识别变量。这是我的forms.py:

class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())

    class Meta:
        model = User
        fields = ('username', 'email', 'password')

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('website', 'picture')


class CreatePostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('title', 'body','datposted', 'category','owner')

以下是我对模特的看法:

class Post(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()
    datposted = models.DateTimeField('date posted')
    category = models.ForeignKey('Category')
    owner = models.ForeignKey('UserProfile')
    def __str__(self):
        return '%s' % self.title

这是我的观点:

def create_post(request):
if request.method == 'POST':
    form = CreatePostForm(request.POST)

    if form.is_valid():
        post = form.save(commit=False)
        post.datposted = datetime.datetime.now()
        #post.owner = request.user()
        post.save()
        return HttpResponseRedirect('/posts/')
    else:
        return HttpResponse("Favor. Verifique os campos necessarios")

else:
    form = CreatePostForm()
    f = {'form' : form}
    return render(request,'create_post.html',f)

您能否提供更多详细信息?

1 个答案:

答案 0 :(得分:0)

我认为您只需要删除所有者'表单中的字段,并确保您处理在视图中填充所有者

class CreatePostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('title', 'body','datposted', 'category')

视图

def create_post(request):
    if request.method == 'POST':
        form = CreatePostForm(request.POST)

        if form.is_valid():
            Posts = form.save(commit=False) 
            # replace below with however you get user profile
            Posts.owner = get_user_profile_from_logged_in_user()
            Posts.save()
            return HttpResponseRedirect('/posts/')
        else:
            return HttpResponse("Favor. Verifique os campos necessarios")

    else:
        form = CreatePostForm()
        f = {'form' : form}
        return render(request,'create_post.html',f)

这个案例在django docs中有所介绍: https://docs.djangoproject.com/en/1.7/topics/forms/modelforms/#the-save-method