I am having trouble saving a custom field in a ModelForm. The field in question is a ModelChoiceField.
I have added a save()
method as shown in this question. However, when I use it I get an error:
ImproperlyConfigured
No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.
When I remove my custom save()
method it works ok but doesn't save the custom field. What am I missing?
class NewStoryForm(forms.ModelForm):
class Meta:
model = Story
fields = ['title', 'story_text']
#custom field
about = forms.ModelChoiceField(queryset=None)
#initialise custom field
def __init__(self, user, *args, **kwargs):
super(NewStoryForm, self).__init__(*args, **kwargs)
self.fields['about'] = forms.ModelChoiceField(queryset=Experience.objects.filter(user=user))
#save custom field
def save(self, commit=True):
self.instance.about = self.cleaned_data['about']
super(NewStoryForm, self).save(commit=commit)
class NewStoryView(CreateView):
form_class = NewStoryForm
template_name = 'story/story_form.html'
#Send user to NewStoryForm to initialise custom field
def get_form_kwargs(self):
kwargs = super(NewStoryView, self).get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs
#save author as current user
def form_valid(self, form):
form.instance.author = self.request.user
return super(NewStoryView, self).form_valid(form)