【问题标题】:Django serve get-requestsDjango 服务获取请求
【发布时间】:2015-05-20 07:17:36
【问题描述】:

大家好,我对 Django 有点陌生。我想要实现的是一个 URL,我可以通过我的应用程序的 GET 请求访问它,并传递一些值。 我在 Django 中有一个 UserProfile 模型,它与 User 具有 oneToOneField 关系。我想用我的 GET 请求传递电子邮件并用这封电子邮件找到一个用户实例,然后我想再传递两个值,我想与这个用户UserProfile 属性进行比较。
但我不太明白如何实现这一点。这是我所拥有的:

在我看来.py

def check(request):
try:
    email = request.GET.get('email', '')
    osusername = request.GET.get('osusername', '')
    computername = request.GET.get('computername','')
except TypeError:
    return HttpResponseBadRequest()

user = get_object_or_404(User.objects.filter(user__email=email)[0])

在我的 urls.py 中

urlpatterns = patterns('',
url(r'^check/$', 'myapp.views.check'),)

但是我如何比较例如计算机名与该用户的 User.UserProfile.computername?不管我怎么写都是错的。

我的 UserProfile 模型应要求@cmets:

class UserProfile(models.Model):

user = models.OneToOneField(User, related_name='profile')
computername = models.CharField("Computername", max_length=150, blank=False)
osusername = models.CharField("Osusername", max_length=150, blank=False)

【问题讨论】:

  • 你能把你的模型添加到用户资料中吗?

标签: django get nested-attributes


【解决方案1】:

所以get_object_or_404 的语法是错误的。您没有将对象传递给它:它会为您获取对象。所以:

user = get_object_or_404(User, email=email)

现在您已经有了一个 User 实例,并且您想要获取相关的配置文件,所以您可以这样做:

 profile = user.userprofile

或者,如果您不需要实际的用户实例来做其他事情,直接获取配置文件可能更容易:

 profile = get_object_or_404(UserProfile, user__email=email)

现在可以查看相关属性了:

 osusername == profile.osusername
 computername == profile.computername

【讨论】:

    【解决方案2】:

    您需要先通过以下方式检索用户实例:

    try:
        a_user = User.objects.get(email=email)
    except User.DoesNotExist:
        # error handling if the user does not exist
    

    然后,通过以下方式获取对应的UserProfile对象:

    profile = a_user.userprofile
    

    然后,您可以从 UserProfile 对象中获取 osusername 和 computername:

    profile.osusername
    profile.computername
    

    【讨论】:

      【解决方案3】:

      作为@daniel-roseman answer 的补充。

      如果检查相关属性是多个视图的常见任务,那么在您的 UserProfile 模型中创建一个可以执行所需验证检查的方法也是值得的。

      class UserProfile(object):
          # various attributes ...
      
          def check_machine_attributes(self, os_username, computer_name):
              if os_username == self.osusername and computername == self.computername:
                  return True
              return False
      

      在您看来,您可以这样做:

      if profile.check_machine_attributes(osusername, computername):
          # ...
      else:
          # ...
      

      【讨论】:

        猜你喜欢
        • 2023-03-30
        • 2013-05-20
        • 1970-01-01
        • 2021-07-31
        • 2016-12-11
        • 1970-01-01
        • 1970-01-01
        • 2020-09-26
        • 2014-02-05
        相关资源
        最近更新 更多