开发者

Django- populating an "update/edit" form with an autofield and foreignkey

I'm new to Django and I'm creating an app to create and display employee data for my company. Currently the model, new employee form, employee table display, login/logout, all works. I am working on editing the current listings. I have hover on row links to pass the pk (employeeid) over the url and the form is populating correctly- except the manytomanyfields are not populating, and the pk is incrementing, resulting in a duplicate entry (other than any data changes made).

I will only put in sample of the code because the model/form has 35 total fields which makes for very long code the way i did the form fields manually (to achieve a prettier format).

#view.py  #SEE EDIT BELOW FOR CORRECT METHOD
@login_required
def employee_details(request, empid): #empid passed through URL/link
    obj_list = Employee.objects.all()
    e = Employee.objects.filter(pk=int(empid)).values()[0]
    form = EmployeeForm(e)
    context_instance=RequestContext(request) #I seem to always need this for {%extend "base.html" %} to work correctly
        return render_to_response('employee_create.html', locals(), context_instance,)

#URLconf 
    (r'^employee/(?P<empid>\d+)/$', employee_details),

# snippets of employee_create.html. The same template used for create and update/edit, may be a source of problems, they do have different views- just render to same template to stay DRY, but could add an additional layer of extend for differences needed between the new and edit requests EDIT: added a 3rd layer of templates to solve this "problem". not shown in code here- easy enough to add another child template
{% extends "base.html" %}
{% block title %}New Entry{% endblock %}
{% block content %}
<div id="employeeform">     
    {% if form.errors %}
        <p style="color: red;">
            Please correct the error{{ form.errors|pluralize }} below.
        </p>
    {% endif %}
    <form action="/newemp/" method="post" class="employeeform">{% csrf_token %} #SEE EDIT
        <div class="left_field">
            {{ form.employeeid.value }}

            {{ form.currentemployee.errors }}
            <label for="currentemployee" >Current Employee?</label>
            {{ form.currentemployee }}<br/><br/>

            {{ form.employer.errors }}
            <label for="employer" class="fixedwidth">Employer:</label>
            {{ form.employer }}<br/>

            {{ form.last_name.errors }}
            <label for="last_name" class="fixedwidth">Last Name:</label>
            {{ form.last_name }}<br/>

                    {{ form.facility.errors }} #ManyToMany 
            <label for="facility" class="fixedwidth">Facility:</label>
            {{ form.facility }}<br/><br/>
                </div>
        <div id="submit"><br/>
        <input type="submit" value="Submit">
        </div>
    </form> 



#models.py
class Employee(models.Model):
    employeeid = models.AutoField(primary_key=True, verbose_name='Employee ID #')
        currentemployee = models.BooleanField(null=False, blank=True, verbose_name='Current Employee?') 
        employer = models.CharField(max_length=30)
        last_name = models.CharField(max_length=30)
        facility = models.ForeignKey(Facility, null=True, blank=True)

base.html just has a header on top, a menu on the left and a big empty div where the forms, employee tables, etc all extend into.

screenshot2

So, how do I need to change my view and/or the in the template to update an entry, rather than creating a new one? ( And how do I populate the correct foriegnkeys? (the drop down boxes have the right options available, but the "-----" is selected even though the original database entry contains the right information.

Let me know if i need to include some more files/code I have more pics too but i cant link more or insert them as a new user :< I'll just have to contribute and help out other people! :D

EDIT: I've been working on this more and haven't gotten too far. I still can't get the drop-down fields to select the values saved in the database (SQLite3). But the main issue I'm trying to figure out is how to save as an update, rather than a new entry. sav开发者_C百科e(force_update=True) is not working with the default ModelForm save parameters.


views.py
    def employee_details(request, empid):
        context_instance=RequestContext(request)
        obj_list = Employee.objects.all()

        if request.method == 'POST':
            e = Employee.objects.get(pk=int(empid))
            form = EmployeeForm(request.POST, instance=e)
            if form.is_valid():
                form.save() 
                return HttpResponseRedirect('/emp_submited/')
        else:
            e = Employee.objects.get(pk=int(empid))
            form = EmployeeForm(instance=e)
        return render_to_response('employee_details.html', {'form': form}, context_instance,)

also changed template form action to "" (from /newemp/ which was the correct location for my new employee tempalte, but not the update.

Thanks to this similar question.


updating a form in djnago is simple: steps: 1. extract the previous data of the form and populate the edit form with this these details to show to user 2. get the new data from the edit form and store it into the database

step1: getting the previous data

views.py

def edit_user_post(request, topic_id):
    if request.method == 'POST':
        form = UserPostForm(request.POST)
        if form.is_valid():
            #let user here be foreign key for the PostTopicModel
            user = User.objects.get(username = request.user.username)
            #now set the user for the form like: user = user

            #get the other form values and post them
            #eg:topic_heading = form.cleaned_data('topic_heading')
            #save the details into db
            #redirect
    else:
        #get the current post details
        post_details = UserPostModel.objcets.get(id = topic_id)
        data = {'topic_heading':topic.topic_heading,'topic_detail':topic.topic_detail,'topic_link':topic.topic_link,'tags':topic.tags}
        #populate the edit form with previous details:
        form = UserPostForm(initial = data)
    return render(request,'link_to_template',{'form':form})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