尝试通过管理模型获取当前用户名时出现RelatedObjectDoesntExist错误

时间:2020-05-06 13:48:57

标签: django python-3.x django-models django-forms

这是我的模特

def get_form_path(instance,filename):  
    upload_dir=os.path.join('uploaded',instance.hostname,instance.Class)
    if not os.path.exists(upload_dir):
        os.makedirs(upload_dir)
    return os.path.join(upload_dir,filename)

Class Book(models.Model):

    Name= models.CharField(max_length=100)
    Class= models.CharField(max_length=100)
    Content =models.FileField(upload_to=get_form_path)
    hostname=models.ForeignKey(settings.AUTH_USER_MODEL,blank=True,on_delete=models.CASCADE)  
    def __str__(self):
            return self.Name
    def delete(self, *args, **kwargs):
            self.Content.delete()
            super().delete(*args, **kwargs)

这是form.py

class BookForm(forms.ModelForm):
class Meta:
    model=Book
    exclude=('hostname',)
    fields=('Name','Class','Content')
class BookAdmin(admin.ModelAdmin):
    exclude=('Name','Class','Content',)
    form=BookForm

这是我的admin.py:

class BookAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self, db_field, request, **kwargs):
    if db_field.name == 'hostname':
        kwargs['queryset'] = get_user_model().objects.filter(username=request.user.username)
    return super(BookAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

def get_readonly_fields(self, request, obj=None):
    if obj is not None:
        return self.readonly_fields + ('hostname',)
    return self.readonly_fields

def add_view(self, request, form_url="", extra_context=None):
    data = request.GET.copy()
    data['hostname'] = request.user
    request.GET = data
    return super(NotesAdmin, self).add_view(request, form_url="", extra_context=extra_context)
admin.site.register(Book, BookAdmin)

我没弄错我要去哪里? 完整的错误行是“ upload.models.Book.hostnamee.RelatedObjectDoesnotExist:Book没有主机名 请为此指导我。.谢谢

0 个答案:

没有答案