将提交表单的用户存储到同一个表中?

时间:2016-10-28 21:28:16

标签: django forms models

我正在寻找最合适的方法来存储负责表单提交的用户名,以便我可以轻松地组织他们通过用户名提交的表单,例如每个用户的“帐户设置”。

我已经搜索过,但解决方案非常分散,所有关于此的帖子都涉及旧版本以及每个Django版本中更改的最佳解决方案。我仍然在学习Django的基础知识,这可能没有用。

这是我的views.py:

def add(request):
    title = 'Add Reddit Account'
    # ADD FORM
    form = AddRedditForm(request.POST or None)
    instance = form.save(commit=False)
    instance.user = request.user
    instance.save()
    if request.method == "POST":
        print(request.POST)

    context = {
        "form": form,
        "title": title,
        "user": instance.user
    }
    return render(request, "addreddit/add.html", context)

和我的models.py:

from django.db import models

class Account(models.Model):
    user_name = models.CharField(max_length=20)
    password = models.CharField(max_length=18)
    secret = models.CharField(max_length=100)
    tag = models.CharField(max_length=20, blank=True)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    user = models.ForeignKey('auth.User', null=True)

    def __str__(self): #Python 3.3 is __str__
        return str(self.user)
        return self.user_name
        return self.password
        return self.secret
        return self.tag
        return self.timestamp

最后,forms.py如果相关:

from django import forms
from .models import Account

class AddRedditForm(forms.ModelForm):
    class Meta:
        model = Account
        fields = ['user_name','password','secret','tag']
    user_name = forms.CharField(required=True)
    password = forms.CharField(widget=forms.PasswordInput,required=True)
    secret = forms.CharField(required=True)
    tag = forms.CharField(required=False)

这似乎工作得非常好,除了表单中保存的事物是用户,而不是其他信息。

建议编辑:

from django.conf import settings
from django.core.mail import send_mail
from django.shortcuts import render, redirect
from .forms import AddRedditForm


# Create your views here.
def add(request):
    title = 'Add Reddit Account'
    # ADD FORM
    if request.method == "POST":
        form = AddRedditForm(request.POST or None)
        print(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.user = request.user
            instance.save()
            return redirect('addreddit/add') 

    context = {
        "title": title,
        "user": request.user,  # not available if you haven't submitted the form
        "form": form
        }
return render(request, "addreddit/add.html", context)

2 个答案:

答案 0 :(得分:0)

ModelForm不要求您重新定义字段。我会重写你的forms.py来反映这个事实。

class AddRedditForm(forms.ModelForm):
    class Meta:
        model = Account
        fields = ['user_name','password','secret','tag']

答案 1 :(得分:0)

即使请求方法不是POST,您也会在该视图中做很多事情来保存表单数据。在这种情况下,当您发出GET请求时,正在保存表单实例,仅填充.user字段。您还没有验证表单,这是一个有用的Django内置操作。试试这个:

def add(request):
    title = 'Add Reddit Account'

    if request.method == 'POST':
        form = AddRedditForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.user = request.user
            instance.save()
            return redirect('addreddit/add')  # or whatever named URL this is
    else:
        form = AddRedditForm()

    context = {
        "form": form,
        "title": title,
        "user": instance.user  # not available if you haven't submitted the form
    }
    return render(request, "addreddit/add.html", context)

在GET请求中,instance.user会出现名称错误。我认为它只是用于调试。否则,您仍然可以访问request.user

我建议的另一个修正是POST后重定向,以便刷新页面不会意外重新提交表单。通过导入获取此信息:

from django.shortcuts import redirect