Django:页面上的多个表单可以单独提交,也可以一次提交

时间:2018-07-31 20:10:21

标签: python django django-forms

我正在创建一个调查应用,用户可以在其中填写其他用户的调查。作为其一部分,我希望允许用户在一个视图中填写多个用户的调查。为此,我要设置2个实例变量,它们是模型必需的,但用户不应为表单设置。它们是报告者(request.user)和用户(调查的主题)。我试图弄清楚该怎么做,但是还没有足够地使用Formsets(即完全)来解决这个问题。

我也发现这有些棘手,因为我在这里有2种不同的模型在玩。第一个(Surveys)是调查结果的存储位置,第二个(SurveysQueue)是有关调查队列的信息的存储位置(即,用户及其用户列表在该队列的ManyToManyField中)。我的代码在下面,但是我基本上需要弄清楚两件事。 1)如果我使用的是表单集,那么如何动态传递实例变量(由于这个原因,我尝试过不使用表单集,因为我无法弄清楚它),以及2)如何允许表单都通过1提交按钮或针对单个表单特定按钮的按钮(计划隐藏该表单或通过javascript / ajax提交:

forms.py

# Note that the Surveys model also has the 2 additional hidden fields, user and reporter
class SurveyForm(forms.ModelForm):
    description = forms.CharField(
        label='Description',
        required=False,)

score = forms.ChoiceField(choices=choices,
    widget=forms.RadioSelect(attrs={'class': 'radiolist inline'}),)

class Meta:
    model = Surveys
    fields = ('reason', 'score')

views.py

def user_survey(request, username):
    u = get_object_or_404(User, username=username)
    if request.method == 'POST':
        form = SurveyForm(request.POST)
        form.instance.reporter = request.user
        form.instance.user = u
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('home'))
    else:
        form = SurveyForm()

    return {'form': form}

# This returns the forms I need correctly, but I want to be able to submit them together or separately
def multi(request):
    u = get_object_or_404(User, user=request.user)
    queue_exists = UserSurveyQueue.objects.filter(user=u)
    if not queue_exists:
        raise Http404
    queue = queue_exists.get(user=u).queue.all()
    survey_users = [user['id'] for user in queue.values('id')]
    forms = []
    for user in survey_users:
        u = User.objects.get(id=user).username
        forms.append(user_survey(request, u))

    return render(request, 'surveys/multi_survey.html', {'forms': forms})

models.py

class Surveys(models.Model):
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE
    )
    created_at = models.DateTimeField(
        auto_now_add=True
    )
    score = models.IntegerField(
        default=-1,
        validators= [
            MinValueValidator(-1),
            MaxValueValidator(10)
        ]
    )
    reason = models.TextField(
        blank=True
    )
    reporter = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='user_reporter'
    )

    objects = PromoterScoreManager()

    def __str__(self):
        return self.user.username


class UserSurveyQueue(models.Model):
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE
    )
    queue = models.ManyToManyField(
        User,
        related_name='survey_queue'
    )

    class Meta:
        verbose_name = ('Survey Queue')
        verbose_name_plural = ('Survey Queues')

模板:

{% extends 'base.html' %}
{% load static %}

{% block content %}
    {% for form in forms %}
    <form class="form-horizontal" method="POST">
        {% csrf_token %}
        <div class="table-responsive">
            <table class="table table-striped">
                <tr>
                    <th>User</th>
                    <td>{{ form.form.instance.user }}</td>
                </tr>
                <tr>
                    <th>Score</th>
                    <td>{{ form.form.score }}</td>
                </tr>
                <tr>
                    <th>Reason for Score</th>
                    <td>{{ form.form.reason }}</td>
                </tr>
            </table>
        </div>
        <button type="submit" class="btn btn-primary" name="submit" value="1">Submit</button>

    </form>
    {% endfor %}
{% endblock %}

0 个答案:

没有答案