Django ORM在尝试使用User时会出现错误

时间:2012-10-14 14:09:36

标签: django django-models

我在Ubuntu 12.04上使用Django 1.4和Python 2.7。

编辑:我正在清除此问题的一些错误部分,因为它似乎重新发生了同样的问题。它运作得非常好 - 我没有做任何改变 - 现在它失败了。怎么了?

这基本上是观点的样子:

@login_required
def request_new_project(request):
    """
    ..  function:: request_new_project()

        Collect information to call the form used to create a new project

        :param request: Django Request object
    """
    user_dict = { 'rsb_username'  : request.user.username}
    form = CreateProject(initial = user_dict)
    data = { 'user' : request.user }
    data.update(csrf(request))
    data.update({ 'form' : form })

    return render_to_response("create_project.html", data)

@login_required
def add_project(request):
    """
    ..  function:: add_project()

        Add a project for the user

        :param request: Django Request object
    """

    if (request.method == "POST"):
        user = User.objects.get(username = request.POST.get('rsb_username'))
        userProfile = UserProfile.objects.get(user = user)

        new_project = Projects(client = userProfile,
                               project_name = request.POST.get('rsb_project_name'),
                               description = request.POST.get('rsb_description'),
                               budget = request.POST.get('rsb_budget'),
                               time_frame = request.POST.get('rsb_time_frame'),
                               time_frame_units = request.POST.get('rsb_time_frame_units'),
                               contact = request.POST.get('rsb_point_of_contact'),
                               contact_email = request.POST.get('rsb_contact_email'),
                               contact_phone = request.POST.get('rsb_contact_phone'),
                               price_quote = 0,
                               eta = 'To Be Determined',
                               current_status = 'Waiting for quote',
                               )
        new_project.save()
        return view_projects(request)

我收到以下错误:

Cannot assign "<UserProfile: UserProfile object>": "Projects.client" must be a "User" instance.

我没有改变模型。

# Create a table for users
class UserProfile(models.Model):
    user = models.OneToOneField(User)

    # Client Info
    company_name = models.CharField(max_length = 200)
    client_type = models.CharField(max_length = 200)
    address1 = models.CharField(max_length = 200)
    address2 = models.CharField(max_length = 200)
    city = models.CharField(max_length = 200)
    state = models.CharField(max_length = 200)
    country = models.CharField(max_length = 200)
    zip_code = models.CharField(max_length = 200)
    phone_number = models.CharField(max_length = 200)

# Create a table to manage project requests
class Projects(models.Model):
    client = models.ForeignKey(User)
    project_name = models.CharField(max_length = 50)
    description = models.TextField()
    budget = models.CharField(max_length = 50)
    time_frame = models.DecimalField(max_digits = 3, decimal_places = 1)
    time_frame_units = models.CharField(max_length = 25)
    contact = models.CharField(max_length = 50)
    contact_email = models.EmailField()
    contact_phone = models.CharField(max_length = 25)
    price_quote = models.DecimalField(max_digits = 10, decimal_places = 2)
    eta = models.CharField(max_length = 200)
    current_status = models.CharField(max_length = 200)

有什么建议吗?

更新1: 从实际数据库中我可以看到rsb_projects约束之一是: rsb_projects_client_id_fkey (client_id) REFERENCE rsb_userprofile (id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED

如果这有帮助......

在我看来,即使我已将ForeignKey中的models.py定义为反对User,数据库也需要UserProfile ID。

思想?

1 个答案:

答案 0 :(得分:2)

错误正是它所说的。

要创建新项目,您需要为项目对象提供用户个人资料对象,而不是用户个人资料ID

   user = User.objects.get(id=7)
   userprofile = user.get_profile()
   project.client = userprofile

请注意,它是userprofile对象,已分配给项目实例的客户端属性。您无法userprofile对象的ID分配给项目实例的客户端属性。

另外,请勿将您的用户ID与您的userprofile ID混淆。它们可能不完全相同。

只要在数据库中创建了新用户,用户标识就是auth_user表中自动生成的主键。 userprofile id是在创建与用户相关的相应用户配置文件时在profiles_userprofile表中自动生成的主键。

换句话说,您的add_project视图功能需要读取类似

的内容
if (request.method == "POST"):
    user = User.objects.get(username = request.POST.get('rsb_username'))
    # userprofile = UserProfile.objects.get(user = user)  <-- we don't need this anymore.

    new_project = Projects(client = user,  # <--- give it a user instance of course now that your model has changed
                           project_name = request.POST.get('rsb_project_name'),
                           description = request.POST.get('rsb_description'),
                           budget = request.POST.get('rsb_budget'),
                           time_frame = request.POST.get('rsb_time_frame'),
                           time_frame_units = request.POST.get('rsb_time_frame_units'),
                           contact = request.POST.get('rsb_point_of_contact'),
                           contact_email = request.POST.get('rsb_contact_email'),
                           contact_phone = request.POST.get('rsb_contact_phone'),
                           )
    new_project.save()

关键是你需要确定原始模型的定义是什么。

如果在您的Project类中,您的客户端属性被指定为FK给User,那么您需要为其提供一个用户对象。

如果在您的Project类中,您的客户端属性被指定为FK到UserProfile,那么您需要为其提供一个userprofile对象。