2👍
✅
First, remove you’re going to need to remove fields
from your ModelForm
definition. As it is no the data you want.
class AddLink(ModelForm):
subtitle = forms.CharField(label='Subreddit')
class Meta:
model = Post
Then, you need to populate your initial form data.
@login_required(login_url='/login/')
def edit_link(request, post_id):
get_post = Post.objects.get(id=post_id)
if request.method == 'POST':
form = AddLink(request.POST, instance=get_post)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
# this line changed
form = AddLink(instance=get_post, initial={ 'subtitle': get_post.subtitle.name })
context = { 'form': form, 'post': get_post, }
template_name = 'edit_post.html'
return render_to_response(template_name, context,
context_instance=RequestContext(request))
Also, you should probably add a save()
method to your model.
def save(self, commit=True):
post = super(AddLink, self).save(commit=False)
subtitle_name = self.cleaned_data['subtitle']
if post.subtitle:
post.subtitle.name = subtitle_name
else:
post.subtitle = new Subtitle(name=subtitle_name)
post.subtitle.save()
post.save()
return post
EDIT: made a change in code base on comment.
Source:stackexchange.com