Peter DeGlopper 작성 :UpdateView에서 M2M 필드를 변경하는 방법은 무엇입니까?
도움을 주셔서 감사합니다. 문제를 해결해 주셔서 감사합니다. 정말 감사하겠습니다. 나는 머리를 테이블에 치고 있었다.
내 ModelForm을 변경할 필요가 없습니다. checked = "checked" 서브넷이 체크 된대로 출력되고 있지만 브라우저에 체크 표시되지 않았습니다. 이것은 CentOS의 Firefox 24.2.0 (VM에서)에 있었기 때문에 Windows 7 호스트로 이동하여 Firefox 26.0을로드했습니다. IE8에서도 제대로 작동했습니다. 그것은 이상한 일 이었지만 그것이 효과가 있다는 혼란을 설명합니다.
덕분에 필드를 절약 할 수 있었기 때문에 나는 이제 어떻게 생각하고 있는지 보았습니다. M2M 필드를 업데이트 할 수 있습니다. 작업 코드를 표시하도록 아래 TagUpdateView를 업데이트했습니다.
나는 M2M 필드와 함께 UpdateView를 사용하려고 2 문제가 ...
내 템플릿에 확인으로 현재 "태그"서브넷이 표시 해달라고- 방법 form_valid를 재정 의하여 내 TagUpdateView에서 M2M 관계를 업데이트 할 수 있습니까?
어떤 통찰력이라도 대단히 감사하겠습니다. 감사합니다. .
태그 M2M의 models.py :
class Tag(models.Model):
tag = models.CharField(max_length=120)
group = models.ForeignKey(Group)
description = models.TextField(max_length=500)
subnet = models.ManyToManyField(Subnet, null=True, blank=True)
date_created = models.DateTimeField()
created_by = models.ForeignKey(User, related_name='tag_created_by')
date_modified = models.DateTimeField(auto_now=True)
modified_by = models.ForeignKey(User, related_name='tag_modified_by')
def __unicode__(self):
return self.tag
태그 ModelForm :
class TagForm(forms.ModelForm):
subnet = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(), required=True, queryset=Subnet.objects.all())
class Meta:
model = Tag
exclude = ('date_created', 'created_by', 'date_modified', 'modified_by')
태그 views.py :
class TagUpdateView(UpdateView):
template_name = 'tag_update.html'
model = Tag
form_class = TagForm
def form_valid(self, form):
update_tag = form.save(commit=False)
update_tag.modified_by = self.request.user
update_tag.save()
form.save_m2m()
return super(TagUpdateView, self).form_valid(form)
내 템플릿 "tag_update.html"
{% extends 'base.html' %}
{% load widget_tweaks %}
{% block title %}Tag {{ object.tag }} Update{% endblock %}
{% block content %}
<h1>Tag {{ object.tag }} Update</h1>
<br />
<form action="" method="post" role="form">{% csrf_token %}
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label for="id_tag">Tag Name</label>
{% render_field form.tag placeholder=form.tag.label class="form-control" %}
</div>
</div>
</div>
<div class="row">
<div class="col-sm-2">
<div class="form-group">
<label for="id_group">Group</label>
{% render_field form.group placeholder=form.group.label class="form-control"%}
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="id_description">Description</label>
{% render_field form.description placeholder=form.description.label class="form-control" rows="5" %}
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="id_checkbox">Link to Subnets</label>
{{ form.subnet }}
</div>
</div>
</div>
<br />
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<br />
{% endblock %}