简体   繁体   中英

In Django, how do I access template values in the views.py?

I'm fairly new to Django and I'm working on a page that takes in user information. If all of the information is correct, it will proceed to the next page. However, if the user does not provide all given info, it will to refresh the page. My problem is that there are quite a bit of fields the user has to fill out and if the person misses any fields, I don't want them to have to re-type everything out. So my workaround for it is that in the views.py I created a dictionary and it populates it with the input names in the template. However, when I go to run the code, it gives me an error saying that the values in my dictionary do not exist. I'm now thinking that my dictionary is not actually accessing any of the template values.

Here is my template:

<!DOCTYPE html>
{% extends "Checklist/base.html" %}
{% block main_content %}
{% load static %}
  <html>
    <body>

      <form action="{% url 'Checklist:signin_check' %}" method="post">
        {% csrf_token %}
        <ul style="list-style-type:none">
        <li>
          <label for="driver_first_name">Driver First Name:</label>
            <input type="text" name="driver_first_name" value="" id="driver_first_name">
        </li>
        <li>
          <label for="driver_last_name">Driver Last Name:</label>
            <input type="text" name="driver_last_name" value="" id="driver_last_name">
        </li>
        <li>
          <label for="driver_wwid">Driver WWID:</label>
            <input type="text" name="driver_WWID" value="" id="driver_WWID" maxlength="8"
              onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57">
        </li>

        <li>
          <label for="co_driver_first_name">CO-Driver First Name:</label>
            <input type="text" name="co_driver_first_name" value="" id="co_driver_first_name">
        </li>
        <li>
          <label for="co_driver_last_name">CO-Driver Last Name:</label>
            <input type="text" name="co_driver_last_name" value="" id="co_driver_last_name">
        </li>
        <li>
          <label for="co_driver_wwid">CO-Driver WWID:</label>
            <input type="text" name="co_driver_WWID" value="" id="co_driver_WWID" maxlength="8"
              onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57">
        </li>
      <li>
        <input type="submit" value="Continue">
      </li>
      </ul>
      </form>

    </body>
  </html>
{% endblock %}

Here is the views.py:

def signin_check(request):
    driver_info_model = Driver()
    if request.method == "POST":
        driver_info_form = Driver_Form(request.POST)
        c = {'driver_first_name':driver_first_name, 'driver_last_name':driver_last_name,
            'driver_WWID':driver_WWID, 'co_driver_first_name':co_driver_first_name,
            'co_driver_last_name':co_driver_last_name, 'co_driver_WWID': co_driver_WWID,}
        if driver_info_form.is_valid():
            driver_info_form.save()
            return render(request, 'Checklist/checklist.html')
    template = loader.get_template('Checklist/signin.html')
    return HttpResponse(template.render(c, request))

any feedback would be greatly appreciated. Thanks!

Im not 100% sure as i'm fairly new to Django myself, but from what i've done previously you can get the POST data from the request that is passed in, like this:

request.POST['driver_first_name']

which raises an error if no data is present or from

request.POST.get('driver_first_name', 'optionaldefaultvalue')

which returns None if no data is present in the specified field, or an optional default.

It might also be easier to do what you are after with django's inbuilt forms

However, when I go to run the code, it gives me an error saying that the values in my dictionary do not exist. I'm now thinking that my dictionary is not actually accessing any of the template values.

From your views.py alone I'm guessing the exception you're running into is that you're assigning dictionary values that aren't defined. For example, in 'driver_first_name':driver_first_name , Python is looking for a variable named driver_first_name but you haven't defined it. The data you're looking for, as Justin alluded to, can be found in requests.POST .

One solution, while more verbose, illustrates what needs to be done:

def signin_check(request):
    driver_info_model = Driver()
    if request.method == "POST":
        driver_info_form = Driver_Form(request.POST)
        driver_first_name = request.POST.get('driver_first_name', '')
        driver_last_name = request.POST.get('driver_last_name', '')
        driver_WWID = request.POST.get('driver_WWID', '')
        co_driver_first_name = request.POST.get('co_driver_first_name', '')
        co_driver_last_name = request.POST.get('co_driver_last_name', '')
        co_driver_WWID = request.POST.get('co_driver_WWID', '')
        c = {'driver_first_name': driver_first_name,
             'driver_last_name': driver_last_name,
             'driver_WWID': driver_WWID,
             'co_driver_first_name': co_driver_first_name,
             'co_driver_last_name': co_driver_last_name,
             'co_driver_WWID': co_driver_WWID, }
        if driver_info_form.is_valid():
            driver_info_form.save()
            return render(request, 'Checklist/checklist.html')
    template = loader.get_template('Checklist/signin.html')
    return HttpResponse(template.render(c, request))

My problem is that there are quite a bit of fields the user has to fill out and if the person misses any fields, I don't want them to have to re-type everything out.

To address your second concern you'll need to deal with your HTML template. Your input fields have a value of "" , so any value you pass through your context is not going to reach any of them. Luckily you're on the right path and you're quite close, so all you need to do is fill those values in. For example:

<li>
    <label for="driver_first_name">Driver First Name:</label>
    <input type="text" name="driver_first_name" value="{{ driver_first_name }}" id="driver_first_name">
</li>

Note that {{ driver_first_name }} is referencing the driver_first_name that's being passed into the context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM