I have a form in my site to get a report about some "collective payment". It has 3 main field: Value, date of payment and who paid.
The field "who paid" is a table containing the name of all users and a checkbox.
Currently I'm looping over all users, adding their full names to the table with a single checkbox. But I don't know how to get this data in my form associating it with each user name (just the text).
How can I get multiple BooleanFields in my form ? Is there a way of associate each BooleanField with an user's name?
model.py
from django.db import models
#created_date attibute needs it
from django.utils import timezone
# This Model is a super class "Financial Transaction"
class GroupTransaction(models.Model):
name = models.CharField(max_length=257, default='')
who_paid = models.CharField(max_length=257, default='')
value = models.DecimalField(max_digits=6, decimal_places=2)
justification = models.CharField(max_length=257, default='')
created_date = models.DateTimeField(default=timezone.now)
date = models.CharField(max_length=257, default='')
receipt = models.FileField(upload_to='comprovantes', blank=True, null=True)
its_type = models.CharField(max_length=257, default='')
def __str__(self):
#INCOMPLETOreturn "%s fez a movimentação financeira de %d para %s no dia " % (self.name, self.restaurant)
return "%s - %s" % (self.name , self.who_paid)
view.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from deposit.forms import DepositForm,MonthlyDepositForm
from django.contrib.auth.models import User
# Create your views here.
#login_required
def deposito(request):
if request.method == 'POST':
form = DepositForm(request.POST, request.FILES)
if form.is_valid():
form.save()
HttpResponseRedirect('/historico/')
else:
print (str(form.errors.as_data()))
else:
form = DepositForm()
groupForm = MonthlyDepositForm()
return render(request, 'shell/app_shell.html', {
'is_deposit' : True,
'title' : 'Deposit',
'transaction' : form,
'groupTransaction' : groupForm,
'users': User.objects.all()
})
form.py
class MonthlyDepositForm(forms.ModelForm):
value = forms.DecimalField()
date = forms.CharField(widget=forms.TextInput(attrs={
'class':'datepicker picker__input',
'readonly':'',
'tabindex':'54',
'aria-haspopup':'True',
'aria-expanded':'false',
'aria-readonly':'false',
'aria-owns':'birthdate_root'
}))
who_paid = forms.BooleanField()
its_type = forms.CharField(widget=forms.HiddenInput(attrs={'readonly':True}),
initial='Deposito Mensal')
class Meta:
model = GroupTransaction
fields = ('value', 'date','who_paid','its_type')
template.html:
<form class="col s12">
{% csrf_token %}
{{ groupTransaction.its_type }}
<div class="row"></div>
<!-- Nome do evento -->
<div class="row">
<div class="input-field col s6">
<!-- <input id="nome_evento" type="number" value="10" step="any" min="0.05" max="400" class="validate" required> -->
{{ groupTransaction.value }}
<label for="nome_evento">Value</label>
</div>
<div class="input-field col s6">
<!-- <input type="text" class="datepicker picker__input" readonly="" tabindex="54" aria-haspopup="true" aria-expanded="false" aria-readonly="false" aria-owns="birthdate_root" required> -->
{{ groupTransaction.date }}
<label for="data-mensal" data-error="Data inválida">Date</label>
</div>
</div>
<!-- Petianos que irão para o evento -->
<table class="striped">
<thead>
<!-- Cabeçalho tabela -->
<tr>
<th>Who Paid</th>
<th>
<div class="switch">
<b class="center-align">Default</b>
<label>
<input type="checkbox">
<span class="lever"></span>
</label>
</div>
</th>
</tr>
<!-- ============= -->
</thead>
<tbody>
{% for user in users %}
<tr>
<td>{{ user.get_full_name }}</td>
<td>
<div class="switch">
<label>
<!-- <input type="checkbox"> -->
{{ groupTransaction.who_paid }}
<span class="lever"></span>
</label>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="row"></div>
<div class="row"></div>
<!-- Botão de registrar saque (submit) -->
<div class="row">
<button class="btn waves-effect waves-light col s6 m3 offset-s6 offset-m9 blue" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</div>
</form>
How the form is:
You need to make who_paid a ManyToManyField(User). Then in the form you can set its widget like this:
class Meta:
model = GroupTransaction
fields = ('value', 'date','who_paid','its_type')
widgets = {
'who_paid': forms.CheckboxSelectMultiple(),
}
That will give you the right structure. Then you can render it manually if you want to change the display.
Related
I am having troubles with submitting the this form. I could submit the form from the admin dashboard but not from the template. What could I be doing wrong?
models.py file:
from teamprofile.models import TeamProfile
from django.utils import timezone
from competition.models import CompetitionProfile
from datetime import datetime
from django.contrib.auth.models import User
class MatchProfile(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
competition = models.ManyToManyField(CompetitionProfile)
home_team = models.ForeignKey(TeamProfile, on_delete=models.CASCADE, related_name = 'home_team')
away_team = models.ForeignKey(TeamProfile, on_delete=models.CASCADE, related_name = 'away_team')
# start_time = models.DateField(blank=True, null=True)
def __str__(self):
return "{} vs {}".format(self.home_team, self.away_team)
forms.py file:
from .models import MatchProfile
class CreateMatchForm(forms.ModelForm):
class Meta():
model = MatchProfile
fields = ('competition', 'home_team', 'away_team')
widgets = {
'competition': forms.Select(attrs={'class': 'uk-select'}),
'home_team': forms.Select(attrs={'class': 'uk-select' }),
'away_team': forms.Select(attrs={'class': 'uk-select' }),
# 'start_time': forms.SelectDateWidget(),
}
views.py file:
from .forms import CreateMatchForm
from .models import MatchProfile
class MatchProfileCreateView(CreateView):
model = MatchProfile
success_url = reverse_lazy('home')
form_class = CreateMatchForm
def form_valid(self, form):
form.instance.owner = self.request.user
return super(MatchProfileCreateView, self).form_valid(form)
.html file:
<form class="uk-child-width-1-2#s uk-grid-small p-4" uk-grid method="POST">
<div> {% csrf_token %}
<h5 class="uk-text-bold mb-2"> Competiton Name </h5>
{{ form.competition }}
<!-- <input type="text" class="uk-input" placeholder="Your name"> -->
</div>
<div>
<h5 class="uk-text-bold mb-2"> Home Teams </h5>
{{ form.home_team }}
<!-- <input type="text" class="uk-input" placeholder="Your seccond"> -->
</div>
<div>
<h5 class="uk-text-bold mb-2"> Away Team </h5>
{{ form.away_team }}
<!-- <input type="text" class="uk-input" placeholder="eliedaniels#gmail.com"> -->
</div>
<!-- <div>
<h5 class="uk-text-bold mb-2"> Organizer Contact</h5>
{{ form.organizer_contact }} -->
<!-- <input type="text" class="uk-input" placeholder="+1 555 623 568 ">
</div> -->
<div class="uk-flex uk-flex-right p-4">
<button class="button soft-primary mr-2">Cancel</button>
<button type="submit" class="button primary">Create Match</button>
</div>
</form>
I am definitely doing something the wrong way but I can't seem to figure it out. Other forms built with same method and template seems to be working.
My terminal would show that a POST request was made yet it still doesn't work
I would find that error was from forms.py:
Turns out the POST request send a field input different from what was declared on the model.
I changed the
'competition': forms.Select(attrs={'class': 'uk-select'}),.
to
'competition': forms.SelectMultiple(attrs={'class': 'uk-select'}),
Difference being forms.SelectMultiple as the model was a ManyToManyField.
I've a trouble with an update view and a delete view. Below the code:
views.py
from django.shortcuts import get_object_or_404, redirect, render
from django.utils.text import slugify
from .forms import BlogTagForm
from .models import BlogTag
def updateBlogTag(request, slug_tag=None):
update_tag = get_object_or_404(BlogTag, slug_tag=slug_tag)
form = BlogTagForm(request.POST or None, instance=update_tag)
if form.is_valid():
update_tag = form.save(commit=False)
update_tag.slug_tag = slugify(update_tag.tag_name)
update_tag.save()
return redirect('tag_list')
context = {
'form': form,
}
template = 'blog/editing/create_tag.html'
return render(request, template, context)
def deleteBlogTag(request, slug_tag):
if request.method == 'POST':
tag = BlogTag.objects.get(slug_tag=slug_tag)
tag.delete()
return redirect('tag_list')
models.py
from django.db import models
from django.urls import reverse
class BlogTag(models.Model):
tag_name = models.CharField(
'Tag',
max_length=50,
help_text="Every key concept must be not longer then 50 characters",
unique=True,
)
slug_tag = models.SlugField(
'Slug',
unique=True,
help_text="Slug is a field in autocomplete mode, but if you want you can modify its contents",
)
def __str__(self):
return self.tag_name
def get_absolute_url(self):
return reverse("single_blogtag", kwargs={"slug_tag": self.slug_tag})
class Meta:
ordering = ['tag_name']
forms.py
from django import forms
from .models import BlogTag
class BlogTagForm(forms.ModelForm):
tag_name = forms.CharField(
max_length=50,
help_text="<small>Write a tag here. The tag must be have max 50 characters.</small>",
widget=forms.TextInput(
attrs={
"placeholder": "Tag",
"type": "text",
"id": "id_tag",
"class": "form-control form-control-lg",
}
),
)
class Meta:
model = BlogTag
fields = ["tag_name"]
urls.py
path("update-tag/", views.updateBlogTag, name='update_tag'),
path("delete-tag/", views.deleteBlogTag, name='delete_tag'),
tag_list.html
<table class="table table-striped shadow">
<thead>
<tr>
<th>Tag</th>
<th>Related Posts</th>
<th class="text-center">Actions</th>
</tr>
</thead>
<tbody>
{% for tag in tag_list %}
<tr>
<td>{{ tag.tag_name }}</td>
<td>{{ tag.tag_blogpost.count }}</td>
<td>
<div class="row justify-content-md-center">
<a class="btn btn-success btn-sm mx-1" href="{#% url 'update_tag' slug_tag=tag.slug_tag %#}">Update</a>
<button class="btn btn-danger btn-sm mx-1" type="button" data-toggle="modal" data-target="#deleteModal">Delete</button>
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h2 class="modal-title text-center" id="deleteModalLabel">Delete Request</h2>
</div>
<div class="modal-body">
<h3>Are you sure to delete this tag?</h3>
<h1 class="py-4"><em><strong>{{ tag.tag_name }}</strong></em></h1>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary btn-sm" data-dismiss="modal">No, don't do this</button>
<form action="{% url 'delete_tag' tag.slug_tag %}" method="POST">
{% csrf_token %}
<button class="btn btn-danger btn-sm" type="submit" name="button">Yes, delete it</button>
</form>
</div>
</div>
</div>
</div>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
I've used the same type of code for another views without problems but in this case I've this error:
UPDATE VIEW NoReverseMatch at /blog/tags/
Reverse for 'update_tag' with keyword arguments '{'slug_tag':
'altro-tag'}' not found. 1 pattern(s) tried: ['blog/update\-tag/$']
DELETE VIEW NoReverseMatch at /blog/tags/
Reverse for 'delete_tag' with arguments '('altro-tag',)' not found. 1
pattern(s) tried: ['blog/delete\-tag/$']
I don't understand where is the error in my code. Someone can tell me where is the error?
The error is coming because you haven't added angle brackets to capture your slug while constructing your URL. I assume your URL looks like this url(r'blog/update-tag/$', updateBlogTag(), name='updated_tag') and url(r'blog/delete-tag/$', deleteBlogTag(), name='delete_tag') they should look like this instead url(r'blog/update-tag/<slug:slug_tag>/$', updateBlogTag(), name='updated_tag') and url(r'blog/delete-tag/<slug:slug_tag>/$', deleteBlogTag(), name='delete_tag') reference
I have a booking system in which i enter dates and timeslots available to book.
the form gets the timeslots from the date and converts it to the user timezone time.
i want the client to select a date and an available timeslot before continuing the form but even with required it doesnt work.
i have a model for timeslots and one for event, date+timeslot
then a form to make client select available date+timeslot, with a html to find timeslot available for each day
html
<option value="">{% if time_slots %}Available Slots{% else %}No Slot Available{% endif %}</option>
{% for time_set in time_slots %}
<option value="{{ time_set.pk }}">{{ time_set.start }} - {{ time_set.end }}</option>
{% endfor %}
models
class TimeSlots(models.Model):
start = models.TimeField(null=True, blank=True)
end = models.TimeField(null=True, blank=True)
class Meta:
ordering = ['start']
def __str__(self):
return '%s - %s' % (self.start.strftime("%I:%M %p"), self.end.strftime("%I:%M %p"))
class Event(models.Model):
event_date = models.DateField()
start = models.ForeignKey(TimeSlots, on_delete=models.CASCADE, verbose_name='Slot Time', null=True)
available = models.BooleanField(default=True)
class Meta:
verbose_name = u'Event'
verbose_name_plural = u'Event'
def __str__(self):
return str(self.event_date)
def get_absolute_url(self):
url = reverse('admin:%s_%s_change' % (self._meta.app_label, self._meta.model_name), args=[self.pk])
return u'%s' % (url, str(self.start))
form
class PatientForm(forms.ModelForm):
class Meta:
model = Patient
fields = ('patient_name', 'patient_country','phone_number', 'email', 'event_date','start', 'timestamp', 'datestamp')
widgets = {
'event_date': DateInput(),
'patient_country': CountrySelectWidget(),
}
def __init__(self, *args, **kwargs):
super(PatientForm, self).__init__(*args, **kwargs)
self.fields['start'].queryset = TimeSlots.objects.none()
if 'event_date' in self.data:
try:
event_id = self.data.get('event_date')
# event = Event.objects.get(pk=event_id)
self.fields['start'].queryset = TimeSlots.objects.filter(event__event_date=event_id, event__available=True)
except (ValueError, TypeError):
pass # invalid input from the client; ignore and fallback to empty City queryset
elif self.instance.pk:
self.fields['start'].queryset = self.instance.timeslot_set
views
class PatientCreate(CreateView):#was CreateView
form_class = PatientForm
template_name = 'appointment/index.html'
def get_context_data(self, **kwargs): # new
context = super(PatientCreate, self).get_context_data(**kwargs)
context['key'] = settings.STRIPE_PUBLISHABLE_KEY
return context
def load_time_slots(request):
event_date = request.GET.get('event_date')
client_timezone = request.GET.get('timezone')
client_timezone = pytz.timezone(client_timezone)
event_date, original_date = get_original_event_date_by_timezone(client_timezone, event_date)
time_slots = TimeSlots.objects.filter(event__event_date= event_date, event__available=True)
final_time_slots = []
for time_slot in time_slots:
start_time = time_slot.start
original_start_date_time = original_date.replace(hour=start_time.hour, minute=start_time.minute,
second=start_time.second,
tzinfo=original_time_zone)
timezone_start_date_time = original_start_date_time.astimezone(client_timezone)
end_time = time_slot.end
original_end_date_time = original_date.replace(hour=end_time.hour, minute=end_time.minute,
second=end_time.second,
tzinfo=original_time_zone)
timezone_end_date_time = original_end_date_time.astimezone(client_timezone)
final_time_slots.append({'pk': time_slot.pk, 'start': timezone_start_date_time.time,
'end': timezone_end_date_time.time})
return render(request, 'appointment/dropdown_list_options.html', {'time_slots': final_time_slots})
def get_original_event_date_by_timezone(client_timezone, event_date):
client_date = datetime.datetime.strptime(event_date, '%Y-%m-%d')
client_date = client_date.replace(tzinfo=client_timezone)
original_date = client_date.astimezone(original_time_zone)
original_date = original_date.replace(hour=0, minute=0, second=0, microsecond=0)
event_date = original_date.strftime('%Y-%m-%d')
return event_date, original_date
def create_event(request, start_time, day_date):
time_slot = TimeSlots.objects.get(start=start_time)
Event.objects.create(event_date=day_date, start=time_slot)
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
form page html
<div class="container" style="margin-top:50px;margin-bottom:50px;">
<div class="stepwizard col-md-offset-3">
<div class="stepwizard-row setup-panel">
<div class="stepwizard-step">
1
<p>Date & Time</p>
</div>
<div class="stepwizard-step">
2
<p>Information</p>
</div>
<div class="stepwizard-step">
3
<p>Calling Method</p>
</div>
<div class="stepwizard-step">
4
<p>Payment Method</p>
</div>
</div>
</div>
<form role="form" action="{% url 'charge' %}" method="POST" id="patientForm" data-times-url="{% url 'ajax_load_time_slots' %}">
<div class="row setup-content" id="step-1">
<div class="col-xs-6 col-md-offset-3">
<div class="col-md-12">
<h3> Appointments date and time</h3>
<div class="form-group">
<label class="control-label" for="id_event_date">Event Date:</label>
<input class="form-control" type="date" name="event_date" id="id_event_date" required="required" />
</div>
<div class="form-group">
<label class="control-label" for="id_start">{% trans "Time:"%}</label>
<p><select required="required" class="form-control" name="start" style="display:inline;" id="id_start">
<option value="">---------</option></select></p><input type="hidden" name="timezone">
<script>$("#patientForm input[name='timezone']").val(Intl.DateTimeFormat().resolvedOptions().timeZone);</script>
</select></p>
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button">Next</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-2">
<div class="col-xs-6 col-md-offset-3">
<div class="col-md-12">
<h3> Step 2</h3>
<div class="form-group">
<label for="id_patient_fname" class="control-label">First Name:</label>
<input name="patient_name" id="id_patient_name" required="required" maxlength="100" type="text" class="form-control" placeholder="Enter First Name" />
</div>
<div class="form-group">
<label class="control-label">Last Name:</label>
<input required="required" maxlength="100" type="text" class="form-control" placeholder="Enter Last Name" />
</div>
<div class="form-group">
<label for="id_phone_number" class="control-label">Phone Number:</label>
<input name="phone_number" id="id_phone_number" required="required" maxlength="100" type="text" class="form-control" placeholder="Enter Phone Number" />
</div>
<div class="form-group">
<label for="id_emal" class="control-label">Email:</label>
<input name="email" id="id_email" maxlength="100" type="text" required="required" class="form-control" placeholder="Enter Email" />
</div>
<div class="form-group">
<label class="control-label">City</label>
<textarea required="required" class="form-control" placeholder="Enter your address"></textarea>
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button">Next</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-3">
<div class="col-xs-6 col-md-offset-3">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Choose The Way You Want to Receive The Video Call:</label>
<label class="radio-inline"><input class="form-control" type="radio" name="optradio" checked>Skype</label>
<label class="radio-inline"><input class="form-control" type="radio" name="optradio">Whatsapp</label>
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button">Next</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-4">
<div class="col-xs-6 col-md-offset-3">
<div class="col-md-12">
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="pk_test_KPSQTmUOl1DLP2eMc7zlvcnS"
data-description="Buying a 30mn Skype Session" data-amount="3000" data-locale="auto"></script>
</div>
</div>
</div>
</form>
</div>
in the html of the form page, i add required to select but it doesnt work
i need client to select lets say 29/01/2019, then if there is availability choose a timeslote lets say 5.30pm-6.00pm, and then only the next arrow will appear
With CreateView it's a little bit tricky when you want to initialize your ModelForm data. So, instead of doing initialization under your ModelForm, do it under the CreateView class like this example:
Your form:
class PatientForm(forms.ModelForm):
class Meta:
model = Patient
fields = ('patient_name', 'patient_country','phone_number', 'email', 'event_date','start', 'timestamp', 'datestamp')
widgets = {
'event_date': DateInput(),
'patient_country': CountrySelectWidget(),
}
Your view:
class PatientCreate(CreateView):
form_class = PatientForm
template_name = 'appointment/index.html'
initial = {}
def get_initial(self):
base_initial = super().get_initial() # it's a simple dict
# initialize your form's data here
# Your logic ...
return base_initial
# The rest of your logic
...
And, in order to know why you need to do this. CreateView inherits from FormMixin which has initial and get_initial() thus will initialize your form's data instead of doing it under your form.
See this links for more details: CreateView MRO and FormMixin
I have a table where I save data(description, x, y, result and creation date) and until now everything works.
I thought then to add a column with the author for each saved line eg:
DES| X | Y | RESULT |CREATION DATE| AUTHOR |
hi | 3| 1 | 4 | 24/02/2015 | username |
then I added in models.py auth:
from django.db import models
from django.utils import timezone
from simpleapp.oper import add_divide
from django.conf import settings
class ElementiTab(models.Model):
author = models.ForeignKey('auth.User', null=True, blank=False)
des = models.CharField(max_length=30)
x = models.FloatField()
y = models.FloatField()
res = models.FloatField(default=0)
created_date = models.DateTimeField(default=timezone.now)
def save(self, *args, **kwargs):
self.res = add_divide(self.x, self.y)
super(ElementiTab, self).save(*args, **kwargs)
def __str__(self):
return self.des
UPDATE:
forms.py
from django import forms
from .models import ElementiTab
class ElementiTabForm(forms.ModelForm):
class Meta:
model = ElementiTab
fields = ('des', 'x', 'y')
views.py
#login_required
def tabval(request):
# if this is a POST request we need to process the form data
valori = ElementiTab.objects.filter().order_by('-created_date')
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = ElementiTabForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
form.save()
# if a GET (or any other method) we'll create a blank form
else:
form = ElementiTabForm()
return render(request, 'simpleapp/simpleapp.html', {'form': form, 'valori': valori})
#user_passes_test(lambda u: u.is_superuser)
def delete(request, id):
valori_to_delete = get_object_or_404(ElementiTab, pk=id).delete()
return redirect(tabval)
simpleapp.html
{% extends 'registration/base_reg.html' %}
{% block title %}SimpleApp-tabval{% endblock %}
{%block content%}
<h4>TABELLA CON DATI</h4>
<form action="/simpleapp/" method="post">
{% csrf_token %}
{{ form.as_table }}
<input type="submit" value="LIST" />
</form>
<form action="/simpleapp/" method="DELETE">
{% csrf_token %}
<input type="submit" name="canc" value="RESET" />
</form>
<br />
<br />
<div class="table-responsive">
<table class="table table-bordered">
<tr class="info">
<td width="15%" align="center"> NOME</td>
<td width="15%" align="center"> X </td>
<td width="15%" align="center"> Y </td>
<td width="15%" align="center"> RISULTATO </td>
<td width="15%" align="center"> DATA CREAZIONE </td>
<td width="15%" align="center"> AUTORE </td>
{% for elementi in valori %}
<div class="elementi">
<tr>
<td>{{elementi.des}}</td>
<td>{{elementi.x}}</td>
<td>{{elementi.y}}</td>
<td>{{elementi.res}}</td>
<td>{{elementi.created_date}}</td>
<td>{{elementi.author}}</td>
<td width="1%">
{% if user.is_superuser %}
Delete
{% else %}
<span style='font-size: small'>Only Admin</span>
{% endif %}
</td>
</div>
{% endfor %}
</table>
</div>
{% endblock content %}
The fact is that the admin page displays a drop-down menu from which I (as administrator) can choose one of the registered user and so I add them both in the table of my app and in the db.
How can I make this process automatic? I.e. after the login, you put data in the table and once saved the data, also the username is saved and should not be the administrator to set it.
I searched a similar question here but I have not found one to help me to solve my problem.
I updated my answere, i misenderstood your question.
Change this in your view
if form.is_valid():
# Creating the object without commiting to database
obj = form.save(commit=False)
# Setting the user from request
obj.author = request.user
# Commiting to the database
obj.save()
i want to auto increament for car_id field which is primary key but after saving registration data the car_id field should automaticaly increament so please anyone can suggest me for this.and my code is as follow.
models.py
class car(models.Model):
car_id = models.IntegerField(max_length=400, primary_key=True)
plate_no = models.IntegerField(max_length=400)
brand = models.CharField(max_length=400)
model = models.CharField(max_length=400)
Condition = models.CharField(max_length=400)
daily_price = models.IntegerField()
def __str__(self):
return ' '.join([
self. ordering,
])
views.py
def display_car(request):
carid_query = car.objects.values('car_id')
plate = car.objects.values('plate_no')
brand = car.objects.values('brand')
model = car.objects.values('model')
price = car.objects.values('daily_price')
condition = car.objects.values('Condition')
query_all = car.objects.all()
data={
'carid_query': carid_query,
'plate': plate,
'brand': brand,
'model': model,
'price': price,
'condition': condition,
'query_all': query_all,
}
return render(request, 'view_car.html', data)
HTML
<body>
<div class="center">
Home  Car Registration  Rent
</div>
<form action="/car/" id="form_id" method="post">
{% csrf_token %}
<div id="head_div">
<h3>car Registration</h3></div>
<table class="center">
<tr><td>
Car_id:<input type="text" name="car_id"><td>
<td>plate no:<input type="text" id="plate_id" name="plate_id"></td></tr>
<tr><td>Brand:<input type="text" id="brand_id" name="brand_id"><td>
<td>Model:<input type="text" name="model_id"></td></tr>
<tr><td>
Daily Price:<input type="text" id="price_id" name="price_id"></td>
<td>
Condition:<select name="select_id"><option value="Good">simple</option>
<option value="middle">A/C</option>
<option value="bad">good</option></select></td>
</tr>
<tr>
<td><input type="submit" id="sub_id" onclick="demo(this.form)"> <input type="button" id="cancel_id" VALUE="Cancel"></td>
</tr>
</table>
</form>
</body>