'Django CreateView Trying to register a client With a specific number that goes from 15 to 15
I am trying to make a small system in which I have to put a client number that goes from 15 to 15, but the truth is that I did not succeed to change a global variable.
I am trying to learn how class based views work.
I hope you can help me.
What I'm looking for is to get the find the last record in the database and add 15 to it.
thank you.
models.py
from django.db import models
# Create your models here.
class Customer(models.Model):
name = models.CharField(max_length=50)
customer_num = models.IntegerField(unique=True)
def __str__(self):
return self.name
views.py
from re import template
from django.shortcuts import render
from aplicacion.models import *
from django.views.generic import *
from django.http import HttpResponse
# Create your views here.
class CreateCustomer(CreateView):
model = Customer
template_name = 'createcustomer.html'
fields = ['name']
success_url = "/admin/aplicacion/customer/"
aa = Customer.objects.last().customer_num
def form_valid(self, form):
global aa
while True:
try:
Customer = form.save(commit=False)
Customer.customer_num = self.aa
print(self.aa, "jjjj")
"""If the form is valid, save the associated model."""
#form.instance.customer_num = self.request.POST['name']
break
aa = self.aa + 15
except:
pass
return super().form_valid(form)
Solution 1:[1]
No need for global or anything "fancy".
Define a simple function preferably in the view-file after importing your model:
def get_new_customer_num():
from django.db.models import Max
biggestNumber = Customer.objects.aggregate(Max('customer_num')["customer_num__max"]
return biggestNumber+15
Call this function wherever you need a new customer-number like
customer_num = get_new_customer_num()
I would suggest that the prefix "first letter of the name" etc. is only used in display, so u only have to deal with unique numbers, that's faster and simpler … For display you could build a function for the model (like like the str()-function) calculating a nice customer number like jd_21375 for a customer John/Jane Doe.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | marc_s |
