简体   繁体   English

Django-无法让用户作为ForeignKey正常工作

[英]Django - Can't get User as ForeignKey to work

I am building a Django site to share code for Python games, but I'm running into trouble associating each game with a specific user. 我正在建立一个Django网站来共享Python游戏代码,但是在将每个游戏与特定用户相关联时遇到了麻烦。 I'm trying to do this by using the user as the ForeignKey , which I think is the right approach, but I can't get the user to actually get inserted into the database without using some weird hack (like passing the user as a string into a hidden user field, which is totally insecure and causes other issues.) 我正在尝试通过将用户用作ForeignKey来执行此操作,我认为这是正确的方法,但是如果不使用一些怪异的技巧(例如将用户作为字符串输入到隐藏的user字段中,这是完全不安全的,并会导致其他问题。

My Game class looks like this: 我的Game类如下所示:

class Game(models.Model):
    user = models.ForeignKey(User, blank=True)
    title = models.CharField(max_length=256)
    image = models.ImageField(upload_to='games')
    description = models.CharField(max_length=256)
    requirements = models.CharField(max_length=256)
    code = models.CharField(max_length=256000)

    def __unicode__(self):
        return self.title

The form for adding a game: 添加游戏的形式:

class GameForm(forms.ModelForm):

    image = forms.ImageField(required=False)
    code = forms.CharField(widget=PagedownWidget(show_preview=True))

    class Meta:
        model = Game
        fields = ('user','title','image','description','requirements','code')

User.game = property(lambda u: Game.objects.get_or_create(user=u)[0])

I create a custom version of this form in my addgame.html template: 我在我的addgame.html模板中创建了此表单的自定义版本:

<form action="/userprofile/addGame/" method="post">{% csrf_token %}
    {% for field in form.visible_fields %}
        <div class="fieldWrapper">
            {{ field.errors }}
            {{ field.label_tag }}
            <br>
            {{ field }}
            <br><br>
        </div>
    {% endfor %}
    <input type="submit" value="Save">
</form>

My View looks like this: 我的视图如下所示:

@login_required
def add_game(request):
    user = request.user
    error_message = None

    if request.method == 'POST':
        form = GameForm(request.POST)
        if form.is_valid():
            form = form.save(commit=False)
            form.uploader = request.user
            form.save()
            return HttpResponseRedirect('/userprofile')
        else:
            error_message = "Invalid Input"
    else:
        form = GameForm()

    args = {}
    args.update(csrf(request))
    args['user'] = user
    args['form'] = form
    args['error_message'] = error_message

    return render_to_response('addgame.html', args)

However, I get the following error: 但是,出现以下错误:

Cannot assign None: "Game.user" does not allow null values. 无法分配无:“ Game.user”不允许使用空值。

I realize that a User instance has not been passed into the form, thus I am getting a 'shouldn't be null' error, but I have no idea how to properly pass in the User instance to the form. 我意识到User实例尚未传递到表单中,因此出现“不应为空”错误,但是我不知道如何正确地将User实例传递给表单。 I've looked at several questions on this exact issue, such as this , but I still haven't been able to get User successfully passed in to the form. 我已经看过有关此确切问题的几个问题,例如this ,但仍然无法使User成功传递到表单中。

Problem 1: 问题一:

form.uploader = request.user

Should be: 应该:

form.user = request.user

I dont see uploader attribute in your Game model 我没有在您的游戏模型中看到上uploader属性

Problem 2: 问题2:

In the GameForm Meta class, the following line should not include a user field: GameForm Meta类,下面的行应该包括user字段:

fields = ('title','image','description','requirements','code')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM