我正在使用旧版数据库构建一个Django应用程序。我有一个模型LIST,它来自那个遗留数据库,无法真正改变。我也在使用标准的Django用户模型。理想情况下,这就是我想要发生的事情。用户注册,并在重新定向注册后创建新的LIST对象。创建新的列表对象后,用户将重定向到包含刚刚创建的LIST对象的数据的视图。一个后续登录,用户被带回包含他们创建的LIST对象的数据的视图。截至目前,我已经扩展了这样的用户模型:
class UserProfile(models.Model):
user = models.OneToOneField(User)
list_id = models.OneToOneField(List, null=True)
def create_profile(sender, instance, created, **kwargs):
if created:
profile, created = UserProfile.objects.get_or_create(user=instance)
post_save.connect(create_profile, sender=User)
我的ListForm看起来像这样:
class ListForm(ModelForm):
error_css_class = 'text-error'
required_css_class = 'text-required'
class Meta:
model = models.List
fields = ('t_handle', 'facebook_id', 'pinterest_id', 'yelp_id', 'foursquare_id', 'yipit_id', )
我的views.py看起来像这样:
def user_signup(request):
if request.method == 'POST':
form = forms.UserSignupForm(data=request.POST)
if form.is_valid():
user = form.save()
g = Group.objects.get(name='test_group')
g.user_set.add(user)
# log user in
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
messages.success(request, u'Welcome to Social FollowUp')
return redirect('user_create')
else:
form = forms.UserSignupForm()
return TemplateResponse(request, 'user_signup.html', {
'form': form,
})
@login_required
@permission_required('')
def user_create(request):
if request.method == 'POST':
list_form = forms.ListForm(request.POST)
if list_form.is_valid():
list_create = list_form.save()
messages.success(request, 'List {0} created'.format(list_create.list_id))
return redirect(reverse('user_dashboard', args=(2,))) # 2 is just an example
else:
list_form = forms.ListForm()
return TemplateResponse(request, 'dashboard/create.html', {'list_form': list_form, })
def user_dashboard(request, list_id):
try:
list_id = models.List.objects.get(pk=list_id)
except models.List.DoesNotExist:
raise Http404
return TemplateResponse(request, 'dashboard/view.html', {'list_id': list_id})
最后我的urls.py包含了这个:
url(r'user/signup/$', views.user_signup, name='user_signup'),
url(r'u/dashboard/(?P<list_id>\d+)/$', views.user_dashboard, name='user_dashboard'),
url(r'u/list/create/$', views.user_create, name='user_create'),
基本上我不知道如何制作我想要发生的事情,发生了。每当用户注册然后创建LIST对象时,list_id都不会保存到我创建的userProfile表中。我甚至不能100%确定我需要那张桌子。有人可以帮帮我吗?
答案 0 :(得分:2)
在user_create
视图
def user_create(request):
if request.method == 'POST':
list_form = forms.ListForm(request.POST)
if list_form.is_valid():
list_create = list_form.save()
messages.success(request, 'List {0} created'.format(list_create.list_id))
up, _ = UserProfile.objects.get_or_create(user=request.user, list_id=list_create)
return redirect(reverse('user_dashboard', args=(2,))) # 2 is just an example
#rest of the code
基本上,您需要做的就是创建一个userprofile对象。