django modelForm,只需要保存选中的字段

vfhzx4xs  于 2023-10-21  发布在  Go
关注(0)|答案(2)|浏览(126)

如何在modelForm中仅保存选定字段?文档对我的表单没有帮助:

class ProfileForm(forms.ModelForm):
    class Meta:
        model = CustomUser
       fields = ['avatar', 'firstname', 'lastname',
            'date_of_birth',]

        widgets = {
        'date_of_birth': SelectDateWidget(years=range(1920, 2015)),
        }

我的看法:

def cabinet(request):

    profile_user = CustomUser.objects.filter(pk = request.user.pk)
    profile = CustomUser.objects.get(pk = request.user.pk)
    form = ProfileForm(request.POST, request.FILES or None, instance=profile)

    if request.POST and form.is_valid():
        obj = form.save(commit=False)
        obj.profile_user = CustomUser.objects.get(pk=request.user.pk)
        obj.save()
        return redirect(reverse(cabinet))

    return render(request, 'cabinet.html', 
    {'form':form, 'profile_user': profile_user,}, )

在HTML代码中,它只是:

<form action="{% url 'cabinet' %}" method="post" enctype="multipart/form-data">
            {% csrf_token %}
            {{ form|crispy }}
            <button class="btn btn-default" type="submit">Submit</button>
        </form>

所以,如果我只想改变我的“名称”字段,我保存其他领域的空值。
还有一个问题,在我的头像字段的顶部,我有这个:

文档对这两个问题都没有帮助
UPD我的表单视图:

UPD我的CustomUser模型:

class CustomUser(AbstractBaseUser, PermissionsMixin):

    alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', message='Only                     alphanumeric characters are allowed.')

    username = models.CharField(unique=True, max_length=30, validators=[alphanumeric])

    email = models.EmailField(
    'Email',
    max_length=255,
    unique=True,
    db_index=True
    )
    avatar = models.ImageField(
    'Avatar',
    blank=True,
    null=True,
    upload_to='user/avatar',
    default='user/default.jpg'
    )
    firstname = models.CharField(
    'First name',
    max_length=40,
    blank=True,
    null=True
    )
    lastname = models.CharField(
    'Last name',
    max_length=40,
    blank=True,
    null=True
    )
    date_of_birth = models.DateField(
    'Date of birth',
    blank=True,
    null=True
    )
    register_date = models.DateField(
    'Register date',
    auto_now_add=True
    )
    is_active = models.BooleanField(
    'Active',
    default=True
    )
    is_admin = models.BooleanField(
    'Superuser',
    default=False
    )

    @property
    def is_staff(self):
        return self.is_admin

    def get_short_name(self):
        return self.email

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    objects = UserManager()

    class Meta:
        verbose_name = 'User'
        verbose_name_plural = 'Users'
um6iljoc

um6iljoc1#

在保存cleaned_data之前,您只需要从cleaned_data中删除附加字段。
重新编译save方法,并从那里删除它们,它应该可以正常工作。

class ProfileForm(forms.ModelForm):

    # skip initial details

    def save(self, commit=True):
        self.cleaned_data = dict([ (k,v) for k,v in self.cleaned_data.items() if v != "" ])
        return super(ProfileForm, self).save(commit=commit)
7rfyedvj

7rfyedvj2#

我终于解决了。不需要修改保存()方法。
这里的变化:

def cabinet(request):

    profile_user = CustomUser.objects.filter(pk = request.user.pk)
    profile = CustomUser.objects.get(pk = request.user.pk)

    if request.method == 'POST':
        form = ProfileForm(request.POST, request.FILES or None,     instance=profile)   
        if form.is_valid():
            form.save()
    else:
        form = ProfileForm(instance=profile)

    return render(request, 'cabinet.html', 
    {'form':form, 'profile_user': profile_user, 'rating':rating,}, )

但我仍然有问题与头像部件

相关问题