python - 如何将活动用户传递给 Django ModelForms
问题描述
在我的表单中,我必须过滤“租户”选择字段,以便它仅显示与活动用户的组织关联的租户。所以我只是将一个额外的参数传递给表单构造函数。当我加载(GET)表单时,这按预期工作。
但是当我提交(POST)表单时,我不断收到以下错误:
AttributeError: 'NoneType' object has no attribute 'organization_profile'
知道这是什么原因吗?
视图.py
def create_booking(request):
if request.method == "POST":
form = BookingCreateForm(data=request.POST)
if form.is_valid():
data = form.cleaned_data
booking = Booking.objects.create(
status=data['status'],
tenant = data['tenant'],
apartment = data['apartment'],
check_in = data['check_in'],
check_out = data['check_out'],
rent = data['rent'],
)
booking.save()
return redirect('dashboard:dashboard')
else:
form = BookingCreateForm(user=request.user)
return render(request, 'accounts/booking_form.html', {'form': form})
表格.py
class BookingCreateForm(forms.ModelForm):
class Meta():
model = Booking
fields = '__all__'
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user',None)
super(BookingCreateForm, self).__init__(*args, **kwargs)
organization = self.user.organization_profile
self.fields['tenant'] = forms.ChoiceField(choices=[
(tenant.id, tenant.name)) for tenant in TenantProfile.objects.filter(organization=organization)
])
模型.py
class Booking(models.Model):
STATUS_OPTIONS = [
(0, 'Pending'),
(1, 'Accepted'),
(2, 'In-tenancy'),
(3, 'Moved-out'),
(4, 'Cancelled'),
]
status = models.PositiveSmallIntegerField(choices=STATUS_OPTIONS, default=0)
tenant = models.ForeignKey('TenantProfile', on_delete=models.CASCADE)
apartment = models.ForeignKey('Apartment', on_delete=models.CASCADE)
check_in = models.DateField(blank=False)
check_out = models.DateField(blank=False)
rent = models.DecimalField(max_digits=6, decimal_places=2, blank=False)
解决方案
您需要在 GET 请求和POST 请求的情况下传递用户,因此:
def create_booking(request):
if request.method == 'POST':
form = BookingCreateForm(data=request.POST, user=self.request.user)
# …
除非tenant
您的Booking
是 a CharField
,否则这将不起作用,您需要使用ModelChoiceField
[Django-doc]。例如:
class BookingCreateForm(forms.ModelForm):
class Meta:
model = Booking
fields = '__all__'
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user',None)
super().__init__(*args, **kwargs)
organization = self.user.organization_profile
self.fields['tenant'].queryset = TenantProfile.objects.filter(
organization=organization
)
注意:您可以使用
@login_required
装饰器 [Django-doc]将视图限制为经过身份验证的用户的视图 。
推荐阅读
- java - 如何在响应式 Web 应用程序中扩展 oauth2 资源服务器提供的安全配置
- r - 使用 group_by 和 dplyr 根据前一个条件计算一个事件的概率
- xml - 如何使用 curl 获取 jenkins config.xml(jenkins 根配置)文件?
- asp.net-core - 使用 ajax 调用 JavaScript 库时,它没有继承到 modal
- scala - spark-submit scala - 具有依赖项的 zip 文件
- android - 2关于CameraX闪烁的问题
- abp - 为 abp-dynamic-form 中的下拉列表扩展实体和配置外键的推荐方法
- android - 如何在android studio中找到未在xml中设置的字符串?
- javascript - Vue 计算属性不会在更新其反应性依赖项时更新
- java - 配置 Spring Boot 日志记录的最佳方法在哪里?在 application.properties 或 xml 文件 (logback-spring.xml) 中?