Python 使模型属于django中的用户

Python 使模型属于django中的用户,python,django,authentication,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.a

我正在使用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

谢谢。

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


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


您可以使用
user.school
school.user
,这些绑定可以使用一对一字段定义的
相关\u name
属性进行更改。

这是我通常采用的方法:

创建属于用户的模型

  • 在模型上,为用户提供一个外键
  • 定义需要将用户传递给构造函数的自定义模型表单(
    \uuuu init\uuuu()
    )。另外,重写表单的
    save()
    方法,以便在保存之前将传递给构造函数的用户添加到模型实例中
  • 基于etc定义基于类的视图,该视图覆盖
    get\u form\u kwargs
    方法,以传递用户存储在请求中的表单
  • 代码如下:

    # 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
    并按当前用户过滤查询集。()

    编辑属于用户的模型

    使用与MyModelCreateView类似的方法,但要扩展。此处重要的一点是检查用户是否具有编辑权限:

    # 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
    

    模型还是模型的实例?模型等价于表,模型实例等价于行。请澄清您的问题。“根据此模型创建的对象”=>实例,对吗?因此,在视图中查找属于用户的对象足以防止用户看到错误的对象?@broinjc No,您需要自己处理。@BurhanKhalid那么我该如何处理呢?@broinjc在视图中使用类似于
    的东西来处理它,例如,如果教室.user==request.user:…
    ,并且在教室创建表单中,我会隐藏用户foreignkey字段并用当前用户自动填充它?