Form Entry not getting updated to be used for Next Form

So I have this new Problem where I submit data into on form and redirect to another form.
in the Forms.py file of the second form I use a queryset function to fetch the last data from the model that I filled just in the first form .
This is not happening for me and the data I get is the last entry that was already in the model before I refreshed the server
I want the second form to fetch the latest entry without refreshing or restarting the server

Below is the Code for the Two forms

First Form

d1s1choice = []
plnm = day1.objects.values_list('d1sight' , flat= True).last()
print(plnm)
z = place.objects.all()
for x in z:
    # y = "('" + x.placeName + "',)"
    y = x.placeName
    

    if plnm == y:
        print (plnm + y)
        d1s1choice.append((x.point1,x.point1))

View

@login_required
def bday1(request):
    q = request.session['qs']
    nquery = q + 1
    day = 1
    formd1 = buildday1(request.POST or None, request.FILES or None)
    place_obj = place.objects.all()
    content ={
        "query" : q,
        "nquery" : nquery,
        "formd1" : formd1,
        "place_obj" : place_obj,
        "day": day
    }
    if day != q:

        if formd1.is_valid():
            print (request.POST)
            formd1.save()
            x = formd1.cleaned_data['code']
            content['formd1'] = buildday1()
            request.session['x']=x
            return redirect("/itnry/buildd1s")
            
    
    return render(request, "itnry/buildday1.html", context=content)

@login_required
def bd1s1(request):
    q = request.session['qs']
    x = request.session['x']
    nquery = q + 1
    day = 1
    initiald1s = {'code': x}
    formd1s = buildday1s(request.POST or None, request.FILES or None, initial= initiald1s)
    place_obj = place.objects.all()
    
    content ={
        "query" : q,
        "nquery" : nquery,
        "formd1s" : formd1s,
        "place_obj" : place_obj,
        "x": x,
        "day": day
    }
    if day != q:

        if formd1s.is_valid():
            print (request.POST)

            formd1s.save()
            content['formd1s'] = buildday1s()
            return redirect("itnry/buildday2.html")
    
    return render(request, "itnry/buildd1s.html", context=content)

Briefly, it doesn’t work that way.

If you do a redirect, that tells the browser to request a different page. You’re not directly passing control from one view to the next. So at that point, any data that you want to keep for the next view must be stored somewhere - either in session or the database.

If you’re looking to do something like a wizard, you might want to look at Django formtools - that’s what we use.

What other way can i use other than Redirect.

Once i refresh / reload the server the new entry gets updated

Ok, clearly I’m missing something here.

Please post the complete forms involved.

Form One
this is the first form that gets loaded . Here I select a particular Value for d1sight

class buildday1(forms.ModelForm):
    d1sight = forms.ChoiceField(choices= choice1, required= False)
    n1stay = forms.ChoiceField(choices= choice2, required= False)
    
    class Meta:
        model = day1
        fields = ['code','d1arrive','d1to','d1sight','n1stay']

Second Form
here I grab the value of d1sight and match it with similar entry
then I pull the complete object where one of the entry matches d1sight

d1s1choice = []
plnm = day1.objects.values_list('d1sight' , flat= True).last()
print(plnm)
z = place.objects.all()
for x in z:
    y = x.placeName
    

    if plnm == y:
        print (plnm + y)
        d1s1choice.append((x.point1,x.point1))
      

class buildday1s(forms.ModelForm):
    d1s1 = forms.MultipleChoiceField( choices= d1s1choice,widget=forms.CheckboxSelectMultiple(), required=False, label='show')
    class Meta:
        model = day1sightseeing
        fields = ['code','d1s1']

this works only when I go back to the shell and refresh the server and then reloading the HTML page.

as I can see this problem can be solved in two ways

  1. passing the latest value without refreshing the server .
  2. or knowing how to refresh a server with django code or function.

I lack proficiency in both the ways.
Critical help required.

Please post the complete forms involved - starting with and including the class statement.

