用数据库数据预填充编辑表单字段

时间:2018-10-09 13:38:11

标签: django django-forms django-views

首先,我想说我是Django的新手,但是我非常喜欢它。 Atm我正在尝试建立一个简单的银行帐户管理网站。我已经完成了注册,视图,用户限制(已记录用户,匿名用户),用户自定义(密码更改,编辑个人资料信息)。我停在最后一个。问题是,每当我使用编辑配置文件url时,编辑配置文件表单(EditProfileForm)都不会在输入框Edit Profile

中显示当前字段值

如您所见,尽管数据库中有值,但这些字段为空(我可以通过管理页面或自定义ProfileView进行检查)

models.py

class UserProfile(models.Model):

username_validator = UnicodeUsernameValidator()

username = models.CharField(_('username'),
    max_length=20,
    unique=True,
    help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
    validators=[username_validator],
    error_messages={
        'unique': _("A user with that username already exists."),
    },)
password = models.CharField(_('password'), max_length=128, default='')
first_name = models.CharField(_('first name'), max_length=30)
last_name = models.CharField(_('last name'), max_length=150)
email = models.EmailField(_('email address'))
card_nr = models.CharField(max_length=16, default='')
location = models.CharField(choices=CHOISE_LOCATIONS, max_length=20, default='')
phone_number = models.CharField(_('phone number'), max_length=10, default='')
bank_account = models.CharField(_('bank account'), max_length=20, default='')


EMAIL_FIELD = 'email'
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']


def __str__(self):
    return self.username

def create_profile(sender,** kwargs):     如果kwargs ['created']:         user_profile = UserProfile.objects.create(username = kwargs ['instance'])

post_save.connect(create_profile,sender = User)

forms.py

class EditProfileForm(forms.ModelForm):

first_name = forms.CharField(max_length=20)
last_name = forms.CharField(max_length=20)
email = forms.EmailField(required=True)
card_nr = forms.CharField(widget=forms.TextInput(attrs={'pattern': r'^[0-9]+$'}), max_length=16)
location = forms.ChoiceField(choices=CHOISE_LOCATIONS)
phone_number = forms.CharField(widget=forms.TextInput(attrs={'pattern': r'^[0-9]+$'}), max_length=10)

class Meta:
    model = UserProfile
    fields = [
        'first_name',
        'last_name',
        'email',
        'card_nr',
        'location',
        'phone_number',
    ]

views.py

def edit_profile(request):
if request.method == 'POST':
    form = EditProfileForm(request.POST)

    if form.is_valid():
        first_name = form.cleaned_data['first_name']
        last_name = form.cleaned_data['last_name']
        email = form.cleaned_data['email']
        phone_number = form.cleaned_data['phone_number']
        location = form.cleaned_data['location']
        card_nr = form.cleaned_data['card_nr']

        #BANK ACCOUNT CREATION
        bank_id = 'RO' + (str(ord(first_name[0])) + str(ord(first_name[-1])))[-2:] + \
                        'BANK' + (str(ord(first_name[0])) + str(ord(first_name[-1])))[:3] + \
                        (str(ord(last_name[0])) + str(ord(last_name[-1])))[:3] + (card_nr[:3]) + (card_nr[-3:])
        #-------------------------

        user = User.objects.get(username=request.user.username)
        user_profile = UserProfile.objects.get(username=user)
        user_profile.first_name = first_name
        user_profile.last_name = last_name
        user_profile.email = email
        user_profile.phone_number = phone_number
        user_profile.location = location
        user_profile.card_nr = card_nr
        user_profile.bank_account = bank_id
        user_profile.save()
        return HttpResponseRedirect(reverse('accounts:view_profile'))
else:
    form = EditProfileForm(instance=request.user)

    args = {'form':form}
    return render(request, 'accounts/edit_profile.html', args)

让我知道我是否缺少任何东西。我尝试过通过更改视图表单,添加id和实例来实现:

def edit_profile(request, id):
instance = get_object_or_404(UserProfile, id=id)
form = EditProfileForm(instance=instance)
if request.method == 'POST':
    form = EditProfileForm(request.POST, instance=instance)

编辑: edit_profile.html

{% block body %}
<div class="container">
    <br>
        <form method="post" action="{% url 'accounts:edit_profile' %}">
            {% csrf_token %}
            {{ form.as_p }}
            <button type="submit">Submit</button>
        </form>
</div>
{% endblock %}

0 个答案:

没有答案