1


我是 django 的新手,我被要求将当前登录的用户与用户创建的上下文(我的模型类)相关联。
如何/在哪里检索用户(来自request.user)对象?如何在模型中设置? 是否可以使用通用视图传递request.user给视图?

这是我的上下文类:

from django.contrib.auth.models import User

class Context(models.Model):
    title = models.CharField(max_length=32)
    description = models.TextField()
    user = models.ForeignKey(User,null=False)

这是表格:

class ContextForm(ModelForm):

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_method = 'post'        
        self.helper.add_input(Submit('submit', 'Submit'))
        super(ContextForm, self).__init__(*args, **kwargs)

    class Meta:
        model = Context
        exclude = ('user')

来自 urls.py 的网址:

url(r'^create/$', CreateView.as_view(model=Context, form_class=ContextForm),name='context_create'),

最后,context_form.html 格式清晰

{% load crispy_forms_tags %}
{% block content %}
  {% crispy form %}
{% endblock %}

预先感谢您的任何帮助。

4

2 回答 2

1

查看django-braces!它有一个表单 mixin,可以从 kwargs 中弹出当前用户。还有一个基于类的视图的混合,它将用户传递给表单。如果你正在做基于类的视图,只需使用 forms.py 和 views.py 中提供的 mixins,并覆盖 save() 方法。

表格.py:

from braces.forms import UserKwargModelFormMixin

class ContextForm(UserKwargModelFormMixin, ModelForm):

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_method = 'post'        
        self.helper.add_input(Submit('submit', 'Submit'))
        super(ContextForm, self).__init__(*args, **kwargs)

    class Meta:
        model = Context
        fields = ('title', 'description',)

    def save(self, force_insert=False, force_update=False, commit=True):
        obj = super(ContextForm, self).save(commit=False)
        obj.user = self.user
        if commit:
            obj.save()
        return obj

视图.py

from braces.views import UserFormKwargsMixin

class CreateContextView(UserFormKwargsMixin, CreateView)

    model = Context
    form_class = ContextForm

网址.py:

url(r'^create/$', CreateContextView.as_view(),name='context_create'),

您也可以像这样实现它:

表格.py:

class ContextForm(ModelForm):

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop("user", None)
        self.helper = FormHelper()
        self.helper.form_method = 'post'        
        self.helper.add_input(Submit('submit', 'Submit'))
        super(ContextForm, self).__init__(*args, **kwargs)

    class Meta:
        model = Context
        fields = ('title', 'description',)

    def save(self, force_insert=False, force_update=False, commit=True):
        obj = super(ContextForm, self).save(commit=False)
        obj.user = self.user
        if commit:
            obj.save()
        return obj

视图.py

def some_view(request):
    ...
    form = ContextForm(request.POST, user=request.user)
    ...
于 2013-02-01T16:35:05.677 回答
0

在您的模型中:

from django.contrib.auth.models import User

class Context(models.Model):
    title = models.CharField(max_length=32)
    description = models.TextField()
    user = models.OneToOneField(User)

在与用户关联的视图中:

    if request.method == 'POST':
            form = ContextForm(request.POST)
            if form.is_valid():
                    user = User.objects.create_user(username=form.cleaned_data['username'], email = form.cleaned_data['email'], password = form.cleaned_data['password'])
                    user.save()

                    obj = Context(user=user, title=form.cleaned_data['title'], description=form.cleaned_data['description'])
                    obj.save()

如果您需要登录,只需添加 @login_required

@login_required
def myfunction(request): 
     ...

看看这个教程

编辑

我已经看到您编辑的问题,您需要将其添加到您的 urls.py

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.core.context_processors.request',
)

这意味着它将被传递给使用 RequestContext 呈现的所有模板,所有通用视图都是如此。

于 2013-02-01T16:32:46.127 回答