Ошибка select a valid choice 0 is not one of the available choices

TYPE1 = 0
TYPE2 = 1

OPEN_TYPES = (
    (TYPE1, _(u"Test")),
    (TYPE2, _(u"Test2")),
)

models:

models.CharField(max_length=10, choices=OPEN_TYPES)

I have this error if I try to add object in admin panel:

Select a Valid Choice. 0 is not one of the available choices

How to fix it?

asked May 15, 2014 at 15:11

mamasi's user avatar

mamasimamasi

9153 gold badges10 silver badges17 bronze badges

You’re using integer values with a CharField. You have to either use the values '0' and '1' or change it to an IntegerField.

answered May 15, 2014 at 15:32

knbk's user avatar

knbkknbk

51.8k9 gold badges123 silver badges122 bronze badges

Use a default value also that will work!

answered Apr 14, 2018 at 7:05

rg8143's user avatar

TYPE1 = 0
TYPE2 = 1

OPEN_TYPES = (
    (TYPE1, _(u"Test")),
    (TYPE2, _(u"Test2")),
)

models:

models.CharField(max_length=10, choices=OPEN_TYPES)

I have this error if I try to add object in admin panel:

Select a Valid Choice. 0 is not one of the available choices

How to fix it?

asked May 15, 2014 at 15:11

mamasi's user avatar

mamasimamasi

9153 gold badges10 silver badges17 bronze badges

You’re using integer values with a CharField. You have to either use the values '0' and '1' or change it to an IntegerField.

answered May 15, 2014 at 15:32

knbk's user avatar

knbkknbk

51.8k9 gold badges123 silver badges122 bronze badges

Use a default value also that will work!

answered Apr 14, 2018 at 7:05

rg8143's user avatar

TYPE1 = 0
TYPE2 = 1

OPEN_TYPES = (
    (TYPE1, _(u"Test")),
    (TYPE2, _(u"Test2")),
)

models:

models.CharField(max_length=10, choices=OPEN_TYPES)

I have this error if I try to add object in admin panel:

Select a Valid Choice. 0 is not one of the available choices

How to fix it?

asked May 15, 2014 at 15:11

mamasi's user avatar

mamasimamasi

9153 gold badges10 silver badges17 bronze badges

You’re using integer values with a CharField. You have to either use the values '0' and '1' or change it to an IntegerField.

answered May 15, 2014 at 15:32

knbk's user avatar

knbkknbk

51.2k9 gold badges120 silver badges117 bronze badges

Use a default value also that will work!

answered Apr 14, 2018 at 7:05

rg8143's user avatar

Create an account to follow your favorite communities and start taking part in conversations.

r/Instagram

r/Instagram - "Select a valid choice. 0 is not one of the available choices." Can't get passed this message despite looking at the report and selecting acknowledge. Any ideas?. Knowing that I tried from different devices

level 1

Same problem for me also.Its been now 4 days and still cant skip this message im so angry .Cant access my page .wtf is this problem,dude.

level 1

Same problem here. Tried literally everything you can imagine. Locked out for 8 days at the moment.

level 2

Omg, that doesn’t sound good at all. 4 DAYS now for me

level 1

I’m having the same problem… been 5 days and nothing…. shocking really.

level 2

Wish I knew.. ive tried reporting it but nothing has happened…

level 1

Guys,

I tweeted @ mosseri on twitter and he is the head of IG. I said how I and others are having this problem. If you all can at some point do the same, maybe he will see it and address it as a whole or individually. Either way, I will report any feedback I get on here! We need to come together and see if we can get a response.

level 2

Give the link of your tweet so we can support you and add our case to yours

level 1

UPDATE!!! IM BACK ON MY ACC

level 2

back for me as well. The stupid checkbox UI is changed, I saw another UI with a «next» and my account it back.

However the following message was quite scary — it said «your account may be disabled» — and it was showing me 3 dmca claims as a list instead of one. I’m not sure what’s going on?

level 1

check off the terms and conditions at the bottom first.

level 2

I’ve got same error, even when i check t&c

level 2

I have no terms and conditions — I only have » I acknowledge that I have viewed the content that was removed on my account. » checkbox

level 1

Error message states that this square box its missing a check-mark.

View whole report (entire thing) come back and check the box.

If that wont register>> report a problem via Account >>Settings>>Report a problem

level 2

I already did several times and still this error appearing. And even tried from different devices it didn’t work . The issue is that I cannot access the account to go to settings and report the problem

level 2

Comment removed by moderator · 3 yr. ago

level 1

I’ve had my account disabled then reinstated because the trademark reporting company retracted the reports but now I’m stuck with this screen. Its been 5 days since my account has been reinstated. I’m trying their IP as well as the support «report a problem» with both IG and Facebook. Hope they fix this today or I will fix to sue the reporter because they got it wrong.

About Community

Subreddit Icon

The un-official (and unaffiliated) subreddit for Instagram.com — Learn tips and tricks, ask questions and get feedback on your account. Come join our great community of over 230,000 users!



class AddLocationPageView(FormView):
    template_name = 'add_location.html'
    form_class = LocationForm
    success_url = '/add_location/location_added/'
    def form_valid(self, form):
        form.save()
        return super(AddLocationPageView, self).form_valid(form)
type_choices = (
('Рассвет/Закат', 'Рассвет/Закат'),('Ландшафт', 'Ландшафт'),('Природа', 'Природа'),
('Вода', 'Вода'),('Животные', 'Животные'),('Люди', 'Люди'),
('Архитектура', 'Архитектура'),('Город', 'Город'),('Астрофото', 'Астрофото'),
('Панорама', 'Панорама'),('Транспорт', 'Транспорт'),('Свадьба', 'Свадьба'),
)
equip_choices = (
('Tripod', 'Tripod'),('Shutter Release Cable', 'Shutter Release Cable'),('Filters', 'Filters'),
('Cleaning Equipment', 'Cleaning Equipment'),('Rain Cover', 'Rain Cover'),('Flash/speedlight', 'Flash/speedlight'),
('Flash Radio Triggers', 'Flash Radio Triggers'),('Light Modifiers', 'Light Modifiers'),
('Wide Angle Lens', 'Wide Angle Lens'),('Telephoto Lens', 'Telephoto Lens'),
('Prime Lens', 'Prime Lens'),('Macro Lens', 'Macro Lens'),('Assistant', 'Assistant'),
)
visit_choices = (
('Январь', 'Январь'),('Февраль', 'Февраль'),('Март', 'Март'),
('Апрель', 'Апрель'),('Май', 'Май'),('Июнь', 'Июнь'),
('Июль', 'Июль'),('Август', 'Август'),('Сентябрь', 'Сентябрь'),
('Октябрь', 'Октябрь'),('Ноябрь', 'Ноябрь'),('Декабрь', 'Декабрь'),
)
class Location(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    name = models.CharField(max_length=100, verbose_name="Локация", default='')
    types = models.CharField(max_length=50, verbose_name="Тип локации", choices=type_choices, default='')
    equipment = models.CharField(max_length=50, verbose_name="Рекомендуемая экипировка", choices=equip_choices, default='')
    visit_times = models.CharField(max_length=50, verbose_name="Лучшее время для съемки", choices=visit_choices, default='')
    photos = models.ImageField(upload_to='photos', null=True, blank=True)
    keywords = models.CharField(max_length=100, verbose_name="Ключевые слова", default='')
    description = models.TextField(null=True, blank=True)
    def __unicode__(self):
        return self.name
class LocationForm(forms.ModelForm):
    class Meta:
        model = Location
        fields = ['name', 'types', 'equipment', 'visit_times', 'photos', 'keywords', 'description']
        widgets = {
        'name': forms.TextInput(attrs={'placeholder': 'Напр. Стоунхендж'}),
        'types': forms.SelectMultiple(),
        'equipment': forms.SelectMultiple(),
        'visit_times': forms.SelectMultiple(),
        'keywords': forms.TextInput(attrs={'placeholder': 'Напр. море, побережье, скалы'}),
        'description': forms.Textarea(attrs={'placeholder': 'Любая информация, которую посчитаете нужной'})
    }

Когда на странице заполняю поля и делаю выбор в полях селекта, то после нажатия кнопки на полях селекта выдает ошибку указанную в названии темы.

I have 2 apps.

input: has the form containing a drop down list: region. The drop down list values are coming from the database of result (uploaded by user). When filling the form, user needs to select the value from the drop down list.

result:have the database

Now I can show the drop down list from the database of «input» app in the input form. (shown in picture).
enter image description here

The problem I face now is after selecting the choice and submit it, there is an error shown as below:

The error shows like: select a valid choice.The choice is not one of available choices. Then I don’t see why because I indeed selected the choice from drop down list.

Thanks in advance for your help to pin point the problem.

models.py

from django import forms
from django.forms import ModelForm
from django.db import models
from dupont.models import Result
from datetime import date
from django.forms import widgets

class Input(models.Model):
    company=models.CharField(max_length=100)
    region=models.CharField(max_length=100)

    def __unicode__(self):
        return self.company

forms.py

from django import forms
from django.forms import ModelForm
from .models import Input
from dupont.models import Result
from django.contrib.auth.models import User,Group
from django.forms import widgets
from functools import partial
from django.forms.utils import ErrorList

class InputForm(forms.ModelForm):
    company=forms.CharField(widget=forms.TextInput, label="Company",error_messages={'required': 'Please enter the company name'},required=True)
    region = forms.ModelChoiceField(queryset=Dupont.objects.values('region').distinct(),widget=forms.Select(),empty_label="(Global)",to_field_name="supply_chain")
    error_css_class='error'
    required_css_class = 'required'

    class Meta:
        model = Input
        fields = ('company', 'region')

views.py

from django.http import HttpResponseRedirect
from django.shortcuts import render,render_to_response,get_object_or_404
from inputform.forms import InputForm
from inputform.models import Input
from dupont.models import Result
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.list import ListView
from django.contrib import messages
from django.template import RequestContext
from django.shortcuts import redirect

@csrf_exempt
def input(request):
    if request.method == 'POST':
        form = InputForm(request.POST)
        if form.is_valid():
            company = form.cleaned_data['company']
            region = form.cleaned_data['region']    /Is this one correct?
            form.save()
            return redirect('result')
        else:
            print form.errors

    else:
        form=InputForm()
    return render_to_response('inputform.html',{'form': form},context_instance=RequestContext(request))

html

<form method="post" action="{% url 'input' %}">
        {% csrf_token %}

        <!--company--> 
        <div class="field">
            {{ form.company.errors }}
            <label for="{{ form.company.id_for_label }}">Company:</label>
            {{ form.company }}
        </div>

        <!--Region-->
        <div class="field" >
            <label> Select the Region:
            {{ form.region }}
                {% for region in form.region.choices %}
                     <option value="region" name= "region" id="id_region">{{region}} </option>
                {% endfor %}
            </label>
        </div>

        <!--submit-->
        <div class="fieldWrapper">
        <p><input type="submit" value="Submit" /></p></div>

 </form>    

I’m new to Django. What i’m trying to do is to show some JSON response value which i converted into tuples to show in the choicefield of my Django form.

This is how i’m creating the tuples

usernamelist = []
useremaillist = []
for userobject in userobjects:
    username = userobject['somevalue']
    email = userobject['somevalue']
    useremaillist.append(email)
    usernamelist.append(username)
user_tuple = zip(usernamelist,useremaillist)

This is my form

class UserSelectForm(forms.Form):
    users = forms.ChoiceField(label="Select user")

Then in my views i’m trying to put all these names into drop down list

selectform = UserSelectForm()
selectform.fields['users'].choices = user_tuple

its successfully showing but when i try to submit my form i’m getting Select a valid choice is not one of the available choices error.

This is where i’m trying to get the drop down selected value from submitted form

if request.method == 'POST' and 'preview' in request.POST:
    selectform = UserSelectForm(request.POST)
    if selectform.is_valid():
        user_email = selectform.cleaned_data['users']
        print user_email
        return HttpResponseRedirect('/')

Answer 1

If you really need to manually decide the choices then you should include them as a requirement for the initializer for the form

class UserSelectForm()
     def __init__(self, choices, *args, **kwargs):
         super().__init__(*args, **kwargs)
         self.fields['users'].choices = choices

Then call it with the choices

UserSelectForm(user_tuple, request.POST or None)

I am building a Create a Recipe form using solved uvdos django crispy forms and I am trying to use a solved uvdos django datalist input field for users to enter solved uvdos django their own ingredients, like ‘Big Tomato’ or solved uvdos django select from GlobalIngredients already in the solved uvdos django database like ‘tomato’ or ‘chicken’. solved uvdos django However, regardless of whether I enter a new solved uvdos django ingredient or select a pre-existing one, I solved uvdos django am getting the following error: «Select a solved uvdos django valid choice. That choice is not one of the solved uvdos django available choices.». How do I fix this solved uvdos django error?

Visual:

models.py

class Recipe(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    websiteURL = models.CharField(max_length=200, blank=True, null=True)
    image = models.ImageField(upload_to='image/', blank=True, null=True)
    name = models.CharField(max_length=220) # grilled chicken pasta
    description = models.TextField(blank=True, null=True)
    notes = models.TextField(blank=True, null=True)
    serves = models.CharField(max_length=30, blank=True, null=True)
    prepTime = models.CharField(max_length=50, blank=True, null=True)
    cookTime = models.CharField(max_length=50, blank=True, null=True)


class Ingredient(models.Model):
    name = models.CharField(max_length=220)

    def __str__(self):
        return self.name

class GlobalIngredient(Ingredient):
    pass # pre-populated ingredients e.g. salt, sugar, flour, tomato

class UserCreatedIngredient(Ingredient): # ingredients user adds, e.g. Big Tomatoes
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

class RecipeIngredient(models.Model):
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
    ingredient = models.ForeignKey(Ingredient, null=True, on_delete=models.SET_NULL)
    description = models.TextField(blank=True, null=True)
    quantity = models.CharField(max_length=50, blank=True, null=True) # 400
    unit = models.CharField(max_length=50, blank=True, null=True) # pounds, lbs, oz ,grams, etc

forms.py

class RecipeIngredientForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
    
        super(RecipeIngredientForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper()
        #self.helper.form_id = 'id-entryform'
        #self.helper.form_class = 'form-inline'
        self.helper.layout = Layout(
            Div(
                Div(Field("ingredient", placeholder="Chickpeas - only write the ingredient here"), css_class='col-6 col-lg-4'),
                Div(Field("quantity", placeholder="2 x 400"), css_class='col-6 col-md-4'),
                Div(Field("unit", placeholder="grams"), css_class='col-5 col-md-4'),
                Div(Field("description", placeholder="No added salt tins - All other information, chopped, diced, whisked!", rows='3'), css_class='col-12'),
            
            css_class="row",
           ),
           
        )
        
    class Meta:
        model = RecipeIngredient
        fields = ['ingredient', 'quantity', 'unit', 'description']
        labels = {
            'ingredient': "Ingredient",
            "quantity:": "Ingredient Quantity",
            "unit": "Unit",
            "description:": "Ingredient Description"}
        widgets={'ingredient': forms.TextInput(attrs={
            'class': 'dropdown',
            'list' : 'master_ingredients',
            'placeholder': "Chickpeas - only write the ingredient here"
        })}

views.py

@login_required
def recipe_create_view(request):
    ingredient_list = Ingredient.objects.all()
    form = RecipeForm(request.POST or None)
    # Formset = modelformset_factory(Model, form=ModelForm, extra=0)
    RecipeIngredientFormset = formset_factory(RecipeIngredientForm)
    formset = RecipeIngredientFormset(request.POST or None)
    RecipeInstructionsFormset = formset_factory(RecipeInstructionForm, extra=0)
    instructionFormset = RecipeInstructionsFormset(request.POST or None, initial=[{'stepName': "Step 1"}], prefix="instruction")
    
    context = {
        "form": form,
        "formset": formset,
        "instructionFormset": instructionFormset,
        "ingredient_list": ingredient_list
    }
    if request.method == "POST":
        print(request.POST)
        if form.is_valid() and formset.is_valid() and instructionFormset.is_valid():
            parent = form.save(commit=False)
            parent.user = request.user
            parent.save()
            # formset.save()
            #recipe ingredients
            for form in formset:
                child = form.save(commit=False)
                print(child.ingredient)
                globalIngredient = Ingredient.objects.filter(name=child.ingredient.lower()) # not truly global as this will return user ingredients too
                if (globalIngredient):
                    pass
                else:
                    newIngredient = UserCreatedIngredient(user=request.user, name=child.ingredient.lower())
                    newIngredient.save()
                if form.instance.ingredient.strip() == '':
                    pass
                else:
                    child.recipe = parent
                    child.save()
            # recipe instructions
            for instructionForm in instructionFormset:
                instructionChild = instructionForm.save(commit=False)
        
                if instructionForm.instance.instructions.strip() == '':
                    
                    pass
                else:
                   
                    instructionChild.recipe = parent
                    instructionChild.save()
            context['message'] = 'Data saved.'
            
            return redirect(parent.get_absolute_url())
    else:
        form = RecipeForm(request.POST or None)
        formset = RecipeIngredientFormset()
        instructionFormset = RecipeInstructionsFormset()
    return render(request, "recipes/create.html", context)

create.html

<!--RECIPE INGREDIENTS-->
{% if formset %}
<h3 class="mt-4 mb-3">Ingredients</h3>
{{ formset.management_form|crispy }}

<div id='ingredient-form-list'>
    {% for ingredient in formset %}

            <div class='ingredient-form'>
                
                {% crispy ingredient %}
               
            </div>
    {% endfor %}

    <datalist id="master_ingredients">
        {% for k in ingredient_list %}
            <option value="{{k.name|title}}"></option>
        {% endfor %}
    </datalist>
</div>

<div id='empty-form' class='hidden'>
    <div class="row mt-4">
        <div class="col-6">{{ formset.empty_form.ingredient|as_crispy_field }}</div>
        <div class="col-6">{{ formset.empty_form.quantity|as_crispy_field }}</div>
        <div class="col-6">{{ formset.empty_form.unit|as_crispy_field }}</div>
        <div id="ingredientIdForChanging" style="display: none;"><div class="col-12">{{ formset.empty_form.description|as_crispy_field }}</div><button type="button"
            class="btn btn-outline-danger my-2" onclick="myFunction('showDescription')"><i class="bi bi-dash-circle"></i> Hide
            Description</button></div><button type="button"
            class="btn btn-outline-primary col-5 col-md-3 col-lg-3 col-xl-3 m-2" id="ingredientIdForChanging1"
            onclick="myFunction('showDescription')"><i class="bi bi-plus-circle"></i> Add a
            Description Field</button>
        
    </div>
</div>
<button class="btn btn-success my-2" id='add-more' type='button'>Add more ingredients</button>
{% endif %}

28

Answers 1 : of Datalist with free text error Select a valid choice. That choice is not one of the available choices.

You can create your own TextInput and post uvdos html-datalist TypedModelListField field to handle post uvdos html-datalist this. I think what you’re looking for is post uvdos html-datalist something which allows the user to both post uvdos html-datalist search and provide a recommended post uvdos html-datalist selection of choices but validate the post uvdos html-datalist input against a model (Ingredient).

I’ve created one here:

class TypedModelListField(forms.ModelChoiceField):

    def to_python(self, value):
        if self.required:
            if value == '' or value == None:
                raise forms.ValidationError('Cannot be empty')
            
        validate_dict = {self.validate_field: value}
        try:
            value = type(self.queryset[0]).objects.get(**validate_dict))
        except:
            raise forms.ValidationError('Select a valid choice. That choice is not one of the available choices.')
        value = super().to_python(value)
        return value

    def __init__(self, *args, **kwargs):
        self.validate_field= kwargs.pop('validate_field', None)
        super().__init__(*args, **kwargs)


class ListTextWidget(forms.TextInput):

    def __init__(self, dataset, name, *args, **kwargs):
        super().__init__(*args)
        self._name = name
        self._list = dataset
        self.attrs.update({'list':'list__%s' % self._name,'style': 'width:100px;'})
        if 'width' in kwargs:
            width = kwargs['width']
            self.attrs.update({'style': 'width:{}px;'.format(width)})
        if 'identifier' in kwargs:
            self.attrs.update({'id':kwargs['identifier']})

    def render(self, name, value, attrs=None, renderer=None):
        text_html = super().render(name, value, attrs=attrs)
        data_list = '<datalist id="list__%s">' % self._name
        for item in self._list:
            data_list += '<option value="%s">' % item
        data_list += '</datalist>'
        return (text_html + data_list)

Within the RecipeIngredientForm add the post uvdos html-datalist following definition:

ingredient = TypedModelListField(
                    queryset=Ingredient.objects.all(),
                    validate_field='name')

And then in RecipeIngredientForm within post uvdos html-datalist the __init__ function. Include the post uvdos html-datalist following after the super() is called.

self.fields['ingredient'].widget = ListTextWidget(
        dataset=Ingredient.objects.all(), 
        name='ingredient_list')

0

2023-01-27T04:58:15+00:00 2023-01-27T04:58:15+00:00Answer Link

mRahman

2

Answers 2 : of Datalist with free text error Select a valid choice. That choice is not one of the available choices.

With ecogels comment I was able to post uvdos html-datalist understand what was causing the issue post uvdos html-datalist and with a combination of Lewis answer post uvdos html-datalist and this answer I managed to get this post uvdos html-datalist working with the following code.

fields.py

    from django import forms

class ListTextWidget(forms.TextInput):
    def __init__(self, data_list, name, *args, **kwargs):
        super(ListTextWidget, self).__init__(*args, **kwargs)
        self._name = name
        self._list = data_list
        self.attrs.update({'list':'list__%s' % self._name})

    def render(self, name, value, attrs=None, renderer=None):
        text_html = super(ListTextWidget, self).render(name, value, attrs=attrs)
        data_list = '<datalist id="list__%s">' % self._name
        for item in self._list:
            data_list += '<option value="%s">' % str(item).title()
        data_list += '</datalist>'

        return (text_html + data_list)

forms.py

from .fields import ListTextWidget

class RecipeIngredientForm(forms.ModelForm):
    ingredientName = forms.CharField(required=True)

    def __init__(self, *args, **kwargs):
        super(RecipeIngredientForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.layout = Layout(
            Div(
                Div(Field("ingredientName", placeholder="Chickpeas - only write the ingredient here"), css_class='col-6 col-lg-4'),
                Div(Field("quantity", placeholder="2 x 400"), css_class='col-6 col-md-4'),
                Div(Field("unit", placeholder="grams"), css_class='col-5 col-md-4'),
                Div(Field("description", placeholder="No added salt tins - All other information, chopped, diced, whisked!", rows='3'), css_class='col-12'),
            
            css_class="row",
           ),
           
        )
        self.fields['ingredientName'].widget = ListTextWidget(data_list=Ingredient.objects.all(), name='ingredient-list')
    class Meta:
        model = RecipeIngredient
        fields = ['ingredientName', 'quantity', 'unit', 'description']
        labels = {
            'ingredientName': "Ingredient",
            "quantity:": "Ingredient Quantity",
            "unit": "Unit",
            "description:": "Ingredient Description"}

create.html:

<!--RECIPE INGREDIENTS-->
                {% if formset %}
                    <h3 class="mt-4 mb-3">Ingredients</h3>
                    {{ formset.management_form|crispy }}
                    
                    <div id='ingredient-form-list'>
                        {% for ingredient in formset %}
                    
                                <div class='ingredient-form'>
                                    
                                    {% crispy ingredient %}
                                    
                                </div>
                        {% endfor %}
                    </div>

                    <div id='empty-form' class='hidden'>
                        <div class="row mt-4">
                            <div class="col-6">{{ formset.empty_form.ingredientName|as_crispy_field }}</div>
                            <div class="col-6">{{ formset.empty_form.quantity|as_crispy_field }}</div>
                            <div class="col-6">{{ formset.empty_form.unit|as_crispy_field }}</div>
                            <div id="ingredientIdForChanging" style="display: none;"><div class="col-12">{{ formset.empty_form.description|as_crispy_field }}</div><button type="button"
                                class="btn btn-outline-danger my-2" onclick="myFunction('showDescription')"><i class="bi bi-dash-circle"></i> Hide
                                Description</button></div><button type="button"
                                class="btn btn-outline-primary col-5 col-md-3 col-lg-3 col-xl-3 m-2" id="ingredientIdForChanging1"
                                onclick="myFunction('showDescription')"><i class="bi bi-plus-circle"></i> Add a
                                Description Field</button>
                            
                        </div>
                    </div>
                    <button class="btn btn-success my-2" id='add-more' type='button'>Add more ingredients</button>
                {% endif %}

views.py changes:

form = RecipeForm(request.POST or None)
    # Formset = modelformset_factory(Model, form=ModelForm, extra=0)
    RecipeIngredientFormset = formset_factory(RecipeIngredientForm)
    formset = RecipeIngredientFormset(request.POST or None)
    RecipeInstructionsFormset = formset_factory(RecipeInstructionForm, extra=0)
    instructionFormset = RecipeInstructionsFormset(request.POST or None, initial=[{'stepName': "Step 1"}], prefix="instruction")
    URLForm = RecipeIngredientURLForm(request.POST or None)
    context = {
        "form": form,
        "formset": formset,
        "URLForm": URLForm,
        "instructionFormset": instructionFormset
    }

0

2023-01-27T04:58:15+00:00 2023-01-27T04:58:15+00:00Answer Link

rohim

I rely on Bitbucket’s API heavily to manage repositories at iThemes. Recently, some of the API calls started to fail and returned nonsensical error messages.

When making a PUT request to the /1.0/repositories/TEAM/SLUG endpoint, I received an error response with a status code of 400 and the following message:

<ul class="errorlist"><li>project<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul>

This message makes no sense as the documentation for that endpoint has no mention of a parameter named project.

Going directly to bitbucket.org and trying to create a new repository there revealed that a new, required Project input is now on the form. This explains where the error message is coming from. It looks as though they added the new parameter to the repositories, made it mandatory, and updated the API endpoint to reflect this new mandatory parameter, but failed to update the documentation or to have any backwards-compatible support.

I found that supplying the project parameter with a value of PROJ (the default value in the form) got rid of the error message.

Did I help you?

  • Send me a tip via Paypal.
  • Help with this site’s hosting with my Linode referral code.

#22614

closed


Uncategorized


(invalid)

Reported by: Owned by: nobody
Component: Uncategorized Version: 1.6
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

I’ve got en error from admin page.

I have some simple django 1.6.2 code

models.py

from django.db import models

# Create your models here.

class PhysicalProperty(models.Model):
    shortname = models.CharField(max_length=255)    
    def __str__(self):
        return self.shortname
    
class Product(models.Model):
    shortname = models.CharField(max_length=255)
    
    product_metricals = models.ManyToManyField( PhysicalProperty, through = 'ProductMetricals' )    
      
    def __str__(self):
        return self.shortname
               
from django.db.models.signals import post_save
from django.dispatch import receiver
  
@receiver(post_save, sender=Product)
def product_post_save(sender, instance, **kwargs):
    # ProductMetricals.objects.filter( product = instance ).delete()    # prev. realizaton
    
    if True: # some conditions will be here
        instance.product_metricals.clear()
   
        
class ProductMetricals(models.Model):
    amount=models.FloatField()
    product=models.ForeignKey( Product )
    physicalproperty = models.ForeignKey(PhysicalProperty )
    
    class Meta:
        unique_together = ("product", "physicalproperty")

admin.py

from django.contrib import admin

# Register your models here.

from product.models import Product, ProductMetricals, PhysicalProperty

from django import forms
    
class PhysicalPropertyAdmin(admin.ModelAdmin):
    list_display = ['shortname']
    
admin.site.register(PhysicalProperty, PhysicalPropertyAdmin)

class ProductMetricalsInline(admin.TabularInline):
    model = ProductMetricals
    fieldsets = [
        (None, {'fields': ['physicalproperty','amount']}),
    ]
    extra = 2

def safe_delete(modeladmin, request, queryset):
    for i in queryset:
        i.save()

safe_delete.short_description = 'safe delete!'
    
class ProductAdmin(admin.ModelAdmin):
    fieldsets = [
        (None,               {'fields': ['shortname']}),
    ]
    inlines = [ProductMetricalsInline]
    list_display = ['shortname']
    actions = [safe_delete]
    
admin.site.register(Product, ProductAdmin)

product_post_save reciever take some conditional subdata clearing. If I makes a changes in product admin page — i’ve got the validation error

‘Select a valid choice. That choice is not one of the available choices.’

In safe_delete admin-action all work fine.

Why I’ve got the ‘Select a valid choice. That choice is not one of the available choices.’ error?

I ask same on http://stackoverflow.com/questions/23521938/django-admin-says-select-a-valid-choice-that-choice-is-not-one-of-the-availabl, but have no answer.

Solution 1

You’re using integer values with a CharField. You have to either use the values '0' and '1' or change it to an IntegerField.

Solution 2

Use a default value also that will work!

Related videos on Youtube

Django : ChoiceField: Select a valid choice. That is not one of the available choices

01 : 24

Django : ChoiceField: Select a valid choice. That is not one of the available choices

Django : Select a Valid Choice. 0 is not one of the available choices

01 : 12

Django : Select a Valid Choice. 0 is not one of the available choices

Select a Valid Choice. 0 is not one of the available choices - Django

01 : 01

Select a Valid Choice. 0 is not one of the available choices — Django

django forms give Select a valid choice. That choice is not one of the available choices - Django

01 : 19

django forms give Select a valid choice. That choice is not one of the available choices — Django

ChoiceField Select a valid choice. That is not one of the available choices - Django

01 : 22

ChoiceField Select a valid choice. That is not one of the available choices — Django

Comments

  • TYPE1 = 0
    TYPE2 = 1
    
    OPEN_TYPES = (
        (TYPE1, _(u"Test")),
        (TYPE2, _(u"Test2")),
    )
    

    models:

    models.CharField(max_length=10, choices=OPEN_TYPES)
    

    I have this error if I try to add object in admin panel:

    Select a Valid Choice. 0 is not one of the available choices

    How to fix it?

Recents


Go to Instagram


r/Instagram


r/Instagram

The un-official (and unaffiliated) subreddit for Instagram.com — Learn tips and tricks, ask questions and get feedback on your account. Come join our great community of over 280,000 users!




Members





Online



by

abedserhan



«Select a valid choice. 0 is not one of the available choices.» Can’t get passed this message despite looking at the report and selecting acknowledge. Any ideas?. Knowing that I tried from different devices


r/Instagram - a screenshot of a phone

  • Ошибка sfh на котле vaillant
  • Ошибка securom reported error 2000 при запуске гта 4
  • Ошибка sf на siemens s7 300
  • Ошибка secure boot violation invalid signature detected check secure boot policy in setup
  • Ошибка setup was unable to create the directory