【发布时间】:2011-05-18 05:57:45
【问题描述】:
如果用户之前没有在登录时填写过,我想向他展示一个表单,但如果他之前填写过信息,我想将他重定向到主页。 我如何做到这一点?
这是我的看法:
def makinginfo(request):
form = SongForm(request.POST or None)
songprofile = SongProfile.objects.get().filter(user=request.user)
if songprofile = null: IS THIS RIGHT?
if form.is_valid():
form.save()
sp = SongProfile
sp.song = form.pk
sp.save()
if 'next' in request.POST:
next = request.POST['next']
else:
next = reverse('index_show')
return HttpResponseRedirect(next)
return render_to_response(
'song/create.html',
{'form':form},
context_instance = RequestContext(request)
)
else:
return render_to_response(
'song/show.html',
context_instance = RequestContext(request)
)
我在正确的轨道上吗?
谢谢,
附加信息:
SongProfile 和 Song 是两个不同的模型。 SongProfile 模型如下:
class SongProfile(models.Model):
song = models.OneToOneField(Song)
因此,当我尝试同时保存歌曲和歌曲配置文件时,其中歌曲配置文件保存了歌曲中创建的记录的最新 id/pk。这是错的吗?
【问题讨论】:
-
1) 您不需要
.get()。让它只是SongProfile.objects.filter(user=request.user)2)null在 Python 中不存在。等价于None,但您只需检查if songprofile:3) 一般而言,一对一关系仅在您需要向不受控制的模型添加信息时才值得。如果您同时控制两者,SongProfile上的字段应该继续Song。 4)您缺少最后一个render_to_response上的数据字典参数,如果您不需要任何东西,请传递一个空字典({})。
标签: django django-templates django-forms django-views