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.
JavaScript
x
23
23
1
# Form
2
from .models import ShortURL
3
from django import forms
4
5
class CreateNewShortURL(forms.ModelForm):
6
class Meta:
7
model=ShortURL
8
9
fields = {'long_url'}
10
11
widgets = {
12
'long_url': forms.URLInput(attrs={'class': 'form-control'})
13
}
14
15
16
# View
17
def page_redirect(request, url):
18
if request.method == 'GET':
19
form = CreateNewShortURL(request.GET)
20
if form.is_valid():
21
original_website = form.cleaned_data['long_url']
22
return HttpResponseRedirect(original_website)
23
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.
JavaScript
1
8
1
def page_redirect(request, url):
2
if request.method == 'GET':
3
form = CreateNewShortURL(request.POST)
4
if form.is_valid():
5
original_website = form.cleaned_data['long_url']
6
return HttpResponseRedirect(original_website)
7
return render(request,'template') # this is the form for the user to enter the url
8