我想创建一个凭证系统,并允许管理员创建多个具有不同值的凭证代码。
def randomString(stringLenght=8):
letters = string.ascii_letters + string.digits
return ''.join(random.sample(letters, stringLenght))
class VoucherCreateView(CreateView):
model = Voucher
form_class = VoucherCreateForm
template_name = 'voucher/VoucherCreateView.html'
success_url = reverse_lazy('voucher:voucher_create')
def form_valid(self, form):
x = self.request.POST.get('value_x')
x = int(x)
for i in range(0, x):
i = randomString()
e = Voucher(voucher=i, money=self.request.POST['value_money'])
e.save()
return super(VoucherCreateView, self).form_valid(form)
Models.py:
class Voucher(models.Model):
voucher = models.CharField(max_length=8, unique=True)
money = models.SmallIntegerField(blank=True)
created = models.DateTimeField(auto_now_add=True)
used = models.BooleanField(default=False)
Forms.py:
class VoucherCreateForm(forms.ModelForm):
value_x = forms.IntegerField(required=True)
value_money = forms.IntegerField(required=True)
class Meta:
model = Voucher
fields = ['voucher', 'money']
我想使用请求将此添加到我的sql中。关于如何执行此操作的任何想法?
编辑//
解决方案如下,如果是这样的错误,则需要更改return super(VoucherCreateView, self).form_valid(form)
,例如return HttpResponse('success')
答案 0 :(得分:1)
您可以尝试使用django-bluk-create
link
针对您的情况
def form_valid(self, form):
x = self.request.POST.get('value_x')
x = int(x)
objs = [
Voucher(voucher=randomString(), money=int('0' + self.request.POST['value_money']))
for i in range(0, x)
]
Voucher.objects.bulk_create(objs)
return super(VoucherCreateView, self).form_valid(form)