I have a specific requirement for a Django model field, essentially I want to create this type of series:
0025-0007
Essentially 4 integer fields, one character, and 4 integer fields thereafter, I don't need an auto-increment as the number changes, is there anything available in Django already that handles such fields, ideally something with automatic validation?
@login_required
def close_lead(request):
if request.method == 'POST':
deal_form = NewDealForm(request.POST)
if deal_form.is_valid():
deal_form.save()
id = request.GET.get('project_id', '')
obj = Leads.objects.get(project_id=id)
obj.status = "Closed"
obj.save(update_fields=['status'])
## Changing the Forecast Table Entry
forecast = LeadEntry.objects.filter(lead_id=id)
for i in forecast:
m = i
m.stage = "Deal"
m.save(update_fields=['stage'])
messages.success(request, 'You have successfully updated the status from open to Close')
return HttpResponseRedirect(reverse('dashboard'))
else:
messages.error(request, 'Error updating your Form')
id = request.GET.get('project_id', '')
keys = Leads.objects.select_related().get(project_id=id)
form_dict = {'project_id': keys.project_id,
'agent': keys.agent,
'client': keys.point_of_contact,
'company': keys.company,
'service': keys.services,
'licenses': keys.expected_licenses,
'country_d': keys.country
}
form = NewDealForm(initial=form_dict)
return render(request,
"account/close_lead.html",
{'form': form})
## HTML
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% load static %}
{% block title %}Close Lead{% endblock %}
{% block content %}
<h1>Close a Lead</h1>
<div >
<form method="post" id="close-lead">
{% csrf_token %}
<div >
<div >
<div >
<div >
{{ form.project_id|as_crispy_field }}
{{ form.agent|as_crispy_field }}
{{ form.sales_order|as_crispy_field }}
</div>
</div>
<div >
<div >
{{ form.company|as_crispy_field }}
{{ form.country_d|as_crispy_field }}
</div>
<div >
{{ form.client|as_crispy_field }}
</div>
</div>
<div >
<div >
{{ form.service|as_crispy_field }}
{{ form.revenue|as_crispy_field }}
{{ form.comments|as_crispy_field }}
</div>
<div >
{{ form.licenses|as_crispy_field }}
</div>
</div>
</div>
</div>
<input type="submit" value="Create Deal">
</form>
{% endblock %}
CodePudding user response:
You can define a validator and work with a CharField
and a RegexValidator
[Django-doc]:
from django.db import models
from django.core.validators import RegexValidator
class MyModel(models.Model):
my_field = models.CharField(
max_length=9,
validators=[RegexValidator(r'\d{4}.\d{4}', 'The value should be four digits, a character and four digits')]
)
If the separator between the four digits is always a hyphen, you use r'\d{4}-\d{4}'
instead.