问题
I am trying to edit my objects using HTML form instead of Django model form. I need to know how to make the view for this (See my incomplete view below in bold)
Intro: I have a very simple html (invisible )form in the right column of my Index.html. when the user clicks on Locate me
button. The form automatically fills the users latitude and longitude details and clicks submit(the user does not see the form). I use jQuery to achieve this
<form method="post" action="#">
{% csrf_token %}
<input id="jsLat" type="text" placeholder="latittude" name="LAT">
<input id="jsLon" type="text" placeholder="longitude" name="LON">
<button type="submit" id="submit">Submit</button>
</form>
My models are
class UserLocation(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
lat = models.FloatField(blank=True, null=True)
lon = models.FloatField(blank=True, null=True)
point = models.PointField(srid=4326, default='SRID=4326;POINT(0.0 0.0)')
My incomplete view(I need help completing this)
@login_required
def edit_location(request):
if request.method == 'POST':
form = ??????????? #don't know how to call the HTML form
user = request.user
lat = request.POST.get('LAT') #lat is a field in the model see above
lon = request.POST.get('LON') #lon is a field in the model see above
form.save(commit=False) #Not sure if I can use this with HTML form
point = lat (some operation) lon
form.save()
return redirect("home")
Also in the HTML form action
do I use the URL created for this view
回答1:
You don't need a form in your view if you're manually picking the values from request.POST
. Just create or modify a model instance directly.
You can create a form class that corresponds to the one you're writing manually to the the validation etc. when receiving data (but without using it to display the form). You'll likely need to add {% csrf_token %}
to your html form if you do this (or mark the view csrf exempt).
urls.py
...
(r'^/my/special/url/', views.edit_location),
views.py (manually pulling request.POST parameters, and updating a model):
@login_required
def edit_location(request):
if request.method == 'POST':
#location,created = UserLocation.objects.get_or_create(user=request.user)
location = UserLocation.objects.get_or_create(user=request.user)[0]
location.lat = request.POST.get('LAT') #lat is a field in the model see above
location.lon = request.POST.get('LON') #lon is a field in the model see above
location.point = lat (some operation) lon
location.save()
return redirect("home")
form:
<form method="post" action="/my/special/url/">
<input id="jsLat" type="text" placeholder="latittude" name="LAT">
<input id="jsLon" type="text" placeholder="longitude" name="LON">
<button type="submit" id="submit">Submit</button>
</form>
来源:https://stackoverflow.com/questions/52120434/editing-an-object-with-html-form-instead-of-django-model-form