Django formsets:以单一形式创建多个模型实例

时间:2016-09-16 08:23:19

标签: python django django-forms inline-formset

这些是我的模特:

class Campaign(models.Model):
  campaign_name= models.CharField(max_length=30)
  campaign_desc= models.CharField(max_length=400)
  cer_date = models.DateTimeField('date created') 

class CampaignForm(ModelForm):
  class Meta:
    model = Campaign
    fields = ['campaign_name', 'campaign_desc'

class Item(models.Model):
  campaign=models.ForeignKey(Campaign)
  item_name=models.CharField(max_length=70)
  item_ID=models.PositiveIntegerField()
  item_url=models.URLField(max_length=400)

我需要一个表单来创建一个包含n个项目的广告系列,并将该广告系列作为其中一个字段。如何完成?有助于以单一形式显示多个模型实例,但不能创建新的模型实例。

我试图通过使用javascript动态创建n个字段来在表单中创建n个项目。所以,我事先并不知道项数。

View.py

def createcampaignform(request) :
  if request.method == 'POST':
    form = CampaignForm(request.POST, request.FILES)
    campaign = form.save(commit=False)   #to change attributes
    if(not campaign.cer_date):
        campaign.cer_date=timezone.now()
    if form.is_valid():
        campaign.save()
        return redirect('/campaign')
    else:
        return HttpResponse("Form is not valid", content_type='text/plain')
else:
    form = CampaignForm()
    return render(request, 'campaign/test/newCampaign_Raw.html', {'form': form})

模板(newcampaign_Raw.html):

<form action="{% url 'campaign:createcampaign' %}" method="post" enctype="multipart/form-data">
<span>Campaign name</span>
  <input type="text" size="20"  name="campaign_name" value="Name"/>
  <input type="text" size="20"  name="campaign_desc" value="Description"/>
<input type="submit" value="Save">
</form>

0 个答案:

没有答案