【问题标题】:Django- populating an "update/edit" form with an autofield and foreignkeyDjango-使用自动字段和外键填充“更新/编辑”表单
【发布时间】:2011-04-29 09:45:19
【问题描述】:

我是 Django 新手,我正在创建一个应用程序来为我的公司创建和显示员工数据。 目前模型,新员工表格,员工表显示,登录/注销,所有工作。我正在编辑当前列表。 我将鼠标悬停在行链接上以通过 url 传递 pk(employeeid),并且表单正在正确填充 - 除了未填充许多字段,并且 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

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

如果我需要包含更多文件/代码,请告诉我 我也有更多图片,但我无法链接更多或将它们作为新用户插入:

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

【问题讨论】:

    标签: django django-forms populate


    【解决方案1】:
    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/,这是我的新员工模板的正确位置,但不是更新。

    感谢this similar question

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 好吧,除了这个问题已经有 5 年的历史并且已经回答了,我认为你的解决方案有一些问题。在您的示例中,您确实应该将 instance kwarg 用于 UserPostForm,而不是将所有数据复制到初始字段中。因为就像现在一样,您将创建一个新对象而不是编辑现有对象。
      猜你喜欢
      • 2019-01-03
      • 2018-12-12
      • 2019-08-31
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      • 2019-02-03
      • 1970-01-01
      • 2020-03-18
      相关资源
      最近更新 更多