获取Django的作者(用户)

时间:2013-04-11 05:14:35

标签: django django-models django-forms django-authentication authentication

我正在尝试使用ModelForms创建一个新闻发布应用程序,目前我正在设置它以便表单自动获取经过身份验证的用户,因此当所述用户发布新闻项目时,他们的名称将显示,如“发布者:用户“。在models.py文件中,我尝试过使用:models.ForeignKey(User),但它不会自动设置用户,而是会在表单中显示一个下拉窗口小部件。它无法正常工作。

我如何实现我正在尝试做的事情,如前所述:

  1. 获取发布表单的经过身份验证的用户
  2. 在包含新闻项目的页面上发布他的名字
  3. 根据要求发布代码:

    Models.py:

    from django.db import models
    from django.forms import ModelForm
    from django.contrib.auth.models import User
    
    # Create your models here.
    
    class NewsItem(models.Model):
        user = models.ForeignKey(User)
        date = models.DateField()
        news = models.TextField(max_length=100000)
    
        def __unicode__(self):
            return u'%s %s %s' % (self.user, self.date, self.news)
    
    class NewsForm(ModelForm):
        class Meta:
            model = NewsItem
    

    Views.py:

    from news.models import NewsForm
    from django.forms import forms
    from django.shortcuts import render
    from django.http import HttpResponseRedirect
    
    def news_poster(request):
        if request.method == 'POST':
            form = NewsForm(request.POST)
    
            if form.is_valid():
                form.save()
            return HttpResponseRedirect('/')
        else:
            form = NewsForm()
        return render(request,'news_post.html', {'form': form})
    

    模板:

    {% extends "base.html" %}
    {% block title %}News poster {% endblock %}
    {% block content %}
        <form action="/news/" method="POST">{% csrf_token %}
        {{ form.as_p}}
        <input type="submit" value="Submit" />
        </form>
    {% endblock %}
    

2 个答案:

答案 0 :(得分:4)

您可以使用instance来传递用户

from news.models import NewsForm, NewsItem
from django.shortcuts import render
from django.http import HttpResponseRedirect

def news_poster(request):
    if request.method == 'POST':
        item = NewsItem(user=request.user)
        form = NewsForm(request.POST, instance=item)
        if form.is_valid():
            form.save()
        return HttpResponseRedirect('/')
    else:
        form = NewsForm()
    return render(request,'news_post.html', {'form': form})

答案 1 :(得分:2)

模型

ForeignKey添加到User

class NewsItem(models.Model):
    user = models.ForeignKey(User)
    date = models.DateField()
    news = models.TextField(max_length=100000)

表单

user中排除NewPostForm字段,以便它不会显示为选择。

class NewPostForm(forms.ModelForm):
    class Meta:
        model = NewsItem
        exclude = ('user',)

浏览

在保存NewPostForm之前,请添加用户:

if form.is_valid():
    news_item = form.save(commit = False)
    news_item.user = request.user  # User posting the form
    news_item.save()