我是Django的新手,我正在創建一個應用程序來創建和顯示我公司的員工數據。 當前模型,新員工表單,員工表格顯示,登錄/註銷,所有作品。我正在編輯當前列表。 我已懸停在行鏈接上,將pk(employeeid)通過url並且表單正確填充 - 除了許多tomanyfields沒有填充,並且pk正在遞增,導致重複條目(除了所做的任何數據更改外) 。Django-使用自動字段和外鍵填充「更新/編輯」表單
我只會放入代碼示例,因爲模型/表單總共有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在形式,員工桌等所有延伸到。
那麼,如何做我需要改變我的觀點和/或在模板中更新條目,而不是創建一個新的? ( 如何填充正確的foriegnkeys?(下拉框有可用的正確選項,但即使原始數據庫條目包含正確信息,也會選擇「-----」。
讓我知道如果我需要包括更多的文件/代碼 我也有更多的照片,但我無法鏈接更多或插入他們作爲新用戶:<我只需要貢獻並幫助其他人:D
編輯: 我一直在努力,並沒有太多。我仍然無法獲得下拉字段來選擇保存在數據庫中的值(SQLite3)。 但我主要的問題是試圖弄清楚是如何做到的保存爲更新,而不是新條目。 save(force_update = True)不適用於默認的ModelForm保存參數。
好,比這個問題爲5歲和已經回答了其他的,我覺得你的解決方案有一些問題。在你的例子中,你真的應該使用'實例'kwarg UserPostForm,而不是將所有數據複製到初始字段。因爲現在,你會創建一個新的對象,而不是編輯現有的對象。 – 2016-03-31 21:13:17