mercredi 21 mars 2018

Django. How to make model choices from another model

I am trying to make migrations for my models:

from django.db import models  
TAKEN = (
    (True, 'Yes'),
    (False, 'No')
)  

class Room(models.Model):
    name = models.CharField(max_length=32)
    number = models.IntegerField()
    taken = models.BooleanField(choices=TAKEN)
    description = models.CharField(max_length=128)

ROOMS_CHOICE = (Room.objects.filter(taken=False))

class Reservation(models.Model):
    date = models.DateField()
    hours = models.IntegerField()
    choice = models.OneToOneField(Room, on_delete=models.CASCADE, choices=ROOMS_CHOICE)

forms for the models:

from django import forms
from .models import TAKEN, ROOMS_CHOICE   
class NewRoomForm(forms.Form):
    name = forms.CharField(label='Name', max_length=32)
    number = forms.IntegerField(label='Room Number')
    taken = forms.ChoiceField(choices=TAKEN, label='Taken', widget=forms.Select)
    description = forms.CharField(label='Description', widget=forms.Textarea)   
class ReservationForm(forms.Form):
    date = forms.DateField(label='Date', widget=forms.SelectDateWidget)
    hours = forms.IntegerField(label='hours', max_value=8)
    choice = forms.ChoiceField(choices=ROOMS_CHOICE, label='room', widget=forms.Select)

When I try to make migrations, an ProgrammingError appears:

django.db.utils.ProgrammingError: (1146, "Table 'conference_room.conference_room' doesn't exist")

I try to make a view where user can book a conference room from a available rooms (those that are not occupied - taken=False). I assume I made some mistakes during building OneToOne relation and writing choices based on the Room model, and that is why the error appeared. How can I rewrite my models and forms?




Aucun commentaire:

Enregistrer un commentaire