如何在Django中获取所选单选按钮值以传递给UpdateView



我想通过单选按钮获得选定的值,并将其传递到更新视图,但我找不到方法。这两个视图都是基于类的。

异常值:
未找到任何参数的"update author"的反转。尝试了1种模式:

列表视图:

class Dashboard(ListView):
model = Author
template_name='catalog/dashboard.html'
def get_context_data(self, **kwargs):
context = super(EditDashboard, self).get_context_data(**kwargs)
context["authors"] =Author.objects.all()
context["publishers"] =Publisher.objects.all()
context["genres"] =Genre.objects.all()
return context

更新视图:

class UpdateAuthor(UpdateView):
model = Author
fields = '__all__'
template_name='catalog/updateauthor.html'
context_object_name = 'author'

型号:

class Author(models.Model):
first_name = models.CharField(max_length=200, blank=False)
last_name = models.CharField(max_length=200, blank=False)
date_of_birth = models.DateField(null=True, blank =True)
date_of_death = models.DateField(null=True, blank =True)

class Meta:
ordering = ['first_name', 'last_name']
def __str__(self):
return  f' {self.first_name} {self.last_name}'

模板中的表单:

<form action="{% url 'update-author' ????? %}" method="post">
{% csrf_token %}
{% for author in authors %}
<input type="radio" name="choice" id="{{ author.id }}" value="{{ author.id }}">
<label for="author">{{ author.first_name}} {{ author.last_name}}</label><br>
{% endfor %}
<input type="submit" value="Update">
</form>

因此,如果我知道您有一个包含所有作者、出版商和流派的listView,并且您希望在选定作者的情况下调用updateView。

一种方法是使用javascript:

  • 为表单标记提供一个id:
  • 将事件映射到"提交"按钮
  • 获取选定的单选框元素和值
  • 使用您获得的值更改表单操作值
  • 调用提交事件

下面是Jquery的一些示例,您可以使用它来实现这一点:

$(document).ready(function(){
$('#myformid').submit(function(event) {
//prevent the form submition on click
event.preventDefault();
//get the selected value
var selected_author_id =$('input[name="choice"]:checked').val();
console.log(selected_author_id);
//add this value to our form action attribute
$(this).attr('action', 'update-author/'+String(selected_author_id));
//finaly submit the form
$(this).unbind('submit').submit();
});
});

不要忘记导入jquery以及

最新更新