“多对多模型表单”未保存到数据库

时间:2016-01-26 07:55:56

标签: django django-models django-forms django-views

我正在创建一个用户可以将书籍添加到数据库的应用程序。

我的用户模型在另一个应用程序和书籍模型之间存在多对多的关系。

图书模型与类别模型有很多关系。

我很困惑为什么我无法将数据保存到数据库中。它正在通过request.POST,因为当我打印到终端时,所有值都存在于url中。

我在哪里弄错了?我一直在阅读文档,但不明白我错过了什么。

用户模型

#Custom User Model Manager - creates and saves user to database
class UsrAccountsManager(BaseUserManager):
    def create_user(self, email, first_name, password=None):
        if not email: 
            raise ValueError('Users must have an email address.')

        user = self.model(
            email = self.normalize_email(email),
            first_name = first_name,
         )
         user.set_password(password)
         user.save(using=self._db)
         return user

     def create_superuser(self, email, first_name, password):
        user = self.create_user(email, 
            password=password,
           first_name=first_name,
         )
        user.is_superuser=False
        user.is_admin = False
        user.is_staff = False
        user.save(using=self._db)
        return user

class UsrAccounts(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=255, unique=True)
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255, blank=True)
    usr_bio = models.CharField(max_length = 500, blank=True)
    image = models.ImageField(upload_to = user_directory_path, null= True, blank=True)
    joined = models.DateTimeField(auto_now=False, auto_now_add=True)
    last_updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    # Calls the Model Manager
    objects = UsrAccountsManager()

    # Sets username field and required fields
    USERNAME_FIELD = 'email'
    REQUIRED_FIELD = ['first_name']

    # Changes table name from model name
    class Meta:
      db_table = 'usr_accounts'


    def __str__(self):
        return '%s %s' % (self.first_name, self.last_name)

   def __unicode__(self):
       return '%s %s' % (self.first_name, self.last_name)

    def get_full_name(self):
        return '%s %s' % (self.first_name, self.last_name)

     # Creates short name (first name)
    def get_short_name(self):
        return self.first_name

书模型

def user_directory_path(instance, filename):
    return 'books/book_{0}/{1}/'.format(instance.title, filename)

# Books Model Created
class Books(models.Model):
    ONESTAR = "BD"
    TWOSTAR = "Ok"
    THREESTAR = "GD"
    FOURSTAR = "VG"
    FIVESTAR = "EX"
    DEFAULT = "NA"
    READ  = "RB"
    NOT_READ = "NR"
    WANT_READ = "WR"

    BOOK_REVIEW_CHOICES = (
    (DEFAULT, 'Rate Book'),
    (FIVESTAR, 'Excellent'),
    (FOURSTAR, 'Very Good'),
    (THREESTAR, 'Good'),
    (TWOSTAR,'Okay'),
    (ONESTAR, 'Bad'),
     )

    READ_BOOKS_CHOICES = (
    (READ,  'Read Book'),
    (NOT_READ, 'Didnt Read Book'),
    (WANT_READ, 'Want To Read Book')
    )

   user = models.ManyToManyField('accounts.UsrAccounts', blank =True)
   category = models.ManyToManyField('Category')
   title = models.CharField(max_length=300)
   author = models.CharField(max_length=255)
   description = models.CharField(max_length=500)
   book_rating = models.CharField(max_length=2,choices=BOOK_REVIEW_CHOICES,  default = DEFAULT)
   read_status = models.CharField(max_length=2, choices=READ_BOOKS_CHOICES, default = READ)
   image = models.ImageField(upload_to = user_directory_path, null= True, blank=True)
   date_added = models.DateTimeField(auto_now=False, auto_now_add=True)
   last_updated = models.DateTimeField(auto_now=True, auto_now_add=False)

   def __str__(self):
    return self.title

   def __unicode__(self):
    return self.title

类别模型

#Category Model
class Category(models.Model):
    name = models.CharField(max_length=255, unique=True)

    class Meta:
        ordering = ('name',)

    def __str__(self):
        return self.name

    def __unicode__(self):
        return self.name

查看

def addBook(request, id=None):
    uid = request.user.id
    myBook = get_object_or_404(UsrAccounts, id = uid)
    if request.method == 'POST':
        form = AddBook(request.POST, instance = myBook)
        if form.is_valid():
            new_book = form.save(commit=False)
            newbook.save()
            form.save_m2m()
            print new_book
            return HttpResponse("Success")
    else:
        form = AddBook()
    context = {
        'addForm': form,
    }
    return render(request, 'books/base_books_addBooks.html', context)

表格

class AddBook(forms.ModelForm):

class Meta:
    model = Books
    fields = ['title', 'author', 'description', 'book_rating', 'read_status', 'image', 'category']
    exclude = ['date_added', 'last_updated']

模板

<form action="" method="POST">
            {% csrf_token %}
                {%for field in addForm%}
                    <label class="formLabel" for="{{ field.name }}">{{ field.label }}<span class="required"> *</span></label><br/>
                {{ field }}<br/>
                {%endfor%}
                <button class="btn btn-success formBtn" type="submit" value="login">Add Book</button>
            </form>

表单数据不会保存到数据库,我做错了什么?

1 个答案:

答案 0 :(得分:0)

我明白了:

def addBook(request):
    uId = request.user.id 
    print(uId)
    if request.method == 'POST':
        form = AddBook(request.POST)
        if form.is_valid():
            newbook = form.save(commit=False)
            newbook.save()
            newbook.user.add(uId)
            form.save_m2m()
    else:
        form = AddBook()
    context = {
        'addForm': form,
    }
    return render(request, 'books/base_books_addBooks.html', context)