Python 如何通过Django ModelForm在数据库中添加任意数量的行?

Python 如何通过Django ModelForm在数据库中添加任意数量的行?,python,django,django-models,django-forms,django-views,Python,Django,Django Models,Django Forms,Django Views,在这种情况下,我希望通过Django ModelForm在数据库中插入任意数量的行。我查看了堆栈溢出和Django文档,但无法为我的用例找到它 就我的模型而言,我有一个雇主、一个工作清单和一个类别_工作清单。我希望用户能够选择多个类别(数量待定),并且我希望将所有这些Category\u JobListings作为模型放在我的数据库中 正如您在下面的代码中所看到的,我试图将我的category\u JobListing模型的category字段的小部件覆盖为CheckboxSelectMulti

在这种情况下,我希望通过Django ModelForm在数据库中插入任意数量的行。我查看了堆栈溢出和Django文档,但无法为我的用例找到它

就我的模型而言,我有一个
雇主
、一个
工作清单
和一个
类别_工作清单
。我希望用户能够选择多个类别(数量待定),并且我希望将所有这些
Category\u JobListing
s作为模型放在我的数据库中

正如您在下面的代码中所看到的,我试图将我的
category\u JobListing
模型的category字段的小部件覆盖为
CheckboxSelectMultiple
,但这并没有像我预期的那样起作用。出现多个复选框,但当我尝试提交某项内容时,我会收到一条错误消息,
ValueError at/submit job listing/Category\u job listing无法创建,因为数据未验证

以下是我项目中文件的相关部分

models.py

class Employer(models.Model):
    # user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
    name = models.CharField(max_length=100, unique=True)
    location = models.CharField(max_length=MAXIMUM_LOCATION_LENGTH, choices=COUNTRY_CITY_CHOICES)
    short_bio = models.TextField(blank=True, null=True)
    website = models.URLField()
    profile_picture = models.ImageField(upload_to=get_upload_path_profile_picture, blank=True, null=True)
    admin_approved = models.BooleanField(default=False)

    def __str__(self):
        return self.name

class JobListing(models.Model):
    employer = models.ForeignKey(Employer, on_delete=models.CASCADE)
    job_title = models.CharField(max_length=100)
    job_description = models.TextField()
    job_requirements = models.TextField();
    what_we_offer = models.TextField();
    time_added = models.DateField(default=now);
    job_application_url = models.URLField()
    admin_approved = models.BooleanField(default=False)

    def __str__(self):
        return self.job_title

class Category_JobListing(models.Model):
    job_listing = models.ForeignKey(JobListing, on_delete=models.CASCADE)
    category = models.CharField(max_length=MAXIMUM_INTEREST_LENGTH, choices=INTEREST_CHOICES)
EmployerForm = modelform_factory(Employer, fields=["name", "location", "short_bio", "website", "profile_picture"])#, widgets={"location": LocationWidget})
JobListingForm = modelform_factory(JobListing, fields=["job_title", "job_description", "job_requirements", "what_we_offer", "job_application_url"])
#Category_JobListingForm = modelform_factory(Category_JobListing, fields=["category"])

class Category_JobListingForm(forms.ModelForm):
    category = forms.MultipleChoiceField(
        widget=forms.CheckboxSelectMultiple,
        choices=Category_JobListing._meta.get_field("category").choices,
    )
    class Meta:
        model=Category_JobListing
        fields=[]
