django - Edit a Key/Value Parameters list Formset -
i'm looking convenient solution create 'edit settings' key/values page.
parameters model :
class parameter(models.model): key = models.charfield(max_length=50) value = models.charfield(max_length=250) showinui = models.smallintegerfield()
initial keys/values inserted in table. load them , send them using model formset factory using these lines :
parameterformset = modelformset_factory(parameter, extra=0, fields=('key', 'value')) parameterformset = parameterformset(queryset=parameter.objects.filter(showinui=1)) return render_to_response('config.html', {'parameterformset': parameterformset}, context_instance=requestcontext(request))
template side, when formset displayed, keys , values shown inputs.
i'd find convenient way display form keys readonly labels , values inputs. and, when submited, validate them according django standards.
i've read lot of stuff, guess solution may custom widget, find reliable solution.
thanks reading.
edit :
working solution
views.py
def config(request): parameterformset = modelformset_factory(parameter, extra=0, fields=('value',)) if request.method == "post": try: formset = parameterformset(request.post, request.files) except validationerror: formset = none return httpresponse("ko") if formset.is_valid(): formset.save() return httpresponse("ok") #parameterformset = modelformset_factory(parameter, extra=0, fields=('value',)) parameterformset = parameterformset(queryset=parameter.objects.filter(showinui=1)) return render_to_response('config.html', {'parameterformset': parameterformset}, context_instance=requestcontext(request))
template
<form method="post"> {% csrf_token %} {{ parameterformset.management_form }} {% form in parameterformset %} <div> {{ form.instance.key }} {{ form }} </div> {% endfor %} <input type="submit" /> </form>
if not want value editable, don't include in fields
when creating form set.
parameterformset = modelformset_factory(parameter, extra=0, fields=('value',)) # don't forget trailing comma after 'value' otherwise it's not tuple!
in template, can loop through forms in form set, , display key @ same time.
{% form in parameter_form_set %} {{ form.instance.key }}{# display key related form #} {{ form }}{# display form #} {% endfor %}
Comments
Post a Comment