I am a beginner in this, the query is how I can add in my form the image of "Edit" and "Add" in a choice field and I opened in a pop-up the form of that model to add it. As Django admin does but I would like to do it from my form. Thank you.
What I can do but I can not update the queryset after adding the code:
Form.py:
class RelatedFieldWidgetCanAdd(widgets.Select):
def __init__(self, related_model, related_url=None, *args, **kw):
super(RelatedFieldWidgetCanAdd, self).__init__(*args, **kw)
if not related_url:
rel_to = related_model
info = (rel_to._meta.app_label, rel_to._meta.object_name.lower())
related_url = 'admin:%s_%s_add' % info
self.related_url = related_url
def render(self, name, value, *args, **kwargs):
self.related_url = reverse(self.related_url)
output = [super(RelatedFieldWidgetCanAdd, self).render(name, value, *args, **kwargs)]
output.append(u'<a href="%s" class="add-another" id="add_id_%s" onclick="return showAddAnotherPopup(this);"> ' % \
(self.related_url, name))
output.append(u'<img src="%sadmin/img/icon_addlink.gif" width="10" height="10" alt="%s"/></a>' % (settings.STATIC_URL, ('Add Another')))
return mark_safe(u''.join(output))
class movimientoPacienteForm(forms.ModelForm):
codigo = forms.ModelChoiceField(
required = False,
queryset = Codigo.objects.all(),
widget = RelatedFieldWidgetCanAdd(Codigo,
related_url="admin:principal_codigo_add")
)
class Meta:
model = Cuenta
exclude = 'paciente', 'operador', 'comentario', 'contabilizado', 'autoriza',
Movimiento.html
<form id='formulario' method="POST" action=''>{% csrf_token %}
<div class="form-group">
{{ formulario|crispy }}
<p><input type="submit" value="Registrar" class="btn-sm btn-warning"></i></p></p>
</div>
</form>
<script language="javascript" type="text/javascript">
function showAddAnotherPopup(url) {
newwindow=window.open(url,'{{title}}','height=200,width=600');
if (window.focus) {newwindow.focus()}
return false;}
</script>