Home > Net >  I'm a newbie to python/Django and getting a value error and no http response error. Please can
I'm a newbie to python/Django and getting a value error and no http response error. Please can

Time:01-11

ValueError at /update_department/14 The view management.views.update_department didn't return an HttpResponse object. It returned None instead.

Request information USER admin

GET No GET data

POST Variable Value csrfmiddlewaretoken 'XLqZBPhMKImvlfgWsNLeN1Ei8nz5u1HJ15IvAQV4JNwVMeG31rhDOD1q9PJuwXmz' department_code '15' department_name_e
'Finance' department_name_l
'Finance' parent_code '' submit
''

These are the details.I don't know why is there error here while all the posted data is right.also the form is not updating.

Models:

class Departments(models.Model):
    department_code = models.CharField(db_column='Department_Code', primary_key= True,  max_length=20, db_collation='SQL_Latin1_General_CP1_CI_AS')  # Field name made lowercase.
    department_name_e = models.CharField(db_column='Department_Name_E', max_length=50, db_collation='SQL_Latin1_General_CP1_CI_AS')  # Field name made lowercase.
    department_name_l = models.CharField(db_column='Department_Name_L', max_length=50, db_collation='SQL_Latin1_General_CP1_CI_AS')  # Field name made lowercase.
    parent_code = models.CharField(db_column='Parent_Code', max_length=20, db_collation='SQL_Latin1_General_CP1_CI_AS')  # Field name made lowercase.
    is_active = models.BooleanField(db_column='Is_Active')  # Field name made lowercase.
    created_by = models.IntegerField(db_column='Created_By')  # Field name made lowercase.
    created_date = models.DateTimeField(db_column='Created_date')  # Field name made lowercase.
    modified_by = models.IntegerField(db_column='Modified_By')  # Field name made lowercase.
    modified_date = models.DateTimeField(db_column='Modified_date')  # Field name made lowercase.

    class Meta:
        db_table = 'Departments'
        unique_together = (('department_code'),)
    def __str__(self):
        return str("self.department_name_e") or ''




View:


@login_required
def update_department(request, department_code):
    dep_up = Departments.objects.get(department_code=department_code)
    if request.method == "POST":
        form = DepartmentsForm(request.POST, instance = dep_up)
        if form.is_valid():
            department_code = form.cleaned_data['department_code']
            department_name_e = form.cleaned_data['department_name_e']
            department_name_l = form.cleaned_data['department_name_l']
            parent_code = form.cleaned_data['parent_code']
            obj = form.save(commit = False)
            obj.is_active = True
            obj.created_by = request.user.id
            obj.created_date = datetime.today()
            obj.modified_by = request.user.id
            obj.modified_date = datetime.today()
            obj.save()
            return HttpResponseRedirect('department_list')



forms:



class DepartmentsForm(forms.ModelForm):
    class Meta:
        model = Departments
        fields = ['department_code','department_name_e','department_name_l','parent_code']



HTML:





{% extends 'base.html' %}

{% block title %}Update Company{% endblock title  %}

{% block body %}
<div style="margin-left:22%" >
  <h2 ><strong>Company:</strong></h2><br><br>

  <form  action="{%url 'update_company' comp_up.company_code  %}" method="post">
    {% csrf_token %}

    <div style="margin-left:20%;margin-right:20%" >
  <input type="text" value="{{comp_up.company_code}}"  id="company_code"  name="company_code" placeholder="Company Code" required>
  <label style="margin-left:15px" for="company_code">Company Code</label>
  </div>
  <br>

  <div style="margin-left:20%;margin-right:20%" >
  <input type="text" value="{{comp_up.company_name_e}}"  id = "company_name_e" name="company_name_e" placeholder="Enter Company" required>
  <label style="margin-left:15px" for="company_name_e">Company Name English</label>
  </div>
<br>

  <div style="margin-left:20%;margin-right:20%" >
  <input type="text" value="{{comp_up.company_name_l}}"  id = "company_name_l" name="company_name_l" placeholder="Enter Company" required>
  <label style="margin-left:15px" for="company_name_e">Company Name Local</label>
  </div>
<br>

  <div style="margin-left:20%;margin-right:20%" >
    <input type="tel" value="{{comp_up.tel}}"  id = "tel" name="tel" placeholder="Telephone Number" required>
    <label style="margin-left:15px" for="tel">Telephone Number</label>
  </div>
<br>

  <div style="margin-left:20%;margin-right:20%" >
  <input type="tel" value="{{comp_up.fax}}"  id = "fax" name="fax" placeholder="Enter Fax"required>
  <label style="margin-left:15px" for="fax"> Fax Number</label>
  </div>
<br>

  <div style="margin-left:20%;margin-right:20%" >
    <textarea name="address"   rows="4" cols="100" placeholder="Address" required>{{comp_up.address}}</textarea>
    <label style="margin-left:15px" for="address">Address</label>
  </div>
<br>

  <div style="margin-left:20%;margin-right:20%" >

    <select  name="country_id" required>

      <option value="{{comp_up.country_id.id}}" >{{comp_up.country_id.country_name_e}}</option>
      {% for con in country %}
      <option value="{{con.id}}" >{{con.country_name_e}}</option>
      {% endfor %}
    </select>

  </div>
  <br>

    <label style = "margin-left:21%; " for="logo">Logo</label>
  <div  >
  <input value="{{comp_up.}}" style = "margin-left:21%;" accept="image/*" type="file" name="logo" onchange="loadFile(event)"  required> <br>
  <img style = "margin-left:21%;" id="output" >
  <script>
    var loadFile = function(event) {
      var output = document.getElementById('output');
      output.src = URL.createObjectURL(event.target.files[0]);
      output.onload = function() {
        URL.revokeObjectURL(output.src) // free memory
      }
    };
  </script>

  </div>
<br><br>

  <center>
  <button type="submit"  name="submit">Update</button>&nbsp;
  <button type="button"  onclick="window.location.href = '{%url 'company_list'%}'" name="cancel">Cancel</button>

  </center>

  
</form>


</div>

{% endblock body %}

CodePudding user response:

You have provided HttpReponse only for POST and valid form. You should give the standard response (with empty form) for fresh entries or posting with errors. Like this:

@login_required
def update_department(request, department_code):
    dep_up = Departments.objects.get(department_code=department_code)
    if request.method == "POST":
        form = DepartmentsForm(request.POST, instance = dep_up)
        if form.is_valid():
            ...
            return HttpResponseRedirect('department_list')
    form = DepartmentsForm()
    return render(request, 'template.html', context={'form': form})

CodePudding user response:

You are not handling what will happen in case of form is not valid or there is a GET request to render the form. You can update the view like this:

def update_department(request, department_code):
    ...
    if request.method == "POST":
        form = DepartmentsForm(request.POST, instance = dep_up)
        if form.is_valid():
           ...
        else:
            return render(request, 'template.html', context={'form': form})
   else:
       return return render(request, 'template.html', context={'form': DepartmentsForm(instance=dep_up)})

And for rendering form errors, you can update your html code like this:

{% for field in form %}
    <div >
        {{ field.errors }}
        {{ field.label_tag }} {{ field }}
    </div>
{% endfor %}

More information on form errors can be found in documentation.

  • Related