I have form where I print all of records from table(lets say its 'item' table in database). User can add new items to db using ajax. Data saves to db correct but when I refresh page i don't see new tags in my multi select box.
I thought cache is a problem but it doesn't.
So I have question: Where is a problem that I can see add records correct but when i refresh this same page where every time select all rows from table then i don't see these new records?
I'm using sqlite and it's development server.
Forms.py:
BLANK_CHOICE = (('', '---------'),)
class OrderCreateForm(forms.ModelForm):
tag_from = forms.MultipleChoiceField(label='Tags', choices=OrderItemList.objects.all().values_list('id', 'name'))
tag_to = forms.MultipleChoiceField()
class Meta:
model = Order
fields = ('price', 'client', 'platform')
def __init__(self, request_client_id, *args, **kwargs):
super(OrderCreateForm, self).__init__(*args, **kwargs)
self.fields['platform'].choices = BLANK_CHOICE + tuple(
Platform.objects.filter(client_id=request_client_id).values_list('id', 'name'))
View.py:
@user_passes_test(lambda u: u.is_staff, login_url='/account/login/')
def order_create(request, request_client_id):
dict = {}
dict['form_order'] = OrderCreateForm(request_client_id)
return render(request, 'panel/order/form.html', dict)
The problem is that you are setting the tag_from
choices in the field definition, so the choices are evaluated once when the form first loads. You can fix the problem by setting the choices in the __init__
method instead.
class OrderCreateForm(forms.ModelForm):
tag_from = forms.MultipleChoiceField(label='Tags', choices=())
...
def __init__(self, request_client_id, *args, **kwargs):
super(OrderCreateForm, self).__init__(*args, **kwargs)
self.fields['tag_from'].choices = OrderItemList.objects.all().values_list('id', 'name'))
...
Another option would be to use a ModelMultipleChoiceField
instead of a regular multiple choice field. With a model multiple choice field, Django will evaluate the queryset each time the form is initialised.
class OrderCreateForm(forms.ModelForm):
tag_from = forms.MultipleChoiceField(label='Tags', queryset=OrderItemList.objects.all())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.