【发布时间】:2015-12-18 10:05:06
【问题描述】:
我必须将一些数据发送到我有电话对象的数据库。为此,我需要选择所需的电话号码并将所需的信息插入数据库。
要求是显示属于当前登录用户的电话号码。
我使用名为 Phone 的 Django 模型和名为 phoneForm 的 modelForm。
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')
如何正确访问数据库以过滤属于当前用户的 phone_num 值,然后在 phone_num 选项中设置它们?
我的模板是:
<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>
还有我的 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')
【问题讨论】:
-
我现在发布,谢谢您的帮助
-
您使用
CharField作为外键是否有特殊原因?通常我会建议让 Django 自动创建主键。
标签: python django django-models django-forms