I'm new to Django and cannot figure out why my form is not working. It seems that after form submit even though the url is being changed to /82nsj/update
it is still going to the index
method in the view.
Views
from business.models import Business, Token
from django.shortcuts import render
from business.forms import BusinessForm
def index(request, token):
try:
business = Business.objects.get(token__token=token)
except Token.DoesNotExist:
business = None
except Business.DoesNotExist:
business = None
form = BusinessForm(instance=business)
return render(request, 'business/index.html', {'form': form})
def update(request, token):
try:
business = Business.objects.get(token__token=token)
except Token.DoesNotExist:
business = None
except Business.DoesNotExist:
business = None
form = BusinessForm(request.POST, instance=business)
if form.is_valid():
form.save()
return render(request, 'business/index.html', {'form': form})
Urls
url(r'^$', 'business.views.index', name='home'),
url(r'^business/(?P<token>\w+)/', 'business.views.index', name='business'),
url(r'^business/(?P<token>\w+)/update/', 'business.views.update', name='business_update'),
Forms
self.helper = FormHelper(self)
self.helper.form_class = 'form-horizontal'
self.helper.form_action = 'update/'
self.helper.form_method = 'post'
self.helper.layout = Layout(
HTML("<p class='alert-info alert'>Please confirm your business contact information is updated and correct.</p>"),
Div(
'my',
'fields',
FormActions(
Submit('save_changes', 'Save changes', css_class="btn-primary"),
),
css_class='row-fluid'
)
)
I know this isn't working because I have breakpoints setup in my index
and in my update
and after I press the submit button only the index
breakpoint is being reached.
What am I doing wrong that is preventing the update
method from running on form submit?
It's probably an issue with your url(...
regex.
Django will go to the first URL that matches so if you have this
url(r'^business/(?P<token>\w+)/', 'business.views.index', name='business'),
url(r'^business/(?P<token>\w+)/update/', 'business.views.update', name='business_update'),
going to /business/<token>/anything_goes_here
will always go to business.views.index
.
To stop this, include a $
for end of expression
.
url(r'^business/(?P<token>\w+)/$', 'business.views.index', name='business'),
Now your /business/<token>/update/
wont match the first URL and will then match business.views.update
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.