用户提交表单,并把信息存到数据库中(form)

Posted by 石坤 on 2018-10-23

model.py

1
2
3
4
5
6
7
8
from django.db import models
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
user_number = models.CharField('工号', max_length=20, blank=True)

class Meta(AbstractUser.Meta):
pass

form.py

1
2
3
4
5
6
7
8
from .models import User

class UserForm(UserChangeForm):
class Meta:
model = User
fields = (
'user_number', 'chinese_name', 'department', 'password', 'english_name', 'english_name2', 'english_name3',
'english_name4')

views.py

1
2
3
4
5
6
7
8
9
10
11
12
13
from django.shortcuts import render, redirect, render_to_response
from .forms import UserForm

def edit_profile(request):
if request.method == 'GET':
form = UserForm(instance=request.user)
if request.method == 'POST':
form = UserForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return redirect(to='/web/profile/')
context = {'form': form}
return render(request, 'web/change.html', context)

url.py

1
url(r'^edit_profile/', views.edit_profile, name='change'),

template

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<form method="post">
{% csrf_token %}
<table border="1">
{% for field in form %}
{% if field.label == '密码' %}
<div></div>
{% elif field.label == '论文署名' %}
{{ field }}
{{ field.label }}
{% else %}
<div>
{{ field }}
{{ field.label }}
</div>
{% endif %}
{% endfor %}


</table>
<br>
<button type="submit" type="button" class="btn-info btn-lg">提交</button>
</form>