如何在Django中动态更新表单数据

时间:2018-08-14 09:19:52

标签: python django

我是django的新手,我正在尝试创建一个审核系统,每个团队成员都对该团队中的所有其他成员进行审核。

这是我的models.py文件:

from django.db import models  
from django.contrib.auth.models import User

class Team(models.Model):
    name = models.CharField(max_length=25)

    def __str__(self):
        return self.name

class Trait(models.Model):
    name = models.CharField(max_length=25)

    def __str__(self):
        return self.name

class Review(models.Model):     
    reviewer = models.ForeignKey(User, on_delete=models.CASCADE, 
                                    related_name='reviewer_id')
    reviewee = models.ForeignKey(User, on_delete=models.CASCADE, 
                                    related_name='reviewee_id')
    trait = models.ForeignKey(Trait, on_delete=models.CASCADE)
    trait_score = models.IntegerField()` return

这是我的views.py文件:

 from django.shortcuts import render, redirect
 from review.forms import ReviewForm
 from django.http import HttpResponse
 from django.contrib.auth.models import User
 from accounts.models import UserProfile

 def positivity_review(request):
     if request.method == 'POST':
     form = ReviewForm(request.POST)
     if form.is_valid():
         form.save()
         return redirect('/review/relationships')
     else:
         form = ReviewForm()
         users = UserProfile.objects.filter(review_team=1)
         args = {'form': form, 'team_members': users}
         return render(request, 'review/positivity.html', args)` return

这是我的forms.py文件:

from django import forms
from django.forms.widgets import NumberInput
from review.models import Team, Review

class RangeInput(NumberInput):
    input_type = 'range'


class ReviewForm(forms.ModelForm):
    trait_score = forms.IntegerField(widget=RangeInput, min_value=0, 
    max_value=100, label='')

    class Meta:
        model = Review
        fields = (
            'trait_score',    
            )` return

这是HTML文件:

{% extends 'base.html' %}

{% block head %}
<title>Review</title>
{% endblock %}

{% block content %}
<br>
<h1>Review</h1>
<h2>Do they foster a postive climate?</h2>
<div class="row">
  <div class="col-md-2">
    <p>Exhibits a lack of awareness for a positive climate. Resistance to prompting.</p>
  </div>
  <div class="col-md-2">
    <p>Cooperates at times, within structured activities and friendly under prompting.</p>
  </div>
  <div class="col-md-2">
    <p>Cooperates within the team environment without prompting.</p>
  </div>
  <div class="col-md-2">
    <p>Cooperates well with others, enthusiastic and positve. Occationally prompts others to engage positively.</p>
  </div>
  <div class="col-md-4">
    <p>Seeks to continuously and consistently create a positive environment. Acts as a role model for the team through prompting being supportive and encouraging and showing genuine concern for others.</p>
  </div>
</div>
<div>
  <form method="post">
    {% for user in team_members %}
      <p>Reviewing: {{ user.first_name }}  {{ user.last_name }}</p>
      {% csrf_token %}
      {{ form.as_p }}
    {% endfor %}
      <button class="btn btn-primary" type="submit">Next</button>
  </form>
</div>
{% endblock %}`

目前,我正在通过views.py将queryset传递到html文件中,并循环遍历以加载相关数量的团队成员。

既然我每次都为团队中的每个人加载一个表单,那么我该如何提交表单,以便它知道正在审核谁?例如,提交审稿人,特征和得分很简单,因为大多数评论都可以直接传递到视图中,但是,提交审稿人(正在审阅的人)是不确定如何处理的部分,因为它们被装入了使用模板标记的表单。我想知道是否有可能将某种数据提交回表格,例如名字+姓氏或他们的用户ID,等等,以便在我发布结果时可以过滤个人结果。

希望描述足够了。预先感谢!

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,则可能是答案。

首先,创建一个简单的表单(而不是ModelForm)并添加以下内容:

pk = forms.CharField(
    widget=forms.TextInput(
        attrs={
            'type': 'hidden',
        }
    ),
    label=''
)

这将保留受审者的pk,并且对审阅者不可见。

然后,在HTML文件中,我认为您必须为每个用户生成一个单独的表单,而不仅仅是输入(我不确定,请尝试一下)。您可以这样做:

{% for user in team_members %}

    <form method="post" id="review_form_{{user.pk}}">

        <p>Reviewing: {{ user.first_name }}  {{ user.last_name }}</p>
        {% csrf_token %}
        {{ form.as_p }}

        <button class="btn btn-primary" type="submit">Next</button>
    </form>
    <script type="text/javascript">
        $('#review_form_{{user.pk}}').children('#id_pk').val("{{user.pk}}");
    </script>
{% endfor %}

请记住,当django生成表单时,每个输入都必须获得一个ID,并且django在您在id_中创建的字段名称的开头添加fields.py


最后,当审阅者提交表单时,您可以通过以下方式在views.py中找到您的收据:

form = ReviewForm(request.POST)
if form.is_valid():
    reviewee_id = request.POST.get('pk')
    reviewee = User.objects.get(pk=reviewee_id)