繁体   English   中英

错误:Select 是一个有效的选择。 该选择不是可用的选择之一

[英]Error : Select a valid choice. That choice is not one of the available choices

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

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

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'}),
        }

视图.py

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

模型.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(),
                )

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

如果有两个名字相同的人,Django 应该如何知道这里的用户是谁? 换句话说,Django map 怎么可能是用户的名字? 这没有意义

由于它无论如何都是一个隐藏字段,而不是request.user.first_name你可以只传递request.user.pk代替(该特定用户的唯一 ID)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM