Django模型不通过ForeignKey将自己与User相关联

时间:2013-12-24 17:25:31

标签: django django-models django-forms django-views

我的问题是关于模型,模型和实例。在做了一些故障排除后,我认为我的问题是UserFile的用户字段没有将自己与auth.User关联,或者modelform没有通过auth.User的实例。错误发生在动态路径 - file_destination - 当我尝试self.user时,它无法找到用户:/

# Model

class UserFile(models.Model):
    user = models.ForeignKey('auth.User', related_name='user_file', primary_key=True, unique=True)
    user_file = models.FileField(upload_to=file_destination, null=True)

    def __unicode__(self):
        return self.user_file.name

# View 

def login_index(request):
    template = 'loginIndex.html'
    context = Context()
    if request.user.is_authenticated():
        if request.method == 'POST':
            form = UserUpload(request.POST, request.FILES, instance=request.user)
            context.update({'form': form})
            if form.is_valid() and form.is_multipart():
                instance = UserFile(user_file=request.FILES.get('user_file'))
                instance.save()     
        else:
            form = UserUpload()
            context.update({'form': form})
        return render(request, template, context)

    else:
        return render(request, template, context)

# Form

class UserUpload(ModelForm):
    user_file = forms.FileField(required=False, widget=forms.ClearableFileInput, label='Upload')

    class Meta:
        model = UserFile
        fields = ['user_file']

    def clean_user_file(self):
        check_user_file = self.cleaned_data.get('user_file')
        if check_user_file:
            if check_user_file.size > 5120000:
                raise ValueError('File is too big for upload')
        return check_user_file

# The problem arises when I submit the instance, which saves the file from the form to upload_to=file_destination
# In file_destination I get an error on self.user.username saying || DoesNotExist at "" UserFile has no user.
# My self.user is an None object.

def file_destination(self, filename):
    filename = name_generator()
    url = "%s/%s/%s" % (self.user.username, 'uploads' ,filename)
    return url

1 个答案:

答案 0 :(得分:0)

您需要在user实例上手动设置UserFile字段:

if form.is_valid():
    instance = form.save(commit=False)
    instance.user = request.user
    instanve.save()
    form.save_m2m()  # add this if you add m2m relationships to `UserFile`

此外,在表单处理成功后重定向是个好主意:

from django.shortcuts import redirect
# ...
return redirect("view-name")