繁体   English   中英

选择一个有效的选项。 该选择不是可用的选择之一——Django 表单

[英]Select a valid choice. That choice is not one of the available choices --Django forms

我正在尝试在 django 中创建一个下拉选择表单(类别)。
表单在网页上呈现良好,但是当我尝试提交时,我收到错误选择一个有效的选择。 该选择不是可用的选择之一。 我已尽我所能解决这个问题。 如果您对如何解决此问题有任何想法,请提供帮助。

图片

模型.py

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

# Create your models here.
class Category(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

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

class Post(models.Model):
    title = models.CharField(max_length=100)
    text = models.TextField()
    author = models.ForeignKey(User,  on_delete=models.CASCADE)
    edited = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)
    category = models.CharField(max_length=100, default='coding')

    def __str__(self):
        return f'{self.title} by {self.author} {self.pk}'

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

表格.py

from django import forms
from .models import Post, Category

choices = Category.objects.all().values_list('name','name')
choices_list = []
for item in choices:
    choices_list.append(item)

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('title', 'category', 'author','text')
    widgets={
            'title': forms.TextInput(attrs={'class':'form-control'}),
            'category': forms.Select(choices=choices_list, attrs={'class':'form-control'}),
            'author': forms.TextInput(attrs={'class':'form-control', 'id':'author'}),
            # 'author': forms.Select(attrs={'class':'form-control'}),
            'text': forms.Textarea(attrs={'class':'form-control','placeholder':choices_list}),
}

class EditForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('title', 'text')
        widgets={
            'title': forms.TextInput(attrs={'class':'form-control'}),
            'text': forms.Textarea(attrs={'class':'form-control','placeholder':"less than 500 words"}),
            # 'author': forms.Select(attrs={'class':'form-control'})
}

视图.py

class createarticleview(CreateView):
    template_name='posts/addpost.html'
    model = Post
    form_class = PostForm
    #fields = '__all__'
    # fields = ('title','text') for certain fields
    def get_context_data(self, *args, **kwargs):
        cat_menu = Category.objects.all()
        context = super(createarticleview, self).get_context_data(*args, **kwargs)
        context['cat_menu'] = cat_menu
        return context  

addpost.html

{%extends 'index.html'%}
{%block content%}
{% if user.is_authenticated %}
    <div class="container">
        <h3>add post...!!!.{{user.username}}</h3>
        <br>
        <div class="mb-3">
        <form method="POST"> {% csrf_token%}
        {{form.as_p}}
        <button type="submit" class="btn btn-info"> post</button>           
        </form>
    </div>
    </div>

    <script>
        
        var name = "{{user.username}}";
    if(document.getElementById("author").value=name)
    document.getElementById('author').readOnly = true;
  

    </script>
{% else%}
        <h3>you are not logged in</h3>
{%endif%}
{%endblock content%}

首先,在定义class的名称时始终使用PascalCase ,就像您可以CreateArticleView而不是createarticleview

在定义Post和给定models.CharField()的模型时,您没有给出choices

使用choices属性更新您的Post模型。

尝试这个:

模型.py


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

CATEOGRY_TYPES = (
    ('sp', 'sport'),
    ('te', 'technology'),
    ('bu', 'business')
)


class Category(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

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


class Post(models.Model):
    title = models.CharField(max_length=100)
    text = models.TextField()
    author = models.ForeignKey(User,  on_delete=models.CASCADE)
    edited = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)
    category = models.CharField(
        choices=CATEOGRY_TYPES, max_length=2, default='coding')

    def __str__(self):
        return f'{self.title} by {self.author} {self.pk}'

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

视图.py

from django.shortcuts import render
from .models import Post, Category
from .forms import PostForm
from django.views.generic.edit import CreateView


class CreateArticleView(CreateView):
    template_name = 'posts/addpost.html'
    model = Post
    form_class = PostForm
    success_url = '/success/'


def success(req):
    return render(req, 'posts/success.html')

其余的事情将保持不变。

您可以通过在Post模型中直接创建ForeignKey字段来执行此操作而无需reverse方法。

你也可以这样做:

模型.py

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


class Category(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name


class Post(models.Model):
    title = models.CharField(max_length=100)
    text = models.TextField()
    author = models.ForeignKey(User,  on_delete=models.CASCADE)
    edited = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)
    category = models.ForeignKey(
        Category, on_delete=models.CASCADE, default='coding')

    def __str__(self):
        return f'{self.title} by {self.author} {self.pk}'

视图.py

from django.shortcuts import render
from .models import Post, Category
from .forms import PostForm
from django.views.generic.edit import CreateView


class CreateArticleView(CreateView):
    template_name = 'posts/addpost.html'
    model = Post
    form_class = PostForm
    success_url = '/success/'


def success(req):
    return render(req, 'posts/success.html')

您的forms.py可以保持不变。

请记住:定义模型时的选择ForeignKey choices优先。

暂无
暂无

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

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