(Specifically, I’m wondering what class this block of lines belongs in:

d1s1choice = []
plnm = day1.objects.values_list('d1sight' , flat= True).last()
print(plnm)
z = place.objects.all()
for x in z:
    y = x.placeName
    

    if plnm == y:
        print (plnm + y)
        d1s1choice.append((x.point1,x.point1))
      

this block of code is outside all the classes

Ok, you don’t do that in django.

Code that exists at the module level only executes once, and that’s when the module is loaded.

All “functional” code that you write - especially code that needs to access the database - should reside in a class or function.

alright I did , as you mentioned.
and put the code in the

class buildday1s(forms.ModelForm):

still no effect , does the same thing

This code should reside within a function within the class.

Again, you’ve got a similar situation. Code at the class level is only executed when the Class is defined.

I suggest you take some time and read the docs at 9. Classes — Python 3.11.1 documentation (You can safely skip sections 9.1 and 9.2 and start with 9.3) If you’re going to be successful with Django, you will need to be very familiar with Python classes.

will that solve the problem I’m having ?
I mean if I create a function for the code

I used a method and called it inside the same class and inside the view
While the method called inside the class had the same problem
But the method inside the view calls the correct values
To my understanding functions inside views.py
Run not at the beginning of the program but when you redirect to it.
Now my problem is that i dont know how i can fetch the values from Views.py to forms.py
Any solution to it ?

When having questions about code, please post the code being discussed. It’s too easy to create misunderstandings about specific code when you’re working with descriptions of that code.

Please be more specific with your question. What are you trying to do? (Frequently, this type of question comes up when someone is trying to do things “backwards”, so it will be helpful to understand what the exact situation is.)

def runn1():
        
        d1s1choice = []

        plnm = day1.objects.values_list('d1sight' , flat= True).last()
        print(plnm)
        z = place.objects.all()
        for x in z:
            # y = "('" + x.placeName + "',)"
            y = x.placeName
            

            if plnm == y:
                print (plnm + y)
                d1s1choice.append((x.point1,x.point1))

                print (d1s1choice)
                
                c1 = forms.MultipleChoiceField( choices= d1s1choice,widget=forms.CheckboxSelectMultiple(), required=False, label='')
                
                return c1

this is the new function I introduced
in the code

now it looks like this

class buildday1s(forms.ModelForm):

def runn1():
        
        d1s1choice = []

        plnm = day1.objects.values_list('d1sight' , flat= True).last()
        print(plnm)
        z = place.objects.all()
        for x in z:
            # y = "('" + x.placeName + "',)"
            y = x.placeName
            

            if plnm == y:
                print (plnm + y)
                d1s1choice.append((x.point1,x.point1))

                print (d1s1choice)
                
                c1 = forms.MultipleChoiceField( choices= d1s1choice,widget=forms.CheckboxSelectMultiple(), required=False, label='')
                
                return c1
d1s1 = runn1()

    class Meta:
        model = day1sightseeing
        fields = ['code','d1s1']

and i added the function in the views as well

this function redirects to the other function

@login_required
def bday1(request):
    q = request.session['qs']
    nquery = q + 1
    day = 1
    formd1 = buildday1(request.POST or None, request.FILES or None)
    place_obj = place.objects.all()
    content ={
        "query" : q,
        "nquery" : nquery,
        "formd1" : formd1,
        "place_obj" : place_obj,
        "day": day
    }
    if day != q:

        if formd1.is_valid():
            print (request.POST)
            formd1.save()
            buildday1s.runn1()
            
            x = formd1.cleaned_data['code']
            content['formd1'] = buildday1()
            request.session['x']=x
            return redirect("/itnry/buildd1s")
            
    
    return render(request, "itnry/buildday1.html", context=content)
@login_required
def bd1s1(request):
    q = request.session['qs']
    x = request.session['x']
    nquery = q + 1
    day = 1
    initiald1s = {'code': x}

    formd1s = buildday1s(request.POST or None, request.FILES or None, initial= initiald1s)
    place_obj = place.objects.all()
    
    content ={
        "query" : q,
        "nquery" : nquery,
        "formd1s" : formd1s,
        "place_obj" : place_obj,
        "x": x,
        "day": day
    }
    if day != q:

        if formd1s.is_valid():
            print (request.POST)

            formd1s.save()
            buildday1s.runn1()
            content['formd1s'] = buildday1s()
            return redirect("itnry/buildday2.html")
    
    return render(request, "itnry/buildd1s.html", context=content)

now I want is
buildday1s.runn1()
to update the value for the select box in the forms.py before displaying

Side note: It appears that you may have a copy/paste error in your class buildday1s definition in that your def runn1 is not indented.

You need to take a step back here. You’re starting to blend different issues and mechanics.

1 - Your form fields don’t change as a result of adding this code. Change your form back to its original definition. You do not try to define the field within the function.

2 - In your choices attribute, you supply the name of the runnable - the function name.

did that still the same thing is happening
but in the terminal

SonmargSonmarg
[('Visit Fish Point (Union Taxi required)', 'Visit Fish Point (Union Taxi required)')]
[26/Jan/2023 23:10:47] "POST /itnry/buildday1 HTTP/1.1" 302 0
[26/Jan/2023 23:10:47] "GET /itnry/buildd1s HTTP/1.1" 200 2911

the values are correctly displayed but not in the form

Again, post the current form code. (Only the form, we don’t need to see the view)

class buildday1s(forms.ModelForm):


    def runn1():
        d1s1choice = []
 
        plnm = day1.objects.values_list('d1sight' , flat= True).last()
        print(plnm)
        z = place.objects.all()
        for x in z:
            # y = "('" + x.placeName + "',)"
            y = x.placeName
            

            if plnm == y:
                print (plnm + y)
                d1s1choice.append((x.point1,x.point1))
                print (d1s1choice)
                c1 = d1s1choice
               
                return c1
  d1s1 = forms.MultipleChoiceField( choices= runn1(),widget=forms.CheckboxSelectMultiple(), 
  required=False, label='')

class Meta:
        model = day1sightseeing
        fields = ['code','d1s1']


It should be choices=runn1, not choices=runn1().

In the first form you’re passing the runnable. In the second form (what you currently have), you’re calling the function at the time that the field is being defined, and using those results in the definition.

You’re also doing a lot of unnecessary work in that function. You’re manually iterating over the place model trying to find those entries where placeName is the name retrieved by your day1 query. You should use a filter on that query to only retrieve the values you need.

1 Like

this solved my problem .
regarding the .filter , yes I wanted to use it but the number of lines will be almost the same