这些是我的文件:
views.py
from django.shortcuts import render, get_object_or_404, redirect
from .models import Campaign
from .forms import CampaignForm
from users.models import CustomUser
def create(request):
form = CampaignForm()
if request.method == 'POST':
title = request.POST['title']
types = request.POST['type']
category = request.POST['category']
location = request.POST['location']
funding_goal = request.POST['funding_goal']
user = CustomUser.objects.first()
campaign = Campaign.objects.create(
title = title,
types = types,
category = category,
location = location,
funding_goal = funding_goal,
starter = user
)
return redirect('campaign:campaign_list')
return render(request, 'create_a_campaign.html', {'formset':form})
Forms.py
from django import forms
from .models import Campaign
class CampaignForm(forms.ModelForm):
class Meta:
model = Campaign
fields = ['title','types','category','location','funding_goal']
Models.py
class Campaign(models.Model):
types = (
('health', 'Health'),
('education', 'Education'),
)
categories = (
('health', 'Health'),
('education', 'Education'),
)
locations = (
('karachi','Karachi'),
('lahore','Lahore'),
('islamabad','Islamabad'),
('quetta','Quetta'),
('peshawar','Peshawar'),
)
title = models.CharField(max_length=100, null=True, blank=True)
description = models.CharField(max_length=700, null=True, blank=True)
types = models.CharField(max_length=30, choices=types, null=True, blank=True)
category = models.CharField(max_length=30, choices=categories, null=True, blank=True)
tags = TaggableManager(blank=True)
image = models.ImageField(null=True, blank=True)
location = models.CharField(max_length=30, choices=locations, null=True, blank=True)
funding_goal = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True)
starter = models.ForeignKey(user.CustomUser, related_name='campaigns', on_delete=models.CASCADE, null=True, blank=True)
last_updated = models.DateTimeField(auto_now_add=True)
team = models.OneToOneField(Team, related_name='campaigns', on_delete=models.CASCADE, null=True, blank=True)
shop = models.OneToOneField(shop_models.Shop, related_name='campaigns', on_delete=models.CASCADE, null=True, blank=True)
def __str__(self):
return self.title
Html template
Select type
{% for type in formset.types %}
{% endfor %}
每当我保存实例时,它都会在类型列中将类型保存为“option value =” . 如何正确传递数据库中的类型?