Home > database >  ignore fields on update view
ignore fields on update view

Time:01-11

I have a very large form that I have an update view for. The issue is when the users submits an update it says some fields are required such as author and post date. I don't want users to change these fields. The fields are manually rendered

How can I ignore these fields in the update view.

I have tried to set the requirements to false

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields['author'].required = False
    self.fields['date_posted'].required = False

But this throws a null value in column "author" of relation "blog_post" violates not-null constraint

Alot of posts said to add null=True but these fields cannot be null

view:

class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Post
    form_class = PostFormUpdate
   
    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

    def test_func(self):
        post = self.get_object()
        if self.request.user.id == post.author_id:
            return True
        return False

form:

class PostFormUpdate(ModelForm):
    class Meta:
        model = Post
        fields = '__all__'

CodePudding user response:

you can set blank=True either in model class which will be implemented on all http methods or using the above technique you used

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields['author'].blank = True
    self.fields['date_posted'].blank = True

blank=True means you are not requiring any values from forms for those fields...

CodePudding user response:

This makes it so the user cannot change the form field but it is still displayed

widgets = {
   'date_posted': forms.TextInput(attrs={'readonly':'readonly'}), }


def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields['date_posted'].required = False
  •  Tags:  
  • Related