Django:如果用户之前输入过地址

发布于 2024-11-08 03:09:07 字数 1178 浏览 0 评论 0原文

如果用户之前在登录时未填写表单,我想向他展示一个表单,但如果他之前填写过信息,则将他重定向到主页。 我该如何做到这一点?

这是我的观点:

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模型如下: 类 SongProfile(models.Model): 歌曲 = models.OneToOneField(Song) 因此,当我尝试同时保存歌曲和歌曲配置文件时,其中 Songprofile.song 保存歌曲中创建的记录的最新 ID/PK。这是错误的吗?

I want to present a user with a form if he has not filled it out previously on login but redirect him to the homepage if he has filled in information previously.
How do i accomplish this?

Here's my view:

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)
               )

Am i on the right track here?

Thanks,

ADDITIONAL INFO:

SongProfile and Song are two different models. SongProfile model is as follows:
class SongProfile(models.Model):
song = models.OneToOneField(Song)

so when im trying to save both in song and songprofile where songprofile.song saves the latest id/pk of the record created in song. is this wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

染年凉城似染瑾 2024-11-15 03:09:07

我假设每个用户只有一个 SongProfile 对象。

 try:
    songprofile = SongProfile.objects.get(user=request.user)
    # Render song/show.html
 except SongProfile.DoesNotExist:
   if form.is_valid():
      # Process post

   # Render song/create.html

要使用通过以下形式创建的歌曲创建新的 SongProfile 对象:

 song = form.save()
 songprofile = SongProfile(user=request.user)
 songprofile.song = song
 songprofile.save()

再次编辑

修复了向后的内容并添加了歌曲对象。

I'm assuming there is only one SongProfile object per user.

 try:
    songprofile = SongProfile.objects.get(user=request.user)
    # Render song/show.html
 except SongProfile.DoesNotExist:
   if form.is_valid():
      # Process post

   # Render song/create.html

To create a new SongProfile object with the Song created by the form:

 song = form.save()
 songprofile = SongProfile(user=request.user)
 songprofile.song = song
 songprofile.save()

EDIT AGAIN:

Fixed backwards stuff and added Song object.

茶底世界 2024-11-15 03:09:07

事实上,您可以像 Tim 演示的那样执行 try/catch,这将会起作用。如果您发现在某些情况下开始过滤更多字段或者想要一个合理的默认值,您可以按照文档的建议进行操作并使用 get_or_create() 方法,如下所示

sp, created = SongProfile.objects.get_or_create(user=request.user)

文档

传递给 get_or_create() 的任何关键字参数(称为 defaults 的可选参数除外)都将在 get() 调用中使用。如果找到一个对象,get_or_create() 返回该对象的元组和 False。如果没有找到对象,get_or_create()将实例化并保存一个新对象,返回新对象和True的元组。

因此,布尔值指示是否需要创建对象,您可以使用它来指导方法逻辑。

这种语法也更加简洁和清晰。

至于尝试保存 SongSongProfile ,不,你没有错。正如 Tim 演示的那样,form.save() 创建了新的 songsongprofile.song = Song,然后是 songprofile.save (),保存songprofile的歌曲引用。

代码示例中有几个小错误。一个错误是

if songprofile = null:
    ...

,如果你使用它,正如 @Natim 指出的那样,应该是,

if songprofile is None:
    ...

另一个问题是,

sp = SongProfile

Python 确实会编译该行,但它分配了 SongProfile 类对象引用变量而不是类本身的实例。您通常想要做的是,

sp2 = SongProfile()

这将创建对象实例。如果您执行 dir(sp)dir(sp2),您将看到差异。

You can, indeed, do a try/catch as Tim demonstrated and that will work. If you find that you are, in some cases, beginning to filter more fields or that you want a sensible default, you can do as the docs suggest and use the get_or_create() method, like so:

sp, created = SongProfile.objects.get_or_create(user=request.user)

From the docs:

Any keyword arguments passed to get_or_create() -- except an optional one called defaults -- will be used in a get() call. If an object is found, get_or_create() returns a tuple of that object and False. If an object is not found, get_or_create() will instantiate and save a new object, returning a tuple of the new object and True.

So the Boolean value indicates if the object needed to be created or not and you can use it to guide method logic.

This syntax, too, is a little briefer and cleaner.

As far as trying to save both Song and SongProfile, no, you're not wrong. As Tim demonstrated, form.save() creates the new song and songprofile.song = song, followed by the songprofile.save(), saves the songprofile's song reference.

There are a couple of small errors in the code example. One error is,

if songprofile = null:
    ...

which, were you to use it, as @Natim noted, should be,

if songprofile is None:
    ...

Another problem is in the line,

sp = SongProfile

which Python will, indeed, compile, but which assigns the SongProfile class object reference to the variable and not an instance of the class itself. What you want to do normally would be,

sp2 = SongProfile()

and that will create the object instance. If you do a dir(sp) and dir(sp2), you'll see the difference.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文