【问题标题】:Cannot assign "'1'": "Groups.profile" must be a "Profile" instance无法分配“'1'”:“Groups.profile”必须是“Profile”实例
【发布时间】:2021-08-11 18:36:13
【问题描述】:

我有具有实例模型用户的配置文件模型。我正在尝试使用表单创建组。那个组模型有 Profile 模型作为实例,那么我该如何选择经过身份验证的用户自动创建组,我很困惑......

这是我的组模型

class Groups(models.Model):
profile = models.ForeignKey(Profile, related_name='my_groups', on_delete=models.CASCADE)
groups_name = models.CharField(max_length=150)
slug = models.SlugField(max_length=150, unique=True)
cover_pic = models.ImageField(upload_to='images/groups/', null=True, blank=True)
type_group = models.CharField(max_length=150)
created_date = models.DateTimeField(auto_now_add=True)
about_group = models.TextField(max_length=600)
members = models.ManyToManyField(Profile,through="GroupMember")

def __str__(self):
    return self.groups_name

这是我的个人资料模特

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
slug = models.SlugField(max_length=100, unique=True)
profile_pic = models.ImageField(upload_to='images/user/profile/', null=True, blank=True)
cover_pic = models.ImageField(upload_to='images/user/profile/', null=True, blank=True)
user_bio = models.TextField(null=True,blank=True, max_length=255)
designation = models.CharField(blank=True,null=True, max_length=255)
education = models.CharField(blank=True, null=True, max_length=255)
marital_status = models.CharField(blank=True, null=True, max_length=60)
hobbies = models.CharField(blank=True, null=True, max_length=500)
location = models.CharField(blank=True, null=True, max_length=500)
mobile = models.IntegerField(blank=True, null=True)

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

这是创建组的表格

class GroupCreateForm(forms.ModelForm):
class Meta:
    model = Groups
    fields = ('cover_pic', 'profile', 'groups_name', 'type_group', 'about_group')

profile = forms.CharField(widget=forms.TextInput(attrs={
    'class': 'form-control input-group-text',
    'value':'',
    'id':'somesh',
    'type': 'hidden',


}))

这是创建组 html 文件

this is html page

this is error..

【问题讨论】:

标签: python django


【解决方案1】:

您已在表单中为个人资料设置了CharField。当您将数据发送到此表单时,它会尝试使用 FK 将 Group 记录创建为 CharField 例如“1”,这会给您错误,因为您应该将 Profile 对象传递给 Group

取决于你到底想要什么,有一些选择。

您可以使用ModelChoiceField。阅读https://docs.djangoproject.com/en/3.2/ref/forms/fields/#django.forms.ModelChoiceField

或者您可以使用Inline FormSet 并在https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets 中阅读相关信息

还有Creating a model and related models with Inline formsetsInline FormSet 的示例

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-18
    • 1970-01-01
    • 2011-02-22
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多