我正在使用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
感谢。
答案 0 :(得分:2)
如果您希望多个对象属于该用户,则User对象的foreign key field将起作用。注意,您仍然可以使用外键,并通过传递一个实例
字段定义的unique
属性。
如果一个对象(且只有一个)属于用户,请使用one to one field。可以从模型的任一侧访问一对一字段
您可以使用user.classroom
或classroom.user
,这些绑定可以使用一对一字段定义的related_name
属性进行更改。
答案 1 :(得分:2)
这是我采取的一般方法:
创建属于用户的模型
__init__()
)。此外,覆盖表单的save()
方法,以便传递给构造函数的用户在保存之前添加到模型实例中。CreateView
等基于类的视图,该视图覆盖get_form_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
并过滤当前用户的查询集。 (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