python - 通过 GET 发送时发送到 django 表单的请求对象正常,但通过 POST 发送时为空
问题描述
我正在尝试将请求用户发送到 Django 表单,问题是,当我通过 GET 方法发送对象时,Django 表单可以正常接收,但是当我通过 POST 方法发送对象时,请求对象始终为空,这是代码:
***************Views.py
class CreateRec(BaseView):
template_name = 'test/rec.html'
def get(self, request, **kwargs):
rec_form = RecForm(req_ses = request)
return render(request, self.template_name,{
'rec_form': rec_form, 'f_new': True,
})
def post(self, request, **kwargs):
user_rec = User.objects.get(username = request)
profile = profile_models.RecProfile.objects.get(cnxuser = user_rec)
form = RecForm(request.POST, request.FILES, req_ses = request)
return render(request, self.template_name,{
'rec_form': rec_form, 'f_new': True,
})
***********Form.py文件的片段:
class RecForm(forms.ModelForm):
def __init__(self, req_ses = None, *args, **kwargs):
super(RecForm, self).__init__(*args, **kwargs)
self.req_ses = kwargs.pop('req_ses', None)
user_rec = User.objects.get(username = req_ses.user)
profile = profile_models.RecProfile.objects.get(cnxuser = user_rec)
通过 GET,req_ses 有对象,通过 POST 它说 req_ses 它是 None ......知道为什么吗??,我也尝试发送 user_rec 对象但得到相同的结果......
解决方案
不需要req_ses
参数和所有额外的工作来找到request.user
,因为HttpRequest
对象具有user
属性。
这是您的代码,经过一些简化,有望解决问题:
表格.py:
class RecForm(forms.ModelForm):
def __init__(self, *args, user=None, **kwargs):
instance = profile_models.RecProfile.objects.get(cnxuser=user)
super(RecForm, self).__init__(*args, instance=instance, **kwargs)
视图.py:
class CreateRec(BaseView):
template_name = 'test/rec.html'
def get(self, request, **kwargs):
rec_form = RecForm(user=request.user)
return render(request, self.template_name,{
'rec_form': rec_form, 'f_new': True,
})
def post(self, request, **kwargs):
form = RecForm(request.POST, request.FILES, user=request.user)
return render(request, self.template_name,{
'rec_form': rec_form, 'f_new': True,
})
更新
class RecForm(forms.ModelForm):
def __init__(self, *args, user=None, **kwargs):
print('args: {}'.format(args))
print('kwargs: {}'.format(kwargs))
print('user: {}'.format(user))
instance = profile_models.RecProfile.objects.get(cnxuser=user)
super(RecForm, self).__init__(*args, instance=instance, **kwargs)
推荐阅读
- django - 使用 celery 和 docker 进行开发
- spring-kafka - 如何在 Spring Cloud Stream 中使用 useNativeEncoding=true 测试绑定
- r - R:tableplot 中的错误:if (by < 1) stop("'by' must be > 0") 中的错误
- angular - 在角度 6 中创建管道时出错
- jmeter - 将 VSTS Web 测试转换为 JMeter 脚本
- c# - Google.Apis.Auth.OAuth2.Responses.TokenResponseException:invalid_grant,机器人被禁用
- c# - 在 Windows 锁定之前截取屏幕截图
- excel - 定位图表
- c# - 为开发创建新的 ASPNETCORE_ENVIRONMENT
- sql - 如何使用 select 语句将单个列的值放入临时表中?