0

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

如前所述,我将如何实现我想要做的事情:

  1. 获取发布表单的经过身份验证的用户
  2. 在新闻项目的页面上张贴他的名字

根据要求发布代码:

模型.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

视图.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 %}
4

2 回答 2

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})
于 2013-04-11T05:32:44.917 回答
2

楷模

添加ForeignKeyUser

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()
于 2013-04-11T05:20:59.150 回答