【问题标题】:Error : Select a valid choice. That choice is not one of the available choices错误:选择一个有效的选项。该选择不是可用的选择之一
【发布时间】:2020-10-30 19:48:30
【问题描述】:

我正在使用 Django 创建博客。我希望在作者框中自动选择我的作者。实际上,该框已由 javascript 正确填充,但是当我提交表单时,它显示“选择一个有效的选择。该选择不是可用的选择之一。”但我为它提供了一个 TextInput 字段。当向作者提供 Select 而不是 TextInput 时,它运行良好。但我不想让作者选择我希望它由登录的名字填写。

我想在表单上添加新类别时自动更新我的选择列表,而不关闭整个服务器然后再次运行它。

Forms.py

from django import forms
from .models import Post, Category
from django.contrib.auth.models import User

# choices = [('coding','coding'),('entertainment','entertainment'),('sports','ssports')]
choices = Category.objects.all().values_list('name','name')
choice_list = []

for item in choices:
    choice_list.append(item)

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('title', 'title_tag','author','category', 'body', 'snippet')

        widgets = {
            'title': forms.TextInput(attrs={'class':'form-control'}),
            'title_tag': forms.TextInput(attrs={'class':'form-control'}),
            'author': forms.TextInput(attrs={'class':'form-control', 
                        'id':'gauname','value':'','type':'hidden'}),
            # 'author': forms.Select(attrs={'class':'form-control'}),
            'category': forms.Select(choices=choice_list,attrs={'class':'form-control'}),
            'body': forms.Textarea(attrs={'class':'form-control'}),
            'snippet': forms.Textarea(attrs={'class':'form-control'}),
        }

views.py

class AddCategoryView(CreateView):
    model = Category
    form_class =  AddCategory
    template_name = 'add_category.html'
    # fields = '__all__'

models.py


class Post(models.Model):
    title = models.CharField(max_length=255)
    title_tag = models.CharField(max_length=255)
    author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    # body = models.TextField()
    body = RichTextField(blank=True, null=True)
    post_date = models.DateTimeField(default=datetime.now)
    category = models.CharField(max_length=255, default='coding')
    snippet = models.CharField(max_length=255)
    likes = models.ManyToManyField(User, related_name='blog_posts')

    def total_likes(self):
        return self.likes.count()

    def __str__(self):
        return self.title + '|' + str(self.author)

    def get_absolute_url(self):
        # return reverse('article-detail', args=(str(self.id)))
        return reverse('home')

HTML


{% block content %}
{% if user.is_authenticated %}
  <h1>Add Post...</h1>
  <br><br><br>

  <form method="POST">
    <div class="form-group">
      {% csrf_token %}
      {{form.media}}
      {{form.as_p}}
      <!-- <input class = form-control type="text" id="gauname" name="author" value=""> -->
      <button class="btn btn-secondary" name="button">Post</button>
   </div>


  </form>

  <script>
    var name = "{{ request.user.first_name }}";
    document.getElementById("gauname").value = name;

  </script>
{% else %}

You are not allowed here!
{% endif %}


{% end block %}

更新

forms.py

class AddCategory(forms.ModelForm):
        class Meta:
            model = Category
            fields = ('name',)

            widgets = {
                'name': forms.TextInput(attrs={'class':'form-control'}),
            }

            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
                self.fields["name"] = forms.ModelChoiceField(
                    queryset=Category.objects.all(),
                )

我想在表单上添加新类别时自动更新我的选择列表,而不关闭整个服务器然后再次运行它。

【问题讨论】:

    标签: python django django-models django-forms foreign-keys


    【解决方案1】:

    如果有两个名字相同的人,Django 怎么知道这里的用户是谁?换句话说,Django 如何将名字映射到用户?没有意义

    因为无论如何它是一个隐藏字段,所以您可以直接传递 request.user.pk 而不是 request.user.first_name(该特定用户的唯一 ID)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-11
      • 2021-04-12
      • 2018-08-13
      • 2017-12-30
      • 2017-11-23
      • 2016-05-18
      • 2019-01-14
      • 2021-01-25
      相关资源
      最近更新 更多