Django-使用autofield和foreignkey填充“更新/编辑”表单

时间:2010-10-22 21:40:31

标签: django django-forms populate

我是Django的新手,我正在创建一个应用程序来为我的公司创建和显示员工数据。 目前模型,新员工表,员工表显示,登录/注销,全部工作。我正在编辑当前的列表。 我将鼠标悬停在行链接上以通过url传递pk(employeeid)并且表单填充正确 - 除了manytomanyfields没有填充,并且pk正在递增,导致重复的条目(除了所做的任何数据更改)。

我只会放入代码示例,因为模型/表单总共有35个字段,这使得代码的方式非常长,就像我手动执行表单字段一样(以获得更漂亮的格式)。

#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上面有一个标题,左边是一个菜单,还有一个大的空div,表格,员工表等都延伸到了。

screenshot2

那么,我如何更改我的视图和/或模板中的更新条目,而不是创建一个新条目? ( 我如何填充正确的foriegnkeys? (下拉框中有正确的选项可用,但即使原始数据库条目包含正确的信息,也会选择“-----”。

如果我需要包含更多文件/代码,请告诉我 我也有更多的照片,但我无法链接更多或插入他们作为新用户:&lt;我只需要贡献并帮助其他人! :d

编辑: 我一直在努力这个,并没有走得太远。我仍然无法获取下拉字段来选择保存在数据库中的值(SQLite3)。 但我想弄清楚的主要问题是如何保存为更新,而不是新条目。 save(force_update = True)不能使用默认的ModelForm保存参数。

2 个答案:

答案 0 :(得分:4)

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,)

还将模板表单操作更改为“”(来自/ newemp /这是我的新员工tempalte的正确位置,但不是更新。

感谢this similar question

答案 1 :(得分:0)

更新djnago中的表单很简单: 脚步: 1.提取表格的先前数据并使用这些详细信息填充编辑表单以向用户显示 2.从编辑表单中获取新数据并将其存储到数据库中

步骤1: 获取以前的数据

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})