无法分配" 42":" Event.user_id"必须是"用户"例

时间:2016-10-18 06:07:24

标签: django python-2.7

我已经检查了与我的问题相关的所有解决方案,但没有人工作,我有一个事件表,我在其中分配用户的ID。事件模型是

def create_new_event(request, steps):
if request.method == 'POST':
    if(steps=="step_1"):
        stepFirstForm = CreateEventStepFirstForm(request.POST)
        if stepFirstForm.is_valid():
            eventStepFirst = Event(
                user_id = request.user.id,
                event_auth_id = uuid4(),
                event_title = request.POST['event_title'],
                ticket_title = request.POST['ticket_title'],
                category = request.POST['categories'],
                event_summary = request.POST['event_summary'],
                event_information = request.POST['event_information'],
                restriction = request.POST['restrictions'],
                notification_email = request.POST['notification_email'],
                notification_frequency = request.POST['email_frequency']
            )

我正在从视图中分配登录的用户ID

Cannot assign "42": "Event.user_id" must be a "User" instance.    

但是它给了我错误

{{1}}

2 个答案:

答案 0 :(得分:1)

ForeignKey字段期望User类型的对象,而不是用户ID。尝试将作业user_id = request.user.id更改为user_id = request.user。将字段重命名为“user”也可能有意义,以避免将来出现混淆。

答案 1 :(得分:1)

问题在于此代码:

    def create_new_event(request, steps):
    if request.method == 'POST':
        if(steps=="step_1"):
            stepFirstForm = CreateEventStepFirstForm(request.POST)
            if stepFirstForm.is_valid():
                eventStepFirst = Event(
                    user_id = request.user.id,
                    event_auth_id = uuid4(),
                    event_title = request.POST['event_title'],
                    ticket_title = request.POST['ticket_title'],
                    category = request.POST['categories'],
                    event_summary = request.POST['event_summary'],
                    event_information = request.POST['event_information'],
                    restriction = request.POST['restrictions'],
                    notification_email = request.POST['notification_email'],
                    notification_frequency = request.POST['email_frequency']
                )

取代" user_id = request.user.id"您应该使用" user_id = request.user"或" user_id = request.user.username"因为在现场

  user_id=models.ForeignKey(User, on_delete=models.CASCADE)
在事件模型的

中,您将user_id指定为User模型的外键,因此user_id字段需要User实例,而不是request.user.id

感谢。