如何动态更新ModelForm的初始值?

时间:2018-03-01 17:36:06

标签: python django django-forms django-templates django-generic-views

我尝试创建一个动态表单,该表单预先填充某个字段initialCreateView属性,当从另一个字段(title)中选择下拉式菜单。

我正在使用Django的通用enter image description here,而我想要解决的方法是覆盖视图的checkin_type方法,例如如果它收到一个AJAX请求(由前面提到的下拉菜单中的jQuery post()触发并包含选择选项的.change()),它会更新id属性表格initial

以下是我迄今为止尝试过的观点(title):

views.py

以下是根据Django的命名约定(from django.views import generic from .models import CheckIn, CheckInType class CheckInCreate(generic.CreateView): model = CheckIn fields = '__all__' def post(self, request, *args, **kwargs): if request.is_ajax(): checkin_type = CheckInType.objects.get(pk=request.POST['id']) form = self.get_form() form['title'].initial = checkin_type.title self.object = CheckIn.objects.create(checkin_type=checkin_type) return self.render_to_response(self.get_context_data(form=form)) else: return super().post(request, *args, **kwargs) 是应用程序的名称)在表单模板中创建AJAX请求的方式,名为templates/dashboard/checkin_form.html

dashboard

以下是相应的模型(在<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script> <script> $(document).ready(function(){ var csrftoken = Cookies.get('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $(".auto-submit").change(function() { $.post({ url: "{% url 'checkin-create' %}", data: {id: $(".auto-submit option:selected").val()} }) }); }); </script> <form action="" method="post">{% csrf_token %} {% for field in form %} <div class="{% if field.name == 'checkin_type' %}auto-submit{% endif %}"> {{ field.errors }} {{ field.label_tag }} {{ field }} </div> {% endfor %} <input type="submit" value="Send message" /> </form> 中):

models.py

问题在于,当我从from django.db import models class CheckInType(models.Model): title = models.CharField(blank=True, max_length=255) description = models.TextField(blank=True) def __str__(self): return self.title class CheckIn(models.Model): checkin_type = models.ForeignKey(CheckInType, null=True, on_delete=models.CASCADE) title = models.CharField(blank=True, max_length=255) description = models.TextField(blank=True) notes = models.TextField(blank=True) # Scheduling requested_date = models.DateField(blank=True, null=True) completed_date = models.DateField(blank=True, null=True) 的下拉菜单中选择一个选项时,我看到表单中没有任何变化:

What happens

我原本希望checkin_type字段预先填入“1周”办理登机手续&#39;在这个例子中。任何想法为什么这不起作用?

1 个答案:

答案 0 :(得分:0)

我认为如果你改变它会起作用 form['title'].initial = checkin_type.titleform.cleaned_data['title'] = checkin_type.title