models.py
class UserProfile(models.Model):
user = models.OneToOneField(User)
phone_daytime = models.CharField(max_length=50, null=True, blank=True)
class User(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.CharField(max_length=75)
password = models.CharField(max_length=75)
views.py
def profile(request):
""""""
registerform = UserRegisterForm(request.POST)
createprofileform = UserCreateProfileForm(request.POST)
if registerform.is_valid() and createprofileform.is_valid():
result = registerform.save(commit=False)
result.set_password(request.POST['password'])
result.save()
member.user_id = user.id
member.member_id = result.id
member.save()
member_profile = UserProfile.objects.get(user=result.id)
createprofileform = UserCreateProfileForm(request.POST, instance=member_profile)
createprofileform.save()
return render(request,'profile.html',{'createprofileform':createprofileform,'registerform':registerform})
查看将数据保存到数据库。
模板
<tr>
<td>First name:</td><td>{{registerform.first_name}}</td>
</tr>
<tr>
<td>Last name:</td><td>{{registerform.last_name}}</td>
</tr>
<tr>
<td>Daytime phone:</td><td>{{createprofile.phone_daytime}} </td>
</tr>
<tr>
<td>Email:</td><td>{{registerform.email}} </td>
</tr>
<tr>
<td>Password</td><td>{{registerform.password}} </td>
</tr>
保存的名称和电子邮件ID显示在这样的模板中,
<td> <input type="submit" name="delete" value="{{list.0.id}}" class="delete_reporter" /></span>
<a href="{{list.0.id}}">{{list.0.first_name|title}} {{list.0.last_name}}</a></td>
<td> {{list.0.email}} {{list.1.phone_daytime}} {{list.1.phone_mobile}}</td>
在模板中,如果我点击<a href="{{list.0.id}}">{{list.0.first_name|title}} {{list.0.last_name}}</a>
表单应该以可编辑模式打开,那么如果我想进行更改,我可以更改并再次保存。如何在django中执行此操作。我正在传递id在<a>
标记中。
答案 0 :(得分:0)
如果我理解你是正确的,你想要某种数据,可以编辑和保存。 你可以借助表格来实现这个目标。这是一个例子:
定义表单:
class BasicForm(forms.Form):
name = forms.CharField()
age = forms.IntegerField()
然后,在您的视图中定义您的逻辑并为您的表单提供初始数据:
def update_view(request):
initial_data = {'name': 'John', 'age': 25}
form = BasicForm(initial_data)
if request.method == 'POST':
form = BasicForm(request.POST)
if form.is_valid():
# Do something with passed data, for example update existing model.
pass
return render(request, 'template.html', {'form': form})
如果您想在数据库中更新模型,可以提供如下的初始数据:
from django.forms.models import model_to_dict
model = Model.objects.get(name='John')
initial_data = model_to_dict(model, exclude=['field_name'])
form = BasicForm(initial_data)
if request.method == 'POST':
form = BasicForm(request.POST)
if form.is_valid():
# Update your "John" model
model.name = form.cleaned_data['name']
model.age = form.cleaned_data['age']
model.save()