Reputation: 67
I'm working on a little app that allows you to save specific location information about places you've been. The issue I'm having is that clicking the submit button on the 'save new location' page doesn't seem to be doing much of anything. It redirects to .../locationlib/savenew/, which is supposed to be the url that saves the form input as a new model object, but both according to debugging print statements and what actually happens, that function is just never called. I've had success with other forms using django but this one seems to be tripping me up. Can someone give me an idea of what's going on here?
views.py
def new(request):
return render(request, 'locationlib/new.html')
def savenew(request):
print 'savenew called'
name = request.POST['name']
latitude = float(request.POST['latitude'])
longitude = float(request.POST['longitude'])
desc = request.POST['description']
user = User.objects.get(username=str(request.POST['user']))
print 'all variables set'
l = Location(
name=name,
longitude=longitude,
latitude=latitude,
custDescription=desc,
user=user,
)
print 'l defined'
l.save()
print 'l saved'
return HttpResponseRedirect(reverse('locationlib:detail', args=[l.id]))
new.html
<div id='new-location-form'>
<form action="{% url 'locationlib:savenew' %}" method="post">
{% csrf_token %}
Name: <input type='text' name='name' value='Place Name' required><br>
User: <input type='text' name='user' value='User' required><br>
Longitude: <input type='text' name='longitude' value="Longitude Coordinate" required><br>
Latitude: <input type='text' name='latitude' value='Latitude Coordinate' required><br>
Description: <textarea name='description'>Description of Place</textarea><br>
<input type="submit" value="Save">
</form>
</div>
urls.py
urlpatterns = patterns( '',
...
url(r'new/', views.new, name='new'),
url(r'^savenew/', views.savenew, name='savenew'),
)
Upvotes: 0
Views: 69
Reputation: 599630
Your first URL pattern, new, is not anchored to the start of the string. That means that it matches anything that ends with "new" - and that includes "savenew". So your request for "savenew" is being caught by that pattern, and being sent to the new view.
Just put a ^
character at the front, as you have done with the other pattern.
Upvotes: 1
Reputation: 818
try to use Modelforms
forms.py:
from django.forms import ModelForm
from myapp.models import Location
# Create the form class.
class LocationForm(ModelForm):
class Meta:
model = Location
def savenew(request):
if request.method == 'POST':
form = LocationForm(request.POST)
if form.is_valid():
new=form.save()
return HttpResponseRedirect(reverse(reverse('locationlib:detail', args=[new.id])))
return render(request,'reservetion/sign.html',{'form': form})
else:
form = SignForm()
return render(request, 'reservetion/sign.html',{'form': form})
<form action="{% url 'locationlib:savenew' %}" method="post">
{% csrf_token %}
{{ form}}
</form>
Upvotes: 0