I have to send some data to my database where I have a phone object. For this I need to select the desired phone number and insert data to it in the database. A requirement is to display the phone numbers that belongs to the current login user.
In my form I have 3 textInputs and one MultipleChoiceField where the different phone numbers are displayed. My question is: how can I get the selected phone_num instance on my view.py and send it to my form ?
My view.py:
def phone_config(request):
phone = Phone.objects.get(phone_num = 611111111)
phone_nums = Phone.objects.filter(user_id = request.user.id).values_list('phone_num', flat=True)
if request.method == 'POST':
form = phoneForm(phone_nums, request.POST, instance=phone)
if form.is_valid():
form.save()
return redirect(reverse('gracias'))
else:
form = phoneForm(phone_nums, instance=phone)
return render(request, 'heroconfigurer/heroconfigurer.html', {'form': form})
def gracias_view(request):
return render(request, 'heroconfigurer/gracias.html')
My forms.py:
class phoneForm(ModelForm):
class Meta:
model = Phone
fields = ['phone_num', 'num_calls', 'time_btwn_calls', 'psap']
widgets = {'phone_num': Select(attrs={'class': 'form-control'}),
'num_calls': TextInput(attrs={'class': 'form-control'}),
'time_btwn_calls': TextInput(attrs={'class': 'form-control'}),
'psap': TextInput(attrs={'class': 'form-control'})
}
labels = {
'phone_num': ('Select phone number'),
'num_calls': ('Number of calls'),
'time_btwn_calls': ('Time between calls'),
'psap': ('PSAP'),
}
def __init__(self, phone_nums, *args, **kwargs):
super(tcuForm, self).__init__(*args, **kwargs)
self.fields['phone_num'].queryset = Sim.objects.filter(phone_num__in = phone_nums)
You can simply access any field value in you form in form cleaned_data , if the form is valid:
view.py:
def phone_config(request):
phone_nums = Phone.objects.filter(user_id = request.user.id).values_list('phone_num', flat=True)
if request.method == 'POST':
form = phoneForm(request.POST)
if form.is_valid():
phone_num = form.cleaned_data.get('phone_num') # here you get the selected phone_num
phone_obj = Phone.objects.get(phone_num=phone_num)
... # the rest of the view
For more details check accessing-clean-data
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.