这是我的models.py
。
from django.db import models
from django.contrib.auth.models import User
class User_data(models.Model):
user_ID = models.CharField(max_length = 20)
name = models.CharField(max_length = 50)
user = models.ForeignKey(User, on_delete = models.CASCADE, null =True)
def __str__(self):
return self.name
这是我的forms.py
from django import forms
from lrequests.models import User_data
class UserForm(forms.ModelForm):
class Meta:
fields = ("name", "user_ID")
model = User_data
这是我的views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import UserForm
from django.shortcuts import render_to_response
from .models import User_data
def get(request):
form_class = UserForm
if request.method == "POST":
form = UserForm(request.POST)
if form.is_valid():
data = form.save(commit = False)
data.user = request.user
form.save()
return HttpResponse("Sucessfully submitted")
else:
form = UserForm()
return render(request, "request_form.html", {'form' : form_class})
#update
def auto_fill_form(request):
form = UserForm(initial = dict(name = request.user.first_name))
context = dict(form=form)
return render(request, "request_form.html", context)
现在,我已经尝试填充在创建帐户时指定的用户数据。因此,他(用户)不会篡改数据(因为它需要是只读的),并且无需用户提供输入即可自动填充数据。我读过django文档,但它仅指定动态初始化数据 see here。我曾尝试将这些代码放入Forms.py中,但没有用。
我什至尝试了HTML模板,但效果也不佳。
{% csrf_token %}
<div class="form-row">
{{ form.name.errors }}
{{ form.name.label_tag }} {{ form.name = user.first_name }}
</div>
{% comment %} {{ form.as_p }} {% endcomment %}
如何默认将数据获取到表单中? 有人可以帮我吗?
答案 0 :(得分:1)
只需更换
else:
form = UserForm()
return render(request, "request_form.html", {'form' : form_class})
作者:
else:
return auto_fill_form(request)