简体   繁体   中英

How do I store values in a model based on user input in django?

For a given slot the user selects (which should have time, club, day, and court associated with it), how do I save the value stored in "username" to the "reservation" field in class Opening?

def vote(request, club_id):
    if 'username' in request.POST and request.POST['username'] and 'slot' in request.POST and request.POST['slot']:
        username = request.POST['username']
        slot = request.POST['slot']
        #save the value stored in "username" to the "reservation" field in class Opening with the other associated data (club, time, day, court)
        return HttpResponseRedirect('reserve/templates/booked.html',{'username':username, 'slot':slot})
    else:
        return render_to_response('reserve/templates/vote.html', {'error': True})

Avail_times.html:

<form action="/clubs/{{ club.id }}/vote/" method="post">
{% csrf_token %}
{{ today }}<br>
{% for slot in open_slots %}
    <input type="checkbox" name="slot" id="slot{{ forloop.counter }}" value="{{ slot.id }}" />
    <label for="slot{{ forloop.counter }}">{{ slot.slot }} on Court {{slot.court}}</label><br />
{% endfor %}

<br>
{{ tomorrow }}<br>
{% for slot in tom_open_slots %}
    <input type="checkbox" name="slot" id="slot{{ forloop.counter }}" value="{{ slot.id }}" />
    <label for="slot{{ forloop.counter }}">{{ slot.slot }} on Court {{slot.court}}</label><br />
{% endfor %}    
<input type="text" name="username" />
<input type="submit" value="Reserve" />

Model:

from django.db import models
import datetime

class Club(models.Model):
    establishment = models.CharField(max_length=200)
    address = models.CharField(max_length=200)
    def __unicode__(self):
        return self.establishment

class Court(models.Model):
    club = models.ForeignKey(Club)
    day = models.ForeignKey(Day)
    court = models.IntegerField(max_length=200)
    def __unicode__(self):
        return unicode(self.court)

class Opening(models.Model):
    club = models.ForeignKey(Club)
    day = models.DateField('date')
    court = models.ForeignKey(Court)
    slot = models.TimeField('slot')
    reservation = models.CharField(max_length=200)
    def __unicode__(self):
        return unicode(self.slot)

If you want to update the Opening model, then you need to know which one.

Write the opening_id into the form. I'm not sure how your slots and openings are related so you'll have to figure this bit out.

I'd usually use get_object_or_404 to get the relevant Opening

username = request.POST['username']
opening = get_object_or_404(Opening, id=request.POST['opening_id'])
opening.reservation = username
opening.save()

You'd also want to check that the user is allowed to update that opening.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM