我有一个应用程序,用户可以创建一个类别页面。我想将其修改为用户只能创建一个。该页面将显示在个人资料页面中。我正在使用userena作为用户配置文件系统。 事情是我不知道如何限制用户只创建一个类别页面。以及如何保存该页面,以便创建者可以进行某些访问(如编辑/删除)
这是我的views.py:
@login_required
def add_category(request):
if request.method == 'POST':
form = CategoryForm(request.POST)
if form.is_valid():
form.save(commit=True)
return index(request)
else:
form = CategoryForm()
return render(request, 'main/add_category.html', {'form':form})
我可以创建编辑/删除视图,但不确定如何让用户只创建一个页面。
Models.py
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
slug = models.CharField(max_length=100, unique=True)
def save(self, *args, **kwargs):
self.slug = uuslug(self.name,instance=self, max_length=100)
super(Category, self).save(*args, **kwargs)
def __unicode__(self):
return self.name
def get_absolute_url(self):
return 'category/%s' % (self.slug)
forms.py
class CategoryForm(forms.ModelForm):
name = forms.CharField(max_length=128, help_text="plz enter")
likes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
slug = forms.CharField(widget=forms.HiddenInput, required=False)
class Meta:
model = Category
fields =('name',)
编辑:
{{post.category}}
答案 0 :(得分:0)
您希望每个用户最多创建一个类别。因此,首先,您需要知道用户是否已创建类别。
有很多方法可以做到这一点,我建议您在模型中添加author
字段:
from django.conf import settings class Category(models.Model): name = models.CharField(max_length=128, unique=True) slug = models.CharField(max_length=100, unique=True) # Here I've chosen to use a ForeignKey, # but you can also use a OneToOneField. author = models.ForeignKey(settings.AUTH_USER_MODEL, unique=True) ...
添加字段后,请记得generate and run the migrations:
$ python manage.py makemigrations
$ python manage.py migrate
这个新的author
字段应自动设置,不得出现在您的表单中。鉴于您已使用fields = ['name']
(并且未使用exclude
),则无需修改CategoryForm
。
现在你必须修改你的视图,以便做两件事:
author
字段; Category
。@login_required def add_category(request): if Category.objects.filter(author=request.user).exists(): # This user has already created another category. # Show him an error message, or redirect him to another page. return ... if request.method == 'POST': category = Category(author=request.user) form = CategoryForm(request.POST, instance=category) if form.is_valid(): form.save(commit=True) return index(request) else: form = CategoryForm() return render(request, 'main/add_category.html', {'form':form})