首页 > 解决方案 > 从Django中的数据库中填充外键字段的输入字段

问题描述

我使用foreignkey模型的字段作为 html 表单中的输入字段,因为如果数据库中不存在该值,我需要用户输入。所以我只是给了一个输入标签,在视图中我取值并将其分配给表单字段。现在,如果已经创建了用户配置文件,那么密码值将在那里。如何使用数据库中的值预填充 html 中的输入字段?

profile.html

<form method="POST" id="userProfileForm" enctype="multipart/form-data">
   {% csrf_token %}
   .
   .
   .
   <div>
     <label for="input_pincode">Pincode</label>
     <input id="input_pincode" type="text" name="input_pincode">                
  </div><br>
  .
  .
  .
</form>

模型.py

class UserProfile(models.Model):
    .
    .
    .
    pincode = models.ForeignKey(Pincode, models.SET_NULL, blank=True, null=True)

表格.py

class UserProfileUpdateForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(UserProfileUpdateForm, self).__init__(*args, **kwargs)
        for visible in self.visible_fields():
            visible.field.widget.attrs['class'] = 'form-control'

    class Meta:
        model = UserProfile
        fields = ['pincode', other_fields]

视图.py

def profile(request):
    if request.method == 'POST':
        u_form = UserUpdateForm(request.POST, instance=request.user)
        up_form = UserProfileUpdateForm(request.POST, request.FILES, instance=request.user.userprofile)
        if u_form.is_valid() and up_form.is_valid():
            u_form.save()
            uncommitted_up_form = up_form.save(commit=False)
            if request.POST['city']:
                pin = Pincode.objects.get_or_create(city_id=request.POST['city'], pincode=request.POST['input_pincode'])[0]
                uncommitted_up_form.pincode = pin

            #other logic
            uncommitted_up_form.save()
            messages.success(request, f'Your profile has been updated!')
            return redirect('profile')

在 html 文件中,我想userprofile.pincode.nameinput_pincode框中显示 的值。我怎样才能做到这一点?

标签: django

解决方案


这是一个如何userprofile.pincode.nameinput_pincode框中显示值的示例。你可以这样试试。

在views.py中

name = userprofile.pincode.name
return render(request, "profile.html", {"name ": name }) OR return render(request, 
"profile.html", {"name ": userprofile.pincode.name})

在 HTML 模板中

<form method="POST" id="userProfileForm" enctype="multipart/form-data">
 {% csrf_token %}
 <div>
 <label for="input_pincode">Pincode</label>
 <input id="input_pincode" value="{{name}}" type="text" name="input_pincode">                
 </div><br>
</form>

推荐阅读