django - How to render a form with a user's data? -
how create django form display user's sell objects radio box next each obejct deletion? i'm trying create similar django admin users listed radio boxes quick deletion.
from request.user i'm trying sell's associated objects user , return list of sells in order delete selected. far profile form looks this:
class profileform(modelform): def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super(profileform, self).__init__(*args, **kwargs) sells = forms.integerfield( widget=forms.select( sell=sell.object.filter(user=self.request.uwer) ) )
in views.py plan delete selected sell objects so:
for sell in form.sells: sell = sell.objects.get(id=sell) sell.delete()
there's quite few things wrong here. significant can't set choices in form definition, don't have access request.user
there.
i don't think want model form, anyway. creating , editing model instances, whereas want list existing instances checkbox. want normal form field represents instances, ie modelmultiplechoicefield.
so, form looks this:
class deletesellform(forms.form): sells = forms.modelmultiplechoicefield(queryset=sell.objects.none(), widget=forms.checkboxselectmultiple) def __init__(self, *args, **kwargs): user = kwargs.pop('user', none) super(deletesellform, self).__init__(*args, **kwargs) self.fields['sells'].queryset=sell.objects.filter(user=user)
you'll notice queryset defaults none, set correct user's objects in __init__
method, can pass in user.
so view looks this:
def delete_sells(request): if request.post: form = deletesellsform(request.post, user=request.user) if form.is_valid(): form.cleaned_data['sells'].delete() else: form = deletesellsform(user=request.user) return render(request, 'template.html', {'form': form})
modelmultiplechoicefield
cleans queryset, should able call delete()
on directly.
Comments
Post a Comment