def submitJobListing(request):
    if request.method == "POST":
        employer_form = EmployerForm(request.POST, request.FILES)
        job_listing_form = JobListingForm(request.POST, request.FILES)
        category_job_listing_form = Category_JobListingForm(request.POST, request.FILES)
        #check if employer with that name already exists
        employer_name = str(request.POST.get("name", ""))
        employer_with_the_same_name = Employer.objects.get(name=employer_name)
        employer = None
        if (employer_with_the_same_name != None):
            employer = employer_with_the_same_name

        if employer == None and employer_form.is_valid() and job_listing_form.is_valid():
            employer = employer_form.save()

        job_listing = job_listing_form.save(commit=False)
        job_listing.employer = employer
        job_listing.save()
        category_job_listing = category_job_listing_form.save(commit=False)
        category_job_listing.job_listing = job_listing
        category_job_listing.save()
        #return HttpResponseRedirect(reverse("employers:thank_you")) # TODO: Add this URL and template
        return HttpResponse("Your form has been successfully submitted.")

    else:
        employer_form = EmployerForm()
        job_listing_form = JobListingForm()
        category_job_listing_form = Category_JobListingForm()

    context = {
        "employer_form": employer_form,
        "job_listing_form": job_listing_form,
        "category_job_listing_form": category_job_listing_form
    }

    return render(request, 'employers/submit_job_listing.html', context)
forms.py

class Employer(models.Model):
    # user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
    name = models.CharField(max_length=100, unique=True)
    location = models.CharField(max_length=MAXIMUM_LOCATION_LENGTH, choices=COUNTRY_CITY_CHOICES)
    short_bio = models.TextField(blank=True, null=True)
    website = models.URLField()
    profile_picture = models.ImageField(upload_to=get_upload_path_profile_picture, blank=True, null=True)
    admin_approved = models.BooleanField(default=False)

    def __str__(self):
        return self.name

class JobListing(models.Model):
    employer = models.ForeignKey(Employer, on_delete=models.CASCADE)
    job_title = models.CharField(max_length=100)
    job_description = models.TextField()
    job_requirements = models.TextField();
    what_we_offer = models.TextField();
    time_added = models.DateField(default=now);
    job_application_url = models.URLField()
    admin_approved = models.BooleanField(default=False)

    def __str__(self):
        return self.job_title

class Category_JobListing(models.Model):
    job_listing = models.ForeignKey(JobListing, on_delete=models.CASCADE)
    category = models.CharField(max_length=MAXIMUM_INTEREST_LENGTH, choices=INTEREST_CHOICES)
EmployerForm = modelform_factory(Employer, fields=["name", "location", "short_bio", "website", "profile_picture"])#, widgets={"location": LocationWidget})
JobListingForm = modelform_factory(JobListing, fields=["job_title", "job_description", "job_requirements", "what_we_offer", "job_application_url"])
#Category_JobListingForm = modelform_factory(Category_JobListing, fields=["category"])

class Category_JobListingForm(forms.ModelForm):
    category = forms.MultipleChoiceField(
        widget=forms.CheckboxSelectMultiple,
        choices=Category_JobListing._meta.get_field("category").choices,
    )
    class Meta:
        model=Category_JobListing
        fields=[]
def submitJobListing(request):
    if request.method == "POST":
        employer_form = EmployerForm(request.POST, request.FILES)
        job_listing_form = JobListingForm(request.POST, request.FILES)
        category_job_listing_form = Category_JobListingForm(request.POST, request.FILES)
        #check if employer with that name already exists
        employer_name = str(request.POST.get("name", ""))
        employer_with_the_same_name = Employer.objects.get(name=employer_name)
        employer = None
        if (employer_with_the_same_name != None):
            employer = employer_with_the_same_name

        if employer == None and employer_form.is_valid() and job_listing_form.is_valid():
            employer = employer_form.save()

        job_listing = job_listing_form.save(commit=False)
        job_listing.employer = employer
        job_listing.save()
        category_job_listing = category_job_listing_form.save(commit=False)
        category_job_listing.job_listing = job_listing
        category_job_listing.save()
        #return HttpResponseRedirect(reverse("employers:thank_you")) # TODO: Add this URL and template
        return HttpResponse("Your form has been successfully submitted.")

    else:
        employer_form = EmployerForm()
        job_listing_form = JobListingForm()
        category_job_listing_form = Category_JobListingForm()

    context = {
        "employer_form": employer_form,
        "job_listing_form": job_listing_form,
        "category_job_listing_form": category_job_listing_form
    }

    return render(request, 'employers/submit_job_listing.html', context)
