1

I'm new to Django and Python and I want to be able to edit a database record with a model form. It is frustrating as I know I've missed something that will be obvious but I've spent hours trying to work out what it is. I've looked at some posts and they give me an idea but I've missed something in the reading.

I'm running Windows 10 desktop, python 3.7. The closest post to what I'm trying to do is this one but I'm still missing something. how to edit model data using django forms (what should the XXX look like in the recommended answer)

I've tried various combinations of pk in my_get_name with no success.

I appreciate any help and guidance for yourselves.

The error I get is:

NameError at /proj1/employees/update/EMP0001
name 'EmpID' is not defined
Request Method: GET
Request URL:    http://localhost:8000/proj1/employees/update/EMP0001
Django Version: 2.2.1
Exception Type: NameError
Exception Value:    
name 'EmpID' is not defined

and the error occurs in views.py where I define my_instance

views.py

from .models import emp_table
from .forms import EmpDetailForm

def my_get_name(request, pk):
    #  error occurs on the next line
    my_instance = emp_table.objects.get(id=EmpID)

    if request.method == 'POST':

        form = EmpDetailForm(request.POST, instance=my_instance)

        if form.is_valid():
            # process the data
            # ...
            # redirect to a new URL:
            return HttpResponseRedirect('/#thanks/')
    else:
        form = EmpDetailForm(instance=my_instance)

    return render(request, 'proj1/emp-detail-form.html', {'form': form}, request.EmpID,)

forms.py

from django import forms
from .models import emp_table

class EmpDetailForm(forms.ModelForm):
    class Meta:
        model = emp_table
        fields = ('EmpID', 'EmpLastName', 'EmpFirstName',)

urls.py

from django.urls import path

from . import views
from . import forms

app_name = 'proj1'

urlpatterns = [
    path('', views.mainmenu, name='mainmenu'),
    path('employees/update/<str:pk>', views.my_get_name, name='emp-detail-form'),
]

models.py

class emp_table(models.Model):
    Default_EmpDeptID = 'ZZZ999'
    Default_EmpEmail = '[email protected]'
    Default_EmpLastName = 'ZZZZZZ'
    Default_EmpFirstName = 'AAAAAA'
    Default_EmpNumber = '1234567890'
    Default_EmpID = '1234567890'
    Default_EmpOrgID = '1234567890'

    EmpID = models.CharField(max_length=45, primary_key=True, default=Default_EmpID)
    EmpNumber = models.CharField(max_length=20, default=Default_EmpNumber)
    EmpFirstName = models.CharField(max_length=20, help_text='Enter first name',
                                  default=Default_EmpFirstName, verbose_name='First Name')
    EmpLastName = models.CharField(max_length=20, help_text='Enter last name',
                                  default=Default_EmpLastName, verbose_name='Last Name')
    EmpEmail = models.EmailField(max_length=60, help_text='eg. [email protected]',
                                  default=Default_EmpEmail)
    EmpDeptID = models.ForeignKey(dept_table, on_delete=models.CASCADE,
                                  default=Default_EmpDeptID)
    EmpOrgID = models.CharField(max_length=20, default=Default_EmpOrgID)

    return_value = EmpLastName, EmpFirstName
    def __str__(self):
        return self.EmpLastName

emp-detail-form.html

{% block content %}
<div class='content'>
<h1>Update Employee Details</h1>

<form action="/proj1/employees/update/{{ object.EmpID }}/" method="POST">
    {% csrf_token %}
    {{ form.as_ul }}
    <input type="submit" value="Submit">
</form>

</div>
{% endblock %}

What I'm trying to do is to read a field from a table, edit it and then write the edited field back to the database. The writing part I haven't got to yet as my issue atm has been reading a field to into a form in preparation to edit it.

2
  • You don't have the variable EmpID in your views.py. What you do have is pk Commented Jul 30, 2019 at 13:31
  • my_instance = emp_table.objects.get(id=pk) Commented Jul 30, 2019 at 13:33

1 Answer 1

0

You don't have any reference to EmpID, but you have primary key of your instance in pk. use pk to get the record

from .models import emp_table
from .forms import EmpDetailForm

def my_get_name(request, pk):
    #  error occurs on the next line
    my_instance = emp_table.objects.get(pk=pk)

    if request.method == 'POST':

        form = EmpDetailForm(request.POST, instance=my_instance)

        if form.is_valid():
            # process the data
            # ...
            # redirect to a new URL:
            return HttpResponseRedirect('/#thanks/')
    else:
        form = EmpDetailForm(instance=my_instance)

    return render(request, 'proj1/emp-detail-form.html', {'form': form}, pk)
Sign up to request clarification or add additional context in comments.

3 Comments

Still wouldn't work; why is there a fourth parameter to render at all?
Plus, the query is wrong in the first place; the whole point is that the pk is called EmpID for some reason. You would need my_instance = emp_table.objects.get(pk=pk) or my_instance = emp_table.objects.get(EmpID=pk)
Thankyou everyone. I followed Higor's and Ajay's advice return render(request, 'proj1/emp-detail-form.html', {'form': form}, pk) and then Daniel's my_instance = emp_table.objects.get(pk=pk) and it all works. Thankyou again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.