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 the desired information to the database.
A requirement is to display the phone numbers that belongs to the current login user.
I use Django model named Phone and a modelForm named phoneForm.
class Phone(models.Model):
user = models.ForeignKey(User)
phone_num = models.ForeignKey(Sim, null=True)
imei = models.CharField(max_length=30, primary_key=True)
num_calls = models.CharField(max_length=20, null=True, blank=True)
time_btwn_calls = models.CharField(max_length=20, null=True, blank=True)
psap = models.CharField(max_length=30, null=True, blank=True)
class Sim(models.Model):
phone_num = models.CharField(max_length=30, primary_key=True)
pin = models.CharField(max_length=15)
puk = models.CharField(max_length=15)
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, *args, **kwargs):
super(phoneForm, self).__init__(*args, **kwargs)
self.queryset = Phone.objects.filter(user_id = request.user.id).values('phone_num')
How can I acces the database properly to filter the phone_num values that belongs to the current user and then set them in phone_num choices?
My template is:
<div class="row">
<div class="col-md-6 col-sm-offset-3">
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %} <!-- obligatorio para protegerse de ataques maliciosos -->
{{ form.as_p }} <!-- pasamos la variable form y con as_p conseguimos <p> -->
<button type="submit" class="btn btn-primary">Send to TCU</button>
</form>
</div>
And my view.py:
def phone_config(request):
phone = Phone.objects.get(phone_num=611111111)
if request.method == 'POST':
form = phoneForm(request, request.POST, instance=phone)
if form.is_valid():
form.save()
return redirect(reverse('gracias'))
else:
form = phoneForm(request, instance=tcu)
return render(request, 'heroconfigurer/heroconfigurer.html', {'form': form})
def gracias_view(request):
return render(request, 'heroconfigurer/gracias.html')