Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recover data from a Django Form

It’s my first time doing a Django Form challenge.
The challenge for now is just from a HTML Template get the last_name information and store into DB from views. So I have a scenario below:

models.py:

class Person(models.Model):
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)

an HTML template, I will put below only the form part:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

      <form action="{% url 'store' %}" method="post">
        {% csrf_token %}
        <div class="form-group row">
          <label for="last_name" class="col-sm-2 col-form-label">Last Name</label>
          <div class="col-sm-10">
            <input type="text" class="form-control" id="last_name" placeholder="Last Name">
          </div>
        </div>

        <div class="form-group row">
          <div class="col-sm-10">
            <button type="submit" class="btn btn-primary">Send Last Name</button>
          </div>
        </div>
      </form>

And the views.py itself… I created a InsertLastName ModelForm to store the data from the form, but didn’t work. For some reason, when I tryed to call form.cleaned_data I reveived an error about the is_valid() verification. Seens like that I’m not getting the information from label.

class InsertLastName(forms.ModelForm):
    class Meta:
        model = Person

        fields = ['last_name']
        exclude = ['first_name']

def index(request):
    persons = Person.objects.all()
    context = {'persons': persons}
    return render(request, '/index.html', context)

def store(request):
    form = InsertLastName(request.POST or None)
    print(form.cleaned_data['last_name'])

    return HttpResponse("Storing a new Last Name object into storage")

What is the correct way to get the information from last_name label in my form?
I’m following that documentation and coding from a challenge template.

>Solution :

Your just set attr name for your input html tag
Example:

<input type="text" name="first">

And for get input in function store in view.py:

request.POST.get("first")

Add this to your html template in your form

{{persons}}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading