gpt4 book ai didi

python - Django 使用从模型填充的数据加载表单

转载 作者:行者123 更新时间:2023-12-01 06:41:34 28 4
gpt4 key购买 nike

我正在使用Python(3.7)和Django(2.3)开发一个项目,其中我通过扩展基本用户模型实现了多种类型的用户,现在我需要创建一个UserEdit页面以允许工作人员编辑一个用户。

这是我的模型:

class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=254, unique=True)
name = models.CharField(max_length=255)
title = models.CharField(max_length=255, choices=TITLE, blank=False)
user_type = models.CharField(max_length=255, choices=USER_TYPE, blank=False)
gender = models.CharField(max_length=255, choices=CHOICES, blank=False)
contenst = models.CharField(max_length=255, blank=True, null=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
last_login = models.DateTimeField(null=True, blank=True)
date_joined = models.DateTimeField(auto_now_add=True)
email_status = models.CharField(max_length=50, default='nc')

USERNAME_FIELD = 'email'
EMAIL_FIELD = 'email'
REQUIRED_FIELDS = ['password']

objects = UserManager()

def get_absolute_url(self):
return "/users/%i/" % (self.pk)

def __str__(self):
return str(self.email)


class PersonalBelow18(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='profile')
dob = models.DateField(blank=False)
customer_id = models.IntegerField(blank=False, verbose_name='Connect other User')
collection_use_personal_data = models.BooleanField(blank=False)
reference_identities = models.ForeignKey(Identities, blank=False, on_delete=models.CASCADE, related_name='refs')

def __str__(self):
if self.user.email is None:
return "ERROR-CUSTOMER NAME IS NULL"
return str(self.user.email)

GRAPPELLI_AUTOCOMPLETE_SEARCH_FIELDS = {
"myapp": {
"MyFile": ("user__email__icontains",)
}
}


class PersonalAbove18(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
dob = models.DateField(blank=False)
customer_id = models.IntegerField(blank=False, verbose_name='Connect other User')
contact_email = models.EmailField(max_length=255, blank=False)
reference_identities = models.ForeignKey(Identities, blank=False, on_delete=models.CASCADE)
contact_no = PhoneNumberField(blank=True, null=True, max_length=13,
help_text='Phone number must be entered in the'
'format: \'+999999999\'. Up to 13 digits allowed.')

collection_use_personal_data = models.BooleanField(blank=False)

def __str__(self):
print(type(self.user.email))
if self.user.email is None:
return "ERROR-CUSTOMER NAME IS NULL"
return str(self.user.email)


class ContactPerson(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
contact_email = models.EmailField(blank=False)
customer_id = models.BigIntegerField(blank=True)
contact_no = PhoneNumberField(blank=True, null=True, help_text='Phone number must be entered in the'
'format: \'+999999999\'. Up to 15 digits allowed.')
collection_use_personal_data = models.BooleanField(blank=False)


class GroupContact(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
contact_email = models.EmailField(blank=False)
customer_id = models.BigIntegerField(blank=False)
contact_no = PhoneNumberField(blank=True, help_text='Phone number must be entered in the'
'format: \'+999999999\'. Up to 15 digits allowed.')
department = models.CharField(max_length=255, blank=False)
address = models.CharField(max_length=255, blank=False)

这是我的表格:

class UserForm(UserCreationForm):
class Meta:
model = User
fields = ('email', 'name', 'password1', 'password2', 'title',
'gender', 'contenst', 'user_type')

class Below18Form(forms.ModelForm):
class Meta:
model = PersonalBelow18
widgets = {'dob': DateInput()}
fields = ('dob', 'customer_id', 'collection_use_personal_data')

class Above18Form(forms.ModelForm):
class Meta:
model = PersonalAbove18
widgets = {'dob': DateInput()}
fields = ('dob', 'customer_id',
'contact_email',
'contact_no', 'collection_use_personal_data')

class UserCPForm(forms.ModelForm):
class Meta:
model = ContactPerson
fields = ('contact_email', 'contact_no', 'collection_use_personal_data')

class GroupContactForm(forms.ModelForm):
class Meta:
model = GroupContact
fields = ('contact_email', 'contact_no', 'department', 'address')

这是MultiModelForm我曾经组合过多种形式:

这是我的观点:

class EditUserDashboard(generic.DetailView):
def get(self, request, *args, **kwargs):
id = self.kwargs['id']
try:
u = User.objects.get(id=id)
print(u.user_type)
u_form = UserForm(request.POST, instance=u)
if u.user_type == 'PB':
p = PersonalBelow18.objects.get(user_id=id)
p_form = Below18Form(request.POST, instance=p)
return render(request, 'dashboard/user_edit.html', {'u_form': u_form,
'p_form': p_form,
'u': u})
elif u.user_type == 'PA':
p = PersonalAbove18.objects.get(user_id=id)
p_form = Above18Form(request.POST, instance=p)
return render(request, 'dashboard/user_edit.html', {'u_form': u_form,
'p_form': p_form,
'u': u})
elif u.user_type == 'ContactPerson':
p = ContactPerson.objects.get(user_id=id)
print(p.user.id)
p_form = UserCPForm(request.POST, instance=p)
return render(request, 'dashboard/user_edit.html', {'u_form': u_form,
'p_form': p_form,
'u': p})
elif u.user_type == 'GC':
p = GroupContact.objects.get(user_id=id)
p_form = GroupContactForm(request.POST, instance=p)
return render(request, 'dashboard/user_edit.html', {'u_form': u_form,
'p_form': p_form,
'u': u})
else:
print('something else')
except Exception as e:
print(e)
pass

Update: My HTML form:

<form action="" method="post" class="form">
{% csrf_token %}
{{ u_form|crispy }}
{{ p_form|crispy }}
<button type="submit" class="btn btn-primary" value="update">Update</button>
</form>

当我加载编辑页面时,它返回错误如下:

'ContactPerson' object is not subscriptable

Internal Server Error: /dashboard/user/10/edit Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response "returned None instead." % (callback.module, view_name) ValueError: The view dashboard.views.EditUserDashboard didn't return an HttpResponse object. It returned None instead. [21/Dec/2019 20:07:16] "GET /dashboard/user/10/edit HTTP/1.1" 500 53502

最佳答案

您可以尝试以下操作:

p = ContactPerson.objects.get(user__id=id)  # instead of user_id=id

p = ContactPerson.objects.get(user=u)

关于python - Django 使用从模型填充的数据加载表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59436066/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com