A user will be able to list his property and he/she will be able to edit the listing.
The Problem
On editing, all other fields will show data already saved by the user and only amenities
field won't display 'values already selected'.
All the values of the amenities
field are saved in a TextField and user can select multiple items via 'CheckboxSelectMultiple' widget.
Models
class Motel(models.Model):
user= models.ForeignKey(User)
name= models.CharField(max_length=100, verbose_name='Name')
amenities= models.TextField()
I added 'checked' to the form field widget but it will only check all the items.
class MotelForm(forms.ModelForm):
amenities = forms.MultipleChoiceField(choices=FACILITY_CHOICES, required= False, widget=forms.CheckboxSelectMultiple(attrs={'checked':'checked'}))
Views
@login_required
def edit_motel_details(request, motel_id, slug):
if id:
motel= Motel.objects.get(id=motel_id, slug=slug)
else:
motel= motel()
motel_form= MotelForm(instance=motel)
MotelImagesInlineFormSet= inlineformset_factory(Motel, MotelImages, fields=('image',))
formset= MotelImagesInlineFormSet(instance=motel)
if request.method== "POST":
motel_form= MotelForm(request.POST, request.FILES)
if id:
motel_form= MotelForm(request.POST, request.FILES, instance=motel)
formset= MotelImagesInlineFormSet(request.POST, request.FILES, instance=motel)
if motel_form.is_valid():
created_motel= motel_form.save(commit=False)
formset=MotelImagesInlineFormSet(request.POST, request.FILES, instance=created_motel)
if formset.is_valid():
created_motel.save()
formset.save()
redirect_url=reverse('listed')
return HttpResponseRedirect(redirect_url)
return render(request, 'm/m_edit.html', {'motel_form': motel_form,'formset':formset,})
I want to display already selected/saved items by the user in the 'edit form'. What am I missing?