我正在尝试将“gender”和“likes_cheeese”字段信息存储在我的模型中,但我似乎这两个值都没有存储在数据库中,因此不会显示在admin中。 有什么建议让它工作并在数据库中显示?
views.py
@login_required(login_url='/users/login/')
def account(request):
context = {}
if request.method == 'POST':
try:
import ipdb
ipdb.set_trace()
full_name = request.POST.get('name')
likes_cheese = request.POST.get('like')
profile_picture = request.POST.get('profile_picture')
sex = request.POST.get('sex')
user_info = request.user.id
user_info = User.objects.get(id=user_info)
try:
user_info_collect = UserProfileInfo.objects.get(user=user_info)
user_info_collect.full_name = full_name
user_info_collect.likes_cheese = likes_cheese
user_info_collect.sex = sex
except UserProfileInfo.DoesNotExist:
user_info_collect = UserProfileInfo(
user=user_info,
full_name=full_name,
likes_cheese=likes_cheese,
profile_picture=profile_picture,
gender=sex)
user_info_collect.save()
context = {'success': True, 'message': 'Successfully saved'}
context.update(csrf(request))
return render_to_response('users/account.html', context)
except:
context = {'success': False, 'message': 'Saving failed'}
else:
context.update(csrf(request))
return render_to_response('users/account.html', context)
模型
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
Boolean_YES_NO_CHOICES = ((None, 'Others'), (True, 'Male'), (False, 'Female'))
GENDER_CHOICES = (('', 'Others'), ('M', 'Male'), ('F', 'Female'))
class UserProfile(models.Model):
user = models.OneToOneField(User)
name = models.CharField(
max_length=255,
blank=False,
null=False,
verbose_name='Name')
email = models.EmailField(
blank=False,
null=False,
verbose_name='Email')
def __unicode__(self):
return self.name
class UserProfileInfo(models.Model):
user = models.OneToOneField(User)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, default='Female')
likes_cheese = models.NullBooleanField(
choices=Boolean_YES_NO_CHOICES,
max_length=3,
blank=True,
null=True,
default=None,)
full_name = models.CharField(
default='',
max_length=255,
blank=True,
null=True)
profile_picture = models.ImageField(
default='',
upload_to='media/Users/',
blank=True,
null=True,
verbose_name='Profile Picture',
help_text='Apna photo dal chutiye.')
def __unicode__(self):
return self.user.username
HTML
{% extends "base.html" %}
{% block content %}
<p>
<h1>Here's what we know about you!</h1>
<strong>Name - </strong>{{account.full_name}}
<strong>Like Cheese - </strong>{{account.likes_cheese}}
</p>
<p>
<form action="/users/account/" method="POST" name="user_account">
{% csrf_token %}
<label>Full Name</label>
<input type="text" name="name" >
<select name="sex">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<label>Profile Picture</label>
<input type="file" name="profile_picture">
<input type='submit' name='submit' value='Save'>
</form>
</p>
{% endblock %}