0

我试图将用户在输入新“提要”时可用的“类别”数量限制为他拥有和他创建的类别。它现在的工作方式是用户可以将“提要”添加到其他用户的“类别”,因为这是表单显示的内容。我该如何解决?

谢谢!-M

模型.py

from django.db import models
from django.contrib.auth.models import User

class Category(models.Model):
    name = models.CharField(max_length=50)
    user = models.ForeignKey(User)

class Feed(models.Model):
    url = models.URLField()
    name = models.CharField(max_length=50)
    created = models.DateTimeField(auto_now_add=True)
    description = models.TextField(blank=True)
    category = models.ForeignKey(Category)
    user = models.ForeignKey(User)

表格.py

class FeedForm(forms.ModelForm):

    class Meta:
        model = Feed
        exclude = ['user']

视图.py

def addfeed(request, user):
    user = request.user
    page_title = "Add feed"
    instance = Category.objects.filter(user=request.user)
    if request.method == 'POST':
        form = FeedForm(request.POST, instance=instance)
        if form.is_valid():
            feed = form.save(commit=False)
            feed.user = request.user  
            feed.save()
            return HttpResponseRedirect("/user/" + user.username + "/manage")
    else:
        form = FeedForm()
    return render(request, "form_manage.html", {
        'page_title': page_title,
        'form': form,
    })
4

2 回答 2

1

在某处设置queryset字段的属性。因为它取决于您的用户,所以您必须在实例化表单期间或之后设置它。例如,以下是如何在视图中执行此操作:

def addfeed(request, user):
    user = request.user # why does this view take user as an arg and then reassign?
    page_title = "Add feed"
    categories = Category.objects.filter(user=request.user)
    if request.method == 'POST':
        form = FeedForm(request.POST)
        form.fields['category'].queryset = categories
        if form.is_valid():
            feed = form.save(commit=False)
            feed.user = request.user  
            feed.save()
            return HttpResponseRedirect("/user/" + user.username + "/manage")
    else:
        form = FeedForm()
        form.fields['category'].queryset = categories
    return render(request, "form_manage.html", {
        'page_title': page_title,
        'form': form,})

我删除了instance您的 POST 案例表单构造的参数,因为这意味着传递现有Feed实例,而不是类别查询集。

__init__如果您传入正确的类别查询集,您也可以在表单中执行此操作。

于 2013-10-16T21:01:03.793 回答
0

javascript用来做这个。例如,您可以在视图中将相关类别的列表作为额外上下文传递,然后在模板中使用 javascript 来清空表单中预先填充的选项字段并将其替换为额外的上下文。

于 2013-10-16T20:56:02.627 回答