У меня есть веб-приложение, в котором пользователи могут добавлять элементы в список и классифицировать их. Пользователи также могут создавать эти категории. Система прекрасно работает, когда пользователь выбирает категорию из выпадающего списка, хотя, если пользователь не создал ни одной категории или хочет не классифицировать элемент, django выдает ошибку в form.is_valid, заявляя: Select a valid choice. That choice is not one of the available choices.
Я зашел так далеко, что изменил варианты в форме, чтобы они были такими, какими пользователь отправляет, но безрезультатно.
Я попытался установить выбор на готовую категорию «Нет», но это все еще не работало.
Вот мой метод публикации (когда пользователь нажимает кнопку «создать», чтобы создать элемент:
def post(self, request, *args, **kwargs):
form = ItemForm(request.POST)
print("Post Request: " + str(request.POST))
choice = request.POST.get('category')
print("Selected choice index: " + str(choice))
current_list = List.objects.get(id=request.session["list"])
category_choice = Category.objects.filter(list=current_list, id=choice)
if not category_choice.exists():
no_category_list = List.objects.get(id=26)
category_choice = Category.objects.filter(list=26, name="None")
#Set the choice to whatever the user inputted
form.fields['category'].choices = [(str(choice), category_choice)]
print("Category Object: " + str(category_choice))
print("Form Choices: " + str(form.fields['category'].choices))
if form.is_valid():
item = form.save()
json = {
"item": item.to_json()
}
else:
print(form.errors)
json = {
"error": "Invalid",
"message": "Please fill out all of the fields."
}
return JsonResponse(json)
Вот форма:
class ItemForm(forms.ModelForm):
class Meta:
model = Item
fields = ('list', 'name', 'desc', 'category')
def __init__(self, *args, **kwargs):
super(ItemForm, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs['autofocus'] = 'autofocus'
self.fields['category'].required = False
А вот модель элемента:
class Item(models.Model):
"""
this model represents an item and holds fields regarding that item
"""
def __unicode__(self):
return unicode(self.name)
list = models.ForeignKey(List, verbose_name="Current List")
name = models.CharField(max_length=200, default="", verbose_name="Item Name")
desc = models.TextField(max_length=400, default="", verbose_name="Item Description")
active = models.BooleanField(default=True, verbose_name="Active Item")
lost = models.BooleanField(default=False, verbose_name="Mark as lost")
category = models.ForeignKey(Category, verbose_name="Item Category", blank=True, null=True)
objects = ItemThings()
def to_json(self):
return {
"list": str(self.list.name),
"name": str(self.name),
"desc": self.desc,
"category": self.category.to_json() if self.category else "None",
"pk": self.id,
"id": self.id,
"active": self.active,
"lost": self.lost,
}
Вывод в моем терминале, когда я нажимаю «Создать», выглядит следующим образом:
Post Request: <QueryDict: {u'category': [u'0'], u'csrfmiddlewaretoken': [token was here], u'desc': [u'test description'], u'name': [u'test name'], u'list': [u'4']}>
Selected choice index: 0
Category Object: <QuerySet [<Category: None>]>
Form Choices: [('0', <QuerySet [<Category: None>]>)]
<ul class="errorlist"><li>category<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul>
Вывод в моем терминале когда я нажимаю «Создать» для элемента с , категория:
Post Request: <QueryDict: {u'category': [u'10'], u'csrfmiddlewaretoken': [token was here], u'desc': [u'test description'], u'name': [u'test name'], u'list': [u'26']}>
Selected choice index: 10
Category Object: <QuerySet [<Category: Tools>]>
Form Choices: [('10', <QuerySet [<Category: Tools>]>)]
Любая помощь будет принята с благодарностью! Может предоставить дополнительную информацию по мере необходимости!
Спасибо вы!