I’m trying to edit an existing object through a form, but every thing is not being populated with the current value.
This object did have a value but when I went to edit, nothing showed up in the all field and only showing blank field.
Here’s the model:
class Flow (models.Model):
title = models.CharField("Title", max_length=200)
slug = models.SlugField(unique=True)
description = models.TextField("Description")
url = models.URLField("URL")
tags = TaggableManager()
flow_date = models.DateTimeField(auto_now_add=True, blank=True, null=True)
author = models.ForeignKey('auth.User', null=True)
def __unicode__(self):
return self.title
@permalink
def get_absolute_url(self):
return ('flow.views.details', (), {'slug':self.slug})
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
return super(Flow, self).save(*args, **kwargs)
class Meta:
verbose_name = 'Flow'
Here’s the view
class FlowForm(forms.ModelForm):
class Meta:
model = Flow
exclude = ['flow_date', 'slug']
@login_required
def edit(request, flow_id = None):
flow = None
if flow_id is not None:
flow = get_object_or_404(Flow, pk=flow_id)
if request.method == 'POST':
form = FlowForm(request.POST, instance=flow)
if form.is_valid():
tags = form.cleaned_data['tags']
newflow = form.save(commit=False)
newflow.save()
for tags in tags:
newflow.tags.add(tags)
return HttpResponseRedirect(newflow.get_absolute_url())
else:
form = FlowForm(request.POST, instance=flow)
return render_to_response('flow/flow_edit.html', {'form':form, 'flow':flow,}, context_instance=RequestContext(request))
Thanks in advance.
UPDATE
Thank you Daniel.
Now I want to delete the object including their django-taggit object. It work with following definition but the tag still show on tag cloud list based on django-taggit-templatetags.
@login_required
def delete(request, flow_id):
flow = Flow.objects.get(pk=flow_id)
flow.delete()
return render_to_response('flow/flow_delete.html', {'flow':flow,}, context_instance=RequestContext(request))
How to remove selected django-taggit’s object/count from form/database?
You’re passing in
request.POSTas the data argument to the form instantiation in the else clause, when the request is not a POST and so therefore that is an empty dictionary. Even though it’s empty, it will still override all fields from the instance, because instance values are only used as defaults and will not be displayed when anything is passed as data. Change that line to just: