在Django中使用ModelForm与ManyToMany关系和中间模型一起工作的步骤如下:
Author
和Book
,并且它们之间有一个多对多关系,通过中间模型AuthorBook
建立。from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author, through='AuthorBook')
class AuthorBook(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
book = models.ForeignKey(Book, on_delete=models.CASCADE)
date_added = models.DateTimeField(auto_now_add=True)
from django import forms
from .models import Author, Book, AuthorBook
class AuthorBookForm(forms.ModelForm):
class Meta:
model = AuthorBook
fields = ['author', 'book', 'date_added']
from django.shortcuts import render
from .forms import AuthorBookForm
def add_author_book(request):
if request.method == 'POST':
form = AuthorBookForm(request.POST)
if form.is_valid():
form.save()
return redirect('success_page')
else:
form = AuthorBookForm()
return render(request, 'add_author_book.html', {'form': form})
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
这样,您就可以在Django中使用ModelForm与ManyToMany关系和中间模型一起工作了。请注意,这只是一个基本示例,您可能需要根据您的具体需求进行调整。
领取专属 10元无门槛券
手把手带您无忧上云