使用django在下拉列表中创建一个独特的模型选项

时间:2017-09-19 16:07:37

标签: python django

我已经创建了这个应用程序,但我现在面临的问题是一直让我感觉不舒服的问题。我希望用户在想要创建帖子时能够只查看和选择自己的类别。这是我的代码的一部分,其他代码将根据要求提供

类别模型

class Category(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1,related_name='categories_created')
    name = models.CharField(max_length = 120)
    slug = models.SlugField(unique= True)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

发布模型

class Post(models.Model):
     user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1,related_name='posts_created') #blank=True, null=True)
     title = models.CharField(max_length = 120)
     slug = models.SlugField(unique= True)
     category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category_created', null= True) 

将根据要求立即提供附加代码。感谢

发布应用中的View.py

def create(request):
    if not request.user.is_authenticated():
        messages.error(request, "Kindly confirm Your mail")
        #or raise Http404
    form = PostForm(request.POST or None, request.FILES or None)
    user = request.user
    categories = Category.objects.filter(category_created__user=user).distinct()
    if form.is_valid():
        instance = form.save(commit=False)
        instance.user = request.user
        instance.save()
        create_action(request.user, 'Posts', instance)
        messages.success(request, "Post created")
        return HttpResponseRedirect(instance.get_absolute_url())
    context = {
        "form": form,
    }
    template = 'create.html'
    return render(request,template,context)

表格

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = [
            "title",
            "content",
            "category",
        ]

HTML

{% if form %}

  <form method="POST" action="" enctype="multipart/form-data">{% csrf_token %}
    {{ form|crispy|safe }}
      <input type="submit" name="submit" value="Publish">
  </form>
      {% endif %}

1 个答案:

答案 0 :(得分:1)

您需要做的事情已被充分描述here。基本上,您正在使用ModelForm从模型生成表单。您的模型对用户过滤没有任何了解,因此您需要向表单中显式添加QuerySet,仅显示所需的类别。更改您的&#34;类别= ...&#34;如下所示:

form.category.queryset = Category.objects.filter(user = user)

form.fields['category'].queryset = Category.objects.filter(user=user)</strike>