使模型属于django中的用户

时间:2014-02-19 04:54:41

标签: python django authentication

我正在使用django.contrib.auth,我想知道如何让一个模型的实例“属于”特定用户。我是否需要在模型中定义指向用户的外键?我希望用户自己保留他们的CRUD。

# The objects created from this model should belong 
# to the user who created them and should not be 
# viewable by other users of the website.

from django.contrib.auth.models import User

class Classroom(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=30)
    def __unicode__ (self):
        return self.name

感谢。

2 个答案:

答案 0 :(得分:2)

如果您希望多个对象属于该用户,则User对象的foreign key field将起作用。注意,您仍然可以使用外键,并通过传递一个实例 字段定义的unique属性。


如果一个对象(且只有一个)属于用户,请使用one to one field。可以从模型的任一侧访问一对一字段

您可以使用user.classroomclassroom.user,这些绑定可以使用一对一字段定义的related_name属性进行更改。

答案 1 :(得分:2)

这是我采取的一般方法:

创建属于用户的模型

  1. 在模型上,为用户提供外键。
  2. 定义一个自定义ModelForm,要求将用户传递给构造函数(__init__())。此外,覆盖表单的save()方法,以便传递给构造函数的用户在保存之前添加到模型实例中。
  3. 定义基于CreateView等基于类的视图,该视图覆盖get_form_kwargs方法以传递用户存储在请求中的表单。
  4. 以下是代码:

    # models.py
    
    from django.db import models
    from django.contrib.auth.models import User
    
    
    class MyModel(models.Model):
        "A model that belongs to a user."
    
        user = models.ForeignKey(User)
    
    # forms.py
    
    from django import forms
    from .models import MyModel
    
    class MyModelForm(forms.ModelForm):
        """A form for creating/updating MyModels that accepts
        the user as a kwarg.
        """
    
        def __init__(self, *args, **kwargs):
            self.user = kwargs.pop('user')
            super(MyModelForm, self).__init__(*args, **kwargs)
    
        def save(self, *args, **kwargs):
            self.instance.user = self.user
            return super(MyModelForm, self).save(*args, **kwargs)
    
        class Meta:
            model = MyModel
            # Don't show the user on the form
            exclude = ('user',)
    
    # views.py
    
    from django.views.generic import CreateView
    from .models import MyModel
    from .forms import MyModelForm
    
    
    class MyModelCreateView(CreateView):
        "View for creating a MyModel belonging to the current user."
        model = MyModel
        form_class = MyModelForm
    
        def get_form_kwargs(self, *args, **kwargs):
            form_kwargs = super(MyModelCreateView,
                            self).get_form_kwargs(*args, **kwargs)
            # Pass the current user to the form constructor
            form_kwargs['user'] = self.request.user
            return form_kwargs
    

    列出属于用户的模型

    这更直接 - 您扩展ListView并过滤当前用户的查询集。 (Read more about ListView.

    编辑属于用户的模型

    MyModelCreateView使用类似的方法,但改为扩展UpdateView。这里重要的是检查用户是否有权编辑:

    # views.py
    from django.views.generic import UpdateView
    from django.core.exceptions import PermissionDenied
    ...
    
    class MyModelUpdateView(UpdateView):
        "View for the current user editing a MyModel."""
    
        model = MyModel
        form_class = MyModelForm
    
        def get_object(self, *args, **kwargs):
            object = super(MyModelUpdateView, self).get_object(*args, **kwargs)
            # Raise a permission denied if the current user doesn't
            # 'own' the MyModel they're trying to edit.
            if object.user != self.request.user:
                 raise PermissionDenied
    
        def get_form_kwargs(self, *args, **kwargs):
            form_kwargs = super(MyModelCreateView,
                        self).get_form_kwargs(*args, **kwargs)
            # Pass the current user to the form constructor
            form_kwargs['user'] = self.request.user
            return form_kwargs