Django在一个模板上有几个ModelForm实例和表单

时间:2013-08-22 17:50:23

标签: django templates django-forms multiple-forms

在为我们的应用程序设置用户配置文件时遇到问题。想象一下具有基本信息,工作和教育职位的LinkedIn式用户档案。

模型(简化)

class UserProfile(models.Model):
    about_me = models.TextField(blank=True, null=True)
    formatted_name = models.CharField(max_length=120,  null=True, blank=True)
    username_slug = models.SlugField(null=True, blank=True, unique=True)
    location_name = models.CharField(max_length=120,  null=True, blank=True)
    ...

class JobPosition(models.Model):
    user_profile = models.ForeignKey(UserProfile)
    company_name = models.CharField(max_length=150, null=True, blank=True)
    title = models.CharField(max_length=150, null=True, blank=True)
    job_description = models.CharField(max_length=1000, null=True, blank=True)
    start_date = models.DateField(blank=True, null=True)
    end_date = models.DateField(blank=True, null=True)


class Education(models.Model):
    user_profile= models.ForeignKey(UserProfile)
    degree = models.CharField(max_length=60, null=True, blank=True)
    field_of_study = models.CharField(max_length=120, null=True, blank=True)
    school_name = models.CharField(max_length=150, null=True, blank=True)
    start_date = models.DateField(blank=True, null=True)
    end_date = models.DateField(blank=True, null=True)

很明显,用户可以拥有0-n个工作岗位和0-n个教育岗位。

forms.py

class BasicForm(ModelForm):
    class Meta:
        model = UserProfile
        fields = ['id', 'about_me', 'linkedin_headline', 'location_name']
    # enter code here

class EducationForm(ModelForm):
    class Meta:
        model = Education
        fields = ['id', 'degree', 'field_of_study', 'school_name', 
                  'start_date','end_date']

class WorkForm(ModelForm):
    class Meta:
        model = JobPosition
        fields = ['id','company_name', 'title', 'job_description', 
                  'start_date','end_date']

views.py - 我希望在一个函数中包含所有内容,因为我不想调用其他URL。 (见模板后面的内容)。用户应该能够编辑他在网站上的位置,点击“更新”并重定向回到个人资料网站上。 - 我尝试通过更新按钮的名称来应用区分帖子收入的应用程序:How can I build multiple submit buttons django form? - 它目前没有做很多验证工作

def detail(request, slug):
u = get_object_or_404(UserProfile, username_slug=slug)

#checking the request on Post 
if request.method == 'POST':
    # Battery of IF statements to determine which form has been used
    # if it's updating basic info
    if 'updateBasic' in request.POST:
        form = BasicForm(request.POST)
        if form.is_valid():
            form.save()

    # if its a Work Position
    if 'updateWork' in request.POST:
        form = WorkForm(request.POST)
        if form.is_valid():
            form.save()
# ... same for education...

# if there is no POST request, then the profile is just called to be displayed
else:
    basicForm = BasicForm()
    educForm = EducationForm()
    workForm = WorkForm()

#CSRF Token generation
c = {'user': u,
    'years' : range( datetime.now().year, 1980, -1),
    'months' : range( 1,13),
    'basicForm': basicForm,
    'educForm': educForm,
    'workForm': workForm}
#CSRF Token generation
c.update(csrf(request))

return render(request, 'userprofile/detail.html', c)

模板: 挺直的。循环工作和教育岗位:

{% for work in user.positions %}
  <div id="work{{ forloop.counter }}" class="row">
    <div class="large-2 small-3 columns">
      <h6>  {{ work.end_date|date:'M Y'|default:"NOW"  }}<br>{{ work.start_date|date:'M Y'  }}</h6>

    </div>
    <div class="large-10 small-9 columns">
        <h6>{{ work.title }}
          <a class="show_hide editIcon" href="#" rel="#editWork{{ forloop.counter }} #work{{ forloop.counter }}" title="Edit"><i class="icon-edit pull-right editIcon icon-large"></i></a> 
        </h6>
        <h6 class="dblue ">{{ work.company_name }}</h6>
      {% if work.job_description %}
      <p> {{ work.job_description}} </p>
      {% endif %}
      {% if not forloop.last %}
      <hr>
      {% endif %}
    </div>
  </div>
  <div id="editWork{{ forloop.counter }}"  style="display: none;" class="row editForm">
    <div class="large-10 large-centered columns">
    <h5>Edit</h5>
      <form class="custom" action="#" method="post" name="WorkForm"> {% csrf_token %}
          <div class="row">
            <div class="large-6 columns">
              <label for="company">Company:</label>
              <input type="text"  name="company" id="company" placeholder="Example Ltd" required value="{{ work.company_name }}"/>
            </div>
            <div class="large-6 columns">
              <label for="title">Title:</label>
              <input type="text" name="title" id="title" placeholder="Example position" required value="{{ work.title }}"/>
            </div>
          </div>
...
<div class="row">
  <div class="large-12 columns">
     <label for="desc">Description</label>
     <textarea name="desc" id="desc" cols="40" rows="6" value="{{ edu.field_of_study_description }}"></textarea>
   </div>
</div>

<div class="row">
  <div class="large-2 small-3 columns">
<button class="tiny submit" type="submit" name="updateWork" title="Update this position" >update</button>
  </div>
  <div class="large-2 small-3 columns">
<button class="tiny submit" type="reset" title"Clear the form">Reset</button>
  </div>
  <div class="large-2 small-3 columns">
<a class="show_hide button tiny" href="#" rel="#editWork{{ forloop.counter }} #work{{ forloop.counter }}" title="Close the edit panel">Cancel</a> 
  </div>
  <div class="large-3 columns">
<a class="button tiny secondary" href="#"  title="Delete this position"> Delete</a>
  </div>
</div>
</form>
</div>
</div>
{% endfor %}

所以我做的是:

  • 我遍历所有工作位置并生成一个div来编辑它 准确的位置。
  • 单击“编辑按钮”和javascript时会显示div 启动以使div可见(滑过非编辑div)
  • 然后,用户应该能够编辑这个确切的位置。单击更新,我调用详细操作来处理更新请求。 (尚未实施)
  • 我也为教育做同样的事情
  • 我知道表格尚未整合。因为我真的不知道如何以适当的方式做到这一点......

问题

  1. 如何正确显示每个位置的一个模型? (Formests并不是我认为我应该使用的,因为他们只允许使用一组表单而不是单个实例)
  2. 如何填写相应的值? (甚至可以在运行时完成,还是我可以创建一个填充了视图中已有值的表单数组,然后将此数组传递给模板?)
  3. 我一般在正确的道路上? :)
  4. 对于冗长的帖子感到抱歉,但我认为id会尽可能多地给你信息,所以你希望能以正确的方式指导我。

    现在已经提前多谢了

    菲尔

0 个答案:

没有答案