views.py

class Employer(models.Model):
    # user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
    name = models.CharField(max_length=100, unique=True)
    location = models.CharField(max_length=MAXIMUM_LOCATION_LENGTH, choices=COUNTRY_CITY_CHOICES)
    short_bio = models.TextField(blank=True, null=True)
    website = models.URLField()
    profile_picture = models.ImageField(upload_to=get_upload_path_profile_picture, blank=True, null=True)
    admin_approved = models.BooleanField(default=False)

    def __str__(self):
        return self.name

class JobListing(models.Model):
    employer = models.ForeignKey(Employer, on_delete=models.CASCADE)
    job_title = models.CharField(max_length=100)
    job_description = models.TextField()
    job_requirements = models.TextField();
    what_we_offer = models.TextField();
    time_added = models.DateField(default=now);
    job_application_url = models.URLField()
    admin_approved = models.BooleanField(default=False)

    def __str__(self):
        return self.job_title

class Category_JobListing(models.Model):
    job_listing = models.ForeignKey(JobListing, on_delete=models.CASCADE)
    category = models.CharField(max_length=MAXIMUM_INTEREST_LENGTH, choices=INTEREST_CHOICES)
EmployerForm = modelform_factory(Employer, fields=["name", "location", "short_bio", "website", "profile_picture"])#, widgets={"location": LocationWidget})
JobListingForm = modelform_factory(JobListing, fields=["job_title", "job_description", "job_requirements", "what_we_offer", "job_application_url"])
#Category_JobListingForm = modelform_factory(Category_JobListing, fields=["category"])

class Category_JobListingForm(forms.ModelForm):
    category = forms.MultipleChoiceField(
        widget=forms.CheckboxSelectMultiple,
        choices=Category_JobListing._meta.get_field("category").choices,
    )
    class Meta:
        model=Category_JobListing
        fields=[]
def submitJobListing(request):
    if request.method == "POST":
        employer_form = EmployerForm(request.POST, request.FILES)
        job_listing_form = JobListingForm(request.POST, request.FILES)
        category_job_listing_form = Category_JobListingForm(request.POST, request.FILES)
        #check if employer with that name already exists
        employer_name = str(request.POST.get("name", ""))
        employer_with_the_same_name = Employer.objects.get(name=employer_name)
        employer = None
        if (employer_with_the_same_name != None):
            employer = employer_with_the_same_name

        if employer == None and employer_form.is_valid() and job_listing_form.is_valid():
            employer = employer_form.save()

        job_listing = job_listing_form.save(commit=False)
        job_listing.employer = employer
        job_listing.save()
        category_job_listing = category_job_listing_form.save(commit=False)
        category_job_listing.job_listing = job_listing
        category_job_listing.save()
        #return HttpResponseRedirect(reverse("employers:thank_you")) # TODO: Add this URL and template
        return HttpResponse("Your form has been successfully submitted.")

    else:
        employer_form = EmployerForm()
        job_listing_form = JobListingForm()
        category_job_listing_form = Category_JobListingForm()

    context = {
        "employer_form": employer_form,
        "job_listing_form": job_listing_form,
        "category_job_listing_form": category_job_listing_form
    }

    return render(request, 'employers/submit_job_listing.html', context)
submit\u job\u listing.html

{% extends "base.html" %}
{% block title %} Submit a job {% endblock %}
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ job_listing_form }}
{{ employer_form }}
{{ category_job_listing_form }}
<input type="submit" value= "Submit">
</form>
{% endblock %}
{%extends“base.html”%}
{%block title%}提交作业{%endblock%}
{%block content%}
{%csrf_令牌%}
{{job_listing_form}
{{雇主表格}
{{category_job_listing_form}
{%endblock%}
有人知道我如何实现我想要的东西吗?