Form Post creates blank values in Models(&mySql)

Hi, everyone, first post, and it’s about POST

Ok so I’m using crispy forms and the model has many fields say about 15 fields. I only want to show say 10 fields (2 of which are editable). The rest 5 i dont want to show nor want to change the values , the problem is if i dont pass it as hidden fields in crispy forms like below , when i post i lose the value in the fields . I guess i have already solved it with hidden fields like below but really is there a better way as i dont want to do that. Meaning no hidden fields i just display 10 out of 15 post 10 and rest 5 fields reamins as it

Part of the code snippet showing having to pass hidden fields into cripy forms
Div (

       Div (Field('Facility', type="hidden")),

        Div (Field('DueDate', type="hidden"))

        Div (Field('Discipline', type="hidden")),

        Div (Field('Subcdisipline', type="hidden")),

Welcome!

When you say you only want to show 10 fields, are the other fields still defined in the form and just not being displayed? Or are you saying that you’re removing those fields from the form?

I think we’re going to need to see your view and more details about the form and what you’re doing with it.

Hi, Ken

Yes i only want to show 10 fields (out of 15) , but when i do that with crispy forms , i lose information in the remaining 5. So the workaround i had was having hidden fields in the crispy form (5 hidden and 10 displayed) . So to your question yes i had to define it (that was the solution but seems messy having so many hidden fields all around). The views I’ve kept it simple below to give you an idea. Just part of the view posted here - its using mixin class. Thank you

class ApproveItemsMixin(UpdateView)
def form_valid(self,form):

   if (self.request.POST.get('Next')): 

        return super().form_valid(form)

Sorry, partial information here isn’t sufficient. For us to see where the problem might be, we’re going to need to see the complete view - and possibly the form as well (not sure about that yet.)

ok here goes for view that has the main class below, it returns the form and hence saves the items on the form. The problem is i have to fit all 15 fields onto form (5 as hidden). Was just wondering if there is a better way when you return it just saves the 10 fields and ignores the 5. Without those hidden fields it overwrites those 5 fields to blank.

class ApproveItemsMixin(UpdateView,ListView, SingleObjectMixin):

template_name = "userT/actionupdateapproveaction.html" #yhs changed to all small letters 

form_class = ApproverForm

success_url = '/ApproverList/'

def get(self, request, *args, **kwargs):

    #uses pk key to automatically get objext

    self.object = self.get_object(queryset=ActionItems.objects.all())

    return super().get(request, *args, **kwargs)

def get_object(self,queryset=None):

    queryset=ActionItems.objects.all()

    return queryset.get(id=self.kwargs['pk'])

def form_valid(self,form):

        #if form is valid just increment q series by 1 so it goes to Approver que so it goes to next queSeries

    if (self.request.POST.get('Reject')):

            

        context = {

                    'StudyActionNo' : form.instance.StudyActionNo

            }

        return HttpResponseRedirect(reverse ('RejectReason', kwargs={'forkeyid': form.instance.id})) #this is key as wanted another screen on the first reject

    if (self.request.POST.get('Cancel')):

       return HttpResponseRedirect('/ApproverList/')

    if (self.request.POST.get('Approve')): 

            #  need another intermediate screen for approval no comments


        return super().form_valid(form)

    if (self.request.POST.get('Pullback')):

        return super().form_valid(form)

    if (self.request.POST.get('Delete')): 

            #  need another intermediate screen for approval no comments

        AttachmentID = self.request.POST.get ('filepk') # hidden file that holds ID of the attachment

        ActionItemID = form.instance.id

        Status = Attachments.mdlDeleteAttachment.mgrDeleteAttachmentbyID(AttachmentID)

        return redirect('ActioneeFormMixin' , pk=ActionItemID)

    if (self.request.POST.get('Next')): 

        return super().form_valid(form)

I think we’ll need to see the form.

Quick answer - there’s no reason to define fields that aren’t going to be used. Or, in the case of a ModelForm, you can exclude fields from the form and they won’t be adversely affected.

On another note:

I wouldn’t expect this mix of classes to work well. UpdateView and ListView aren’t designed to be combined. Also, UpdateView already inherits from SingleObjectMixin - that makes it superfluous.

If you want to combine a form with a list, you probably want to base your page on an UpdateView and create the list yourself.

Ok thanks,let me clean up and test with a simpler mixin; the short answer helped as it maybe points to the forms . Not sure but …eventhough in the layout ive defined the fields to be used exactly but maybe the issue was with the fields= ‘all’?

class CommonLayout (Layout):

def __init__(self, *args, **kwargs):

    super().__init__(

        

        Div(

        Div(Field('StudyActionNo',readonly=True),  style="font-family: Dancing Script", css_class='col-md-2'), 

        Div (Field('StudyName',readonly=True),  css_class='col-md-3'),

        Div (Field('ProjectPhase', readonly=True), css_class='col-md-3'),

        Div (Field('InitialRisk', readonly=True), css_class='col-md-2'),

        Div (Field('ResidualRisk', readonly=True), css_class='col-md-2'),

        #Div (Field('QueSeries', readonly=True), css_class='col-md-3'),

       #-somehow not working Div (Field('DueDate', readonly=True), css_class='col-md-2'),

        css_class='row',

                  

       ),

        Div (

        Div (Field('Guidewords', rows=1 ,readonly=True), css_class='col-md-5'),

        Div (Field('Deviation', rows=1 ,readonly=True), css_class='col-md-5'),

        Div (Field('Revision', rows=1 ,readonly=True), css_class='col-md-2'),

        Div (Field('Cause', rows=8 ,readonly=True), css_class='col-md-12'),

        Div (Field('Safeguard', rows=8, readonly=True), css_class='col-md-12'),

        #Div (Field('Consequence',rows=8, readonly=True,style="font-family: Great Vibes;font-size: 60px"), css_class='col-md-12'), - Left this commented as it shows how to add style to text box directly

        Div (Field('Consequence',rows=8, readonly=True), css_class='col-md-12'),

        Div (Field('Recommendations',rows=8, readonly=True), css_class='col-md-12'),

        css_class='row',#-dont know why i have to put this in so it aligns to left

        

        ),

#needs these hidden fields otherwise it passes blank values into the model- need to see if can do some other way

        Div (

            

        Div (Field('Facility', type="hidden")),

        Div (Field('DueDate', type="hidden")), #yhs added for testing duedate gone missing upon submission

        Div (Field('Disipline', type="hidden")),

        Div (Field('Subdisipline', type="hidden")),

        Div (Field('Organisation', type="hidden")),

       Div (Field('QueSeries', type="hidden")),



        ),

    )

class frmUpdateActioneeForm(forms.ModelForm):

def __init__(self, *args, **kwargs):

    super(frmUpdateActioneeForm, self).__init__(*args, **kwargs)

    self.helper = FormHelper(self)

    self.helper.form_show_labels = True

    self.helper.form_method = 'POST'

    self.fields['Response'].required = True #yhs added. now response is compulsory. need to test if upload empty sheets. what will happen?

    #self.helper.add_input(Submit('Upload', 'Next...', css_class='btn btn-outline-dark float-right col-md-1'))

    #self.helper.add_input(Submit('Cancel', 'Cancel', css_class='btn btn-outline-dark float-right col-md-1'))

    self.helper.layout = Layout(

    CommonLayout(),

    

    Div (

            

        Div ('Response', required=True, css_class='col-md-12'),#YHS Testing

        #Div ('Attachment', css_class='col-md-12'),

        Div ('FutureAction', css_class='col-md-12'),

        css_class='row',

        ),

  

    )

class Meta:

    model = ActionItems

    fields = '__all__'

Yes, if you define all fields in the form, the form must handle all fields. If you don’t want to handle all fields, either list the fields you want or exclude the ones you don’t want.