django-extra-views用于多对多关系

时间:2019-04-14 21:26:57

标签: django many-to-many django-class-based-views formset inline-formset

使用Django额外视图-Django Extra Views

我有一个表格,技能模型与个人资料有多对多关系。

我得到的错误是

Unknown field(s) (title) specified for Skill_profile

我以使用exclude的方式使其工作。

class ProfileSkillInline(InlineFormSetFactory):
        model = Skill.profile.through
        exclude = ['id']

然后它开始工作-如何在不使用exclude = ['id']的情况下正确使用具有多对多关系的表单集-我在Django 2.2中知道,我需要使用fieldsexclude-但如果我使用fields = ['title']-它给我一个错误,所以我使用exclude并选择了一个我不需要的随机字段-但这不是正确的方法-这就是为什么我想知道。

我已使用Django手册进行了适当的操作-Django MTM Relationship

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    full_name = models.CharField(max_length=50, blank=True)
    description = models.TextField(blank=True)
    avatar = models.ImageField(blank=True)

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

    def get_absolute_url(self):
        return reverse('profile')


class Skill(models.Model):
    profile = models.ManyToManyField(Profile, related_name='skills', blank=True)
    title = models.CharField(max_length=100, blank=True)

    def __str__(self):
        return self.title

views.py

class ProfileSkillInline(InlineFormSetFactory):
    model = Skill.profile.through
    fields = ['title']


class SkillInline(InlineFormSetFactory):
    model = Skill
    inlines = [ProfileSkillInline]
    # fields = ['title']
    # initial = [{'title': 'Enter Skill'}]
    factory_kwargs = {'extra': 1, 'max_num': None,
                  'can_order': False, 'can_delete': True}
    prefix = 'skill_formset'


class ProfileUpdateView(UpdateWithInlinesView):
    model = Profile
    inlines = [ProfileSkillInline, ProjectInline]
    fields = ['full_name', 'description', 'avatar']
    template_name = 'profile_edit.html'

    def get_queryset(self):
        return Profile.objects.get(user=self.request.user)

    def get_object(self, queryset=None):
        return self.get_queryset()

0 个答案:

没有答案