I’m making a url shortener with django. I have a form that has a long_url attribute. I’m trying to get the long_url and add it to a redirect view with a HttpResponseRedirect.
# Form from .models import ShortURL from django import forms class CreateNewShortURL(forms.ModelForm): class Meta: model=ShortURL fields = {'long_url'} widgets = { 'long_url': forms.URLInput(attrs={'class': 'form-control'}) } # View def page_redirect(request, url): if request.method == 'GET': form = CreateNewShortURL(request.GET) if form.is_valid(): original_website = form.cleaned_data['long_url'] return HttpResponseRedirect(original_website)
When I go to the link, it gives me The view urlshort.views.page_redirect didn't return an HttpResponse object. It returned None instead.
Does anyone know why this is happening?
Advertisement
Answer
It is not returning because there is no valid form, you need to redirect to a form for the user to enter data first, you will then get that data from the form to perform your redirect. additionally because a user is returning data you will need to get the data from request.POST.
def page_redirect(request, url): if request.method == 'GET': form = CreateNewShortURL(request.POST) if form.is_valid(): original_website = form.cleaned_data['long_url'] return HttpResponseRedirect(original_website) return render(request,'template') # this is the form for the user to enter the url