django - 从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.name
在input_pincode
框中显示 的值。我怎样才能做到这一点?
解决方案
这是一个如何userprofile.pincode.name
在input_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>
推荐阅读
- r - 在 R 中的一个图上绘制每个(分类)组的多个测量值
- node.js - 当我尝试安装 Angular 软件包时,我收到了 npm 基金警告:
- c# - C# 客户端请求从 PHP 脚本获取加密图像
- python - 在python中导入包含重载打印函数的自定义模块生成属性错误
- native - 本地构建时,Openhtml to pdf 会弄乱 pdf 显示
- sql-server - 尝试在 SQL 的 While 循环中每次迭代将 TINYINT 递增 1
- android - 如何检查在android中按下后退按钮的次数
- php - 在 Centos 7.8 上安装 php 7.4 的包错误问题
- python - Python数据帧矢量化for循环
- docker - Docker 容器 Evee 渲染中的 Blender 背景