How to view the value of a selector in Django’s Forms.py?

Asked

Viewed 15 times

0

I have a field that must be validated from a selector that is a foreign key in the model.

py.models

class NyModel1(models.Model):
    field1 = models.CharField(max_length=50)
    description = models.TextField(blank=True)

    def __str__(self):
        return self.field1


class MyModel2(models.Model):
    
    f_field = models.ForeignKey(NyModel1, on_delete=models.PROTECT)
    field2 = models.CharField(max_length=50)

In the template

<select id ="id_field" class="select" name="f_field" required=True>

        {% for value, field in Form.fields.f_field.choices %}
 
          <option value="{{value}}">
              {{field}}
          </option>
        {% endfor %}
      </select>

Forms.py

class Form(forms.ModelForm):

    document = forms.CharField()

    class Meta:
        model = MyModel2
        fields = ['f_field','field2', 'document']

    def clean_document(self):
        doc = self.cleaned_data.get('document')
        f= self.cleaned_data.get('f_field')
        fiedl2 = self.cleaned_data.get('field2')
        
        print("Document: ",doc) 
        print("Field2 : ",fiedl2) # O valor correto aparece
        print("f Field : ",f) # não consigo visualzar o dado aparece None.

        if f == "something one":
            
            #validate document
        else:
            #other action

        return doc

Prints from the Forms:

Document: 12345
Field2 : ", Teste
f Field : None

view. ,py

def MyView(request):

    if request.method == 'POST':
        my_form = MyForm(request.POST)
       
        if my_form.is_valid():
            
            f_field = my_form.cleaned_data['f_field']
            
            print("Value f_field: ", f_field)  # Here it's OK. I can see the value.
           
            return redirect("my_url")
    else:
       my_form = MyForm()
        

    context = {}
    context['Form'] = my_form 
    

    return render(request, "my_app/template.html", context)

In my view I can see the data coming from the selector, but in Forms.py although I can visualize the first two prints, the third (from the selector) appears as None.

How I can visualize the value of a selector in Forms.py to validate a field?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.