How to count objects in django - django

Thank you all for always sharing your knowledge here.
I have an issue with counting an object in Django. I am currently learning and working on a basic HR system and already have my views, models, et al set up. I plan to have an interface whereby I can print out employees count based on gender. The one I currently have set up is increasing the counts for both male and female any time I create a new employee. Please how do I correct this anomaly?
views.py
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.shortcuts import render
from django_tables2 import RequestConfig
from django_tables2.export import TableExport
from .models import Employee
from .models import EmployeeFilter
from .tables import EmployeeTable
#login_required()
def employees(request):
filter = EmployeeFilter(request.GET, queryset=Employee.objects.all())
table = EmployeeTable(filter.qs)
RequestConfig(request, paginate={"per_page": 15}).configure(table)
count = Employee.objects.all().count()
male_count = Employee.objects.filter(gender__contains='Male').count()
female_count = Employee.objects.filter(gender__contains='Female').count()
user_count = User.objects.all().count()
export_format = request.GET.get("_export", None)
if TableExport.is_valid_format(export_format):
exporter = TableExport(export_format, table)
return exporter.response("table.{}".format("csv", "xlsx"))
return render(request, "employees/employees.html", {
"table": table,
"filter": filter,
"count": count,
"male_count": male_count,
"female_count": female_count,
"user_count": user_count,
})
template.html
{% extends "employees/base.html" %}
{% load render_table from django_tables2 %}
{% load django_tables2 %}
{% load querystring from django_tables2 %}
{% block content %}
<!--Data overview-->
<div class="container data overview">
<div class="row">
<div class="col-md-3">
<div class="container-fluid bg-warning data-ov-container">
<div class="row">
<div class="col-8">
<h6 class="data-heading font-weight-bold">Total Employees</h6>
<p class="data-text ">{{ count }}</p>
</div>
<div class="col-4">
<i class="fas fa-users data-icon"></i>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="container-fluid bg-dark data-ov-container">
<div class="row">
<div class="col-9">
<h6 class="data-heading text-white font-weight-bold">Male Employees</h6>
<p class="data-text text-white">{{ male_count }}</p>
</div>
<div class="col-3">
<i class="fas fa-male data-icon text-white"></i>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="container-fluid bg-danger data-ov-container">
<div class="row">
<div class="col-9">
<h6 class="data-heading text-white font-weight-bold">Female Employees</h6>
<p class="data-text text-white">{{ female_count }}</p>
</div>
<div class="col-3">
<i class="fas fa-female data-icon text-white"></i>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="container-fluid bg-secondary data-ov-container">
<div class="row">
<div class="col-8">
<h6 class="data-heading text-white font-weight-bold">Active Users</h6>
<p class="data-text text-white">{{ user_count }}</p>
</div>
<div class="col-4">
<i class="fas fa-users-cog data-icon text-white"></i>
</div>
</div>
</div>
</div>
</div>
</div>
<!--Employees data-->
<div class="filter-container container-fluid">
<div class="row">
<div class="col-md-9">
<!--filter form-->
<form action="" class="form form-inline employee-filter-form" method="get">
<legend class="mb-2">Filter employee records</legend>
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ filter.form.first_name.errors }}
{{ filter.form.first_name }}
</div>
<div class="fieldWrapper">
{{ filter.form.last_name.errors }}
{{ filter.form.last_name }}
</div>
<button aria-expanded="false" aria-haspopup="true"
class="ml-2 btn btn-danger filter-btn" type="submit">
Filter
</button>
</form>
</div>
<div class="col-md-3 download-btn-col">
<button aria-expanded="false" aria-haspopup="true"
class="mr-3 btn btn-success" type="submit">
<i class="fas fa-upload"></i> Import
</button>
<div class="btn-group download-btn">
<button aria-expanded="false" aria-haspopup="true"
class="btn btn-warning dropdown-toggle"
data-toggle="dropdown" type="button">
<i class="fas fa-file-export"></i> Export
</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="{% querystring '_export'='csv' %}">csv</a>
<a class="dropdown-item" href="{% querystring '_export'='xlsx' %}">xlsx</a>
</div>
</div>
</div>
</div>
</div>
<!-- data rendered here -->
{% render_table table 'django_tables2/bootstrap.html' %}
<!-- data rendered here -->
{% endblock content %}
models.py
...
GENDER_CHOICES = (
('FEMALE', 'Female'),
('MALE', 'Male'),
("DWTS" "Don't want to say"),
)
...
#python_2_unicode_compatible
class Employee(models.Model):
# basic information of employee
first_name = models.CharField(_('first name'), max_length=40)
last_name = models.CharField(_('last name'), max_length=40)
emp_photo = models.ImageField(_('passport'))
date_of_birth = models.DateField(_('birthday'))
gender = models.CharField(_('gender'), max_length=15, choices=GENDER_CHOICES, default=['MALE', 'Male'])
house_address = models.CharField(_('house address'), max_length=100)
city_of_residence = models.CharField(_('city'), max_length=100)
state_of_residence = models.CharField(_('state'), max_length=100, choices=NIGERIAN_STATE_CHOICES)
country_of_residence = models.CharField(_('country'), max_length=100, choices=COUNTRY_CHOICES,
default=[156, 'Nigeria'])
state_of_origin = models.CharField(_('state of origin'), max_length=100, choices=NIGERIAN_STATE_CHOICES)
class Meta:
verbose_name = _('Employee')
verbose_name_plural = _('Employees')
def __str__(self):
return "{} {}".format(self.first_name, self.last_name)
#python_2_unicode_compatible
class EmployeeFilter(django_filters.FilterSet):
first_name = django_filters.CharFilter(lookup_expr='iexact', widget=TextInput(
attrs={'placeholder': 'First name', 'class': 'input_search'}))
last_name = django_filters.CharFilter(lookup_expr='iexact',
widget=TextInput(attrs={'placeholder': 'Last name', 'class': 'input_search'}))
class Meta:
model = Employee
fields = ["first_name", "last_name", ]

I think you need to remove contains from your filter:
male_count = Employee.objects.filter(gender='Male').count()
female_count = Employee.objects.filter(gender='Female').count()
Or make a single request:
male_femail_count = Employee.objects.values('gender').annotate(count=Count('id'))
# result
# [{'gender': 'Male', 'count': 2}, {'gender': 'Female', 'count': 3}]

Related

For loop not showing on template

i'm trying to display the news on my website but for some reason its not showing, the first loop is ok, but the second one is not displaying anything where it suposed to be.
Here are my code:
HTML:
<div class="container-fluid">
<div class="container">
<div class="row">
{% for cat in cats %}
<div class="col-lg-6 py-3">
<div class="bg-light py-2 px-4 mb-3">
<h3 class="m-0">{{cat.category_name}}</h3>
</div>
<div class="owl-carousel owl-carousel-3 carousel-item-2 position-relative">
{% for news in category.news_set.all %}
{% if forloop.counter == 4 %}
<div class="position-relative">
<img class="img-fluid w-100" src="{{news.cover.url}}" style="object-fit: cover;">
<div class="overlay position-relative bg-light">
<div class="mb-2" style="font-size: 13px;">
{{news.title}}
<span class="px-1">/</span>
<span>{{news.created_at}}</span>
</div>
<a class="h4 m-0" href="">{{news.description}}</a>
</div>
</div>
{% endif %}
{% endfor %}
</div>
</div>
{% endfor %}
</div>
</div>
views.py:
def home (request):
cats = Category.objects.all()[0:4]
articles = Article.objects.all()
return render (request,'pages/home.html',
context={
'articles': articles,
'cats': cats,
})
models.py
class Category(models.Model):
category_name = models.CharField(max_length=65)
slug = models.SlugField(unique=True)
class Article(models.Model):
title = models.CharField(max_length=65)
description = models.CharField(max_length=165)
slug = models.SlugField(unique=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
is_published = models.BooleanField(default=False)
cover = models.ImageField(
upload_to='newsroom/covers/%Y/%m/%d/', blank=True, default='')
category = models.ForeignKey(
Category, on_delete=models.SET_NULL, null=True, blank=True,
default=None,)
<div class="owl-carousel owl-carousel-3 carousel-item-2 position-relative">
{% for news in cat.news_set.all %}
{% if forloop.counter == 4 %}
<div class="position-relative">
<img class="img-fluid w-100" src="{{news.cover.url}}" style="object-fit: cover;">
<div class="overlay position-relative bg-light">
<div class="mb-2" style="font-size: 13px;">
{{news.title}}
<span class="px-1">/</span>
<span>{{news.created_at}}</span>
</div>
<a class="h4 m-0" href="">{{news.description}}</a>
</div>
</div>
I am assuming that news is a relationship to category.

How to render error or validation messages to ModelForm in 2022

I've spent several hours researching on the internet, especially the official Django documentation, but still it is not clear to me which is the best option in 2022 (since almost all questions I read on SO are > 6 yo)
and there are diverse opinions on whether crispy forms is better or not.
Is still crispy forms a recommended option?
How can I (and what is the most recommended way to) get the typical validation error messages?
Like: "this field is mandatory" or "this input accepts numbers only"? I've seen some Django pages using those default messages but I don't know how to show them in my ModelForm fields.
Lets say I have the following model:
class Project(models.Model):
project_name = models.CharField(max_length=250, null=False, blank=False)
status = models.CharField(
max_length=250,
null=True,
blank=True,
default=PROJECT_STATUS_DEFAULT,
choices=PROJECT_STATUS,
)
creation_date = models.DateField(max_length=250, null=False, blank=False)
project_code = models.IntegerField(null=True, blank=True)
notes = models.CharField(max_length=250, null=True, blank=True)
And for the Project model I have the following ModelForm:
class CreateNewProjectForm(ModelForm):
creation_date = forms.DateField(widget=forms.DateInput(format = '%d/%m/%Y'), input_formats=settings.DATE_INPUT_FORMATS) #UK Date format
class Meta:
model = Project
fields = '__all__'
The view, when I try to create a new object Project:
def add_new_project(request):
context = {}
if request.method == 'POST':
form = CreateNewProjectForm(request.POST)
if form.is_valid():
form.save()
return redirect('project_page')
else:
print (form.errors)
form = CreateNewProjectForm()
context['form'] = form
return render(request, 'new_project.html', context)
HTML part:
<div class="card h-100">
<div class="card-header project-page-header">
<h3>Create A New Project</h3>
</div>
<div class="card-body px-0 new-project-card-body">
<div class="cardItem">
<div class="row">
<div class="col">
<div class="row">
<div class="tab-pane fade show active" id="general">
<form id="newProjectForm" method="POST" action="new_project">
{% csrf_token %}
<div class="accordion accordion-flush" id="accordionGeneral">
<div class="accordion-item">
<h2 class="accordion-header" id="general-headingOne">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#general-collapseOne" aria-expanded="false" aria-controls="general-collapseOne">
Details
</button>
</h2>
<div id="general-collapseOne" class="accordion-collapse collapse show" aria-labelledby="general-headingOne" data-bs-parent="#accordionGeneral">
<div class="accordion-body">
<div class="row">
<div class="col-5">
<ul class="list-unstyled">
<li class="mt-3">
<div class="row">
<div class="col-sm ph-tabs-field-label">
Project Name
</div>
<div class="col-sm">
<input type="text" name="project_name" class="form-control" aria-label="Project Name">
</div>
</div>
</li>
<li class="mt-3">
<div class="row">
<div class="col-sm ph-tabs-field-label">
Status
</div>
<div class="col-sm">
<select name="status" class="selectpicker show-tick w-100" aria-label="Status">
{% for status in project_status %}
{% if forloop.first %}
<option value="{{ status.id }}" selected>{{ status.text }}</option>
{% else %}
<option value="{{ status.id }}">{{ status.text }}</option>
{% endif %}
{% endfor %}
</select>
</div>
</div>
</li>
<li class="mt-3">
<div class="row">
<div class="col-sm ph-tabs-field-label">
Creation Date
</div>
<div class="col-sm">
<input type="text" name="creation_date" class="form-control">
</div>
</div>
</li>
<li class="mt-3">
<div class="row">
<div class="col-sm ph-tabs-field-label">
Project Code
</div>
<div class="col-sm">
<input type="text" name="project_code" class="form-control">
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="accordion-item">
<h2 class="accordion-header" id="general-headingThree">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#general-collapseThree" aria-expanded="false" aria-controls="general-collapseThree">
Note
</button>
</h2>
<div id="general-collapseThree" class="accordion-collapse collapse" aria-labelledby="general-headingThree" data-bs-parent="#accordionGeneral">
<div class="accordion-body"><textarea name="notes" class="form-control" rows="7"></textarea></div>
</div>
</div>
<button type="submit" id="projectEditBtn" form="newProjectForm" class="btn btn-info rounded-0">Save</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
I saw solutions like this, but the problem is that my form fields are spread over different accordions, I can't use something like {% if form.errors %}, I need something more specific for each field.
First update your views like this
def add_new_project(request):
context = {}
if request.method == 'POST':
form = CreateNewProjectForm(request.POST)
if form.is_valid():
form.save()
return redirect('project_page')
else:
print (form.errors)
context['form'] = form
return render(request, 'new_project.html', context)
context['form'] = CreateNewProjectForm()
return render(request, 'new_project.html', context)
You can specify error for each field like this
{% if form.field_name.errors %}
{{ form.field_name.errors }}
{% endif %}

request.GET.get() returns None all the time - django

I have these two models :
class Payment(models.Model):
admin = models.ForeignKey(User,on_delete=models.PROTECT)
client_seller = models.ForeignKey(ClientCompany,on_delete=models.PROTECT,blank=True)
next_payment = models.OneToOneField(NextPayment,blank=True,null=True,related_name='next_payments',on_delete=models.PROTECT)
#others
class NextPayment(models.Model):
next_payment = models.DateTimeField()
status = models.BooleanField(default=True)
I want to create NextPayment instance before Payment instance will be create , and assign the NextPayment object to Payment > next_payment field ! here is my views.py
#login_required
def create_payment(request):
main_form = PaymentForm()
next_paymentform = NextPaymentForm()
next_payment= request.GET.get('next_payment')
print(next_payment)
if request.method == 'POST' and request.is_ajax():
main_form = PaymentForm(request.POST)
next_paymentform = NextPaymentForm(request.POST)
if main_form.is_valid():
main_obj = main_form.save(commit=False)
main_obj.admin = request.user
if next_payment:
date_next = next_paymentform(next_payment=next_payment)
#date_next = NextPayment(next_payment=next_payment,status=True) also tried this
date_next.save()
main_obj.next_payment= date_next
main_obj.save()
else:
main_obj.save()
data = {
'id':main_obj.id
}
return JsonResponse({'success':True,'data':data})
else:
return JsonResponse({'success':False,'error_msg':main_form.errors,'next_paymentform':next_paymentform.errors})
return render(request,'payments/pay.html',{'main_form':main_form,'next_paymentform':next_paymentform})
my forms.py
class NextPaymentForm(forms.ModelForm):
next_payment = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M'],widget=forms.DateTimeInput(attrs={'type':'datetime-local','class':'form-control'}),required=False)
class Meta:
model = NextPayment
fields = ['next_payment']
class PaymentForm(forms.ModelForm):
class Meta:
model = Payment
fields = ['client_seller','type_of_payment','price','note']
here is my template
<form action="" method="POST" id="create-payment-form">{% csrf_token %}
<div class="row">
<div class="col-md-6">
<div class="form-group">
<i class="fas fa-user-check"></i>
<label>name </label>
{{ main_form.client_seller | add_class:'form-control' | append_attr:'onchange:currentPaymentBalance();' }}
</div>
</div>
<!-- /.col -->
<div class="col-md-6">
<div class="form-group">
<i class="fas fa-money-check-alt"></i>
<label>number</label>
<input type="number" class="form-control" disabled id="balance_client">
</div>
<!-- /.form-group -->
</div>
<div class="col-md-6">
<div class="form-group">
<i class="far fa-handshake"></i>
<label> type</label>
{{ main_form.type_of_payment | add_class:'form-control' }}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<i class="fas fa-money-check-edit-alt"></i>
<label> price</label>
{{ main_form.price }}
</div>
</div>
<div class="col-md-12 col-12">
<div class="form-group text-center ">
<i class="far fa-comment-dots"></i>
<label class="">note</label>
{{ main_form.note | add_class:'form-control' }}
</div>
</div>
<div class="col-md-6 justify-content-center">
<div class="form-group">
<i class="fas fa-quote-right"></i>
<label> next payment</label>
{{ next_paymentform.next_payment }}
</div>
</div>
<!-- /.col -->
</div>
<!-- /.row -->
<div class="card-footer">
<div class="row justify-content-center">
<button type="submit" class="btn btn-lg btn-success">زیادکردن</button>
</div>
</div>
</form>
next_payment prints None! but it wasn't None
but doesn't work, and only saves the main form! I need to check if the next_payment exists then create an instance of NextPayment and assign that new instance to the Payment model?
any idea is much appreciated.
thank you in advance...
Since your form is sending a POST request you have to change
next_payment= request.GET.get('next_payment')
to
next_payment= request.POST.get('next_payment')

Issue with CreateView ,object not created in model on submit

I have issue might missed something , i have created CreateView view for submitting objects in db , all seems to ok , but when i try to submit i don't get anything happen no error at all except
"POST /create_task/ HTTP/1.1" 200 12972 ,
MY code goes as follows , please advice
Thanks
models.py
class MainTask(models.Model):
task_title = models.CharField(max_length=200)
global_task_info = models.TextField(max_length=500,default=None)
complete = models.BooleanField(default=False)
overall_precent_complete = models.PositiveIntegerField(default=0)
created_at = models.DateTimeField(default=datetime.datetime.now())
updated_at = models.DateTimeField(default=datetime.datetime.now())
due_date = models.DateTimeField(default=datetime.datetime.now())
task_location = models.CharField(max_length=400, blank=True, null=True)
global_task_assign = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="global_task_assign",default=1)
TASK_STATUS_CHOICES = [
('ST', 'STARTED'),
('NS', 'NOT STARTED'),
('IP', 'IN PROGRESS'),
('PA', 'PAUSED'),
('CO', 'COMPLETED'),
]
task_status = models.CharField(max_length=2,choices=TASK_STATUS_CHOICES,default='NOT STARTED')
def __str__(self):
return self.task_title
forms.py
class TaskCraetionForm(forms.ModelForm):
TASK_STATUS_CHOICES = [
('ST', 'STARTED'),
('NS', 'NOT STARTED'),
('IP', 'IN PROGRESS'),
('PA', 'PAUSED'),
('CO', 'COMPLETED'),
]
task_title = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Task Title'}))
global_task_info = forms.CharField(max_length=500, widget=forms.Textarea(attrs={'class':'form-control','placeholder':'Task Description'}))
due_date = forms.DateTimeField(widget=forms.DateTimeInput(attrs={
'class': 'form-control',
'id': 'picker'
}))
global_task_assign = forms.ModelChoiceField(queryset= UserProfile.objects.all(), widget=forms.Select(attrs={'class':'form-control'} ))
task_status = forms.ChoiceField(label='', choices=TASK_STATUS_CHOICES, widget=forms.Select(attrs={'class':'form-control'}))
class Meta:
model = MainTask
fields = ['task_title',
'global_task_info',
'due_date',
'global_task_assign',
'task_status',
]
views.py
class CreatTaskView(CreateView):
model = MainTask
template_name = "create_newtask.html"
form_class = TaskCraetionForm
success_url = None
def form_valid(self, form):
f = form.save(commit=False)
f.save()
return super(CreatTaskView, self).form_valid(form)
Thank you very much Alasdair you're comment gave me the direction and more added the following to my HTML template shown below and found out i have issue with my datetime picker format needed to added the following
Thanks
INPUTֹTIMEֹFORMATS = [
'%Y/%m/%d %H:%M']
due_date = forms.DateTimeField(input_formats=INPUTֹTIMEֹFORMATS, widget=forms.DateTimeInput(attrs={
'class': 'form-control',
'id': 'picker'
}))
html temaplate
<form action="" method="POST">
<h3 class="mt-3 text-left">Create New Task</h3>
<hr>
<p class="text-muted text-left">Creat New Itom task</p>
{% csrf_token %}
{% if form.errors %}
<!-- Error messaging -->
<div id="errors">
<div class="inner">
<p>There were some errors in the information you entered. Please correct the following:</p>
<ul>
{% for field in form %}
{% if field.errors %}<li>{{ field.label }}: {{ field.errors|striptags }}</li>{% endif %}
{% endfor %}
</ul>
</div>
</div>
<!-- /Error messaging -->
{% endif %}
<div class="input-group mt-3 mb-3 mr-auto">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1"><i class="fas fa-book-medical"></i></span>
</div>
{{ form.task_title}}
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-pen"></i></span>
</div>
{{form.global_task_info}}
</div>
<!---date time picker-->
<h6 class="text-left">Task Due Date</h6>
<div class="input-group date mb-3 col-3">
<div class="input-group-append">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
{{ form.due_date }}
</div>
<!--end of date time picker-->
<!---user assign-->
<h6 class="text-left">Assign Task to IT member</h6>
<div class="input-group mb-3 mt-3 col-8">
<div class="input-group-prepend">
<div class="input-group-text"><i class="fas fa-user-tie"></i></div>
{{form.global_task_assign}}
</div>
</div>
<!--End Of User Assign-->
<h6 class="text-left">Set Task Status</h6>
<div class="input-group mb-3 mt-3 col-4">
<div class="input-group-prepend">
<div class="input-group-text"><i class="far fa-caret-square-right"></i></div>
</div>
{{form.task_status}}
</div>
<div class="col text-left">
<button type="submit" value="Save" class="btn btn-primary btn-lg text-white mt-2"><span><i class="fas fa-database"></i></span> Create Task</button>
</div>
</form>
</div>
</div>

how to code view with a "submit" AND "delete" method

I have a simple app that takes entries/tasks and distibutes them to appropriate inbox's.
The model, template and view follows. What I want to do is modify the view so that I can
have a functional "delete" button in my form (alongside the "add/submit" button, like in an admin form.):
models.py
class InboxEntry(models.Model):
job_number = models.CharField(validators=[RegexValidator(regex='^\w{8}$', message='Please enter a valid job number', code='nomatch')], max_length=8, unique=False, blank=False, null=False)
cell_number = models.CharField(max_length=4, unique=False, blank=True, null=True)
job_name = models.CharField(max_length=64, unique=False, blank=False, null=False)
request = models.CharField(max_length=64, choices=PRINT_CHOICES)
date_in = models.DateField(("Date"), auto_now=True, auto_now_add=True)
date_due = models.DateTimeField(("Due"),auto_now=False, auto_now_add=False)
basecamp_link = models.URLField(validators=[RegexValidator(regex='^(http|https)://', message='url must begin with http or https', code='nomatch')], blank=True, null=False, max_length=300)
note = models.TextField(max_length=1000, unique=False, blank=True, null=True)
assigned_by = models.ForeignKey(UserProfile, blank=False, null=False)
box = models.CharField(max_length=64, choices=INBOX_CHOICES)
assigned_to = models.ForeignKey(UserProfile, related_name='+', blank=True, null=True)
assigned_team = models.ManyToManyField(ProjectTeam, blank=True, null=True)
status = models.CharField(max_length=30, choices=STATUS_CHOICES, default="Awaiting Action")
accepted_by = models.ForeignKey(UserProfile, related_name='+', blank=True, null=True)
completed_on = models.DateTimeField(("Completed"),auto_now=False, auto_now_add=False, blank=True, null=True)
def __unicode__ (self):
return u'%s %s' % (self.job_number, self.job_name)
class Admin:
pass
views.py
def edit_prdInboxEntry(request, id, userid):
if request.method == 'POST':
a=InboxEntry.objects.get(pk=id)
form = PrdInboxForm(request.POST, instance=a)
if form.is_valid():
form.save()
return HttpResponseRedirect('/production-display/'+ userid +'/')
else:
a=InboxEntry.objects.get(pk=id)
form = PrdInboxForm(instance=a)
user = request.user
u = UserProfile.objects.get(pk=userid)
creativerecords = InboxEntry.objects.filter(box="Creative")
studiorecords = InboxEntry.objects.filter(box="Studio")
records = InboxEntry.objects.filter(assigned_to=u)
return render_to_response('production_InboxEntry.html', {'form': form, 'records': records, 'studiorecords': studiorecords, 'creativerecords': creativerecords, 'user': user}, context_instance=RequestContext(request))
template
<form action="." method="POST">{% csrf_token %}
<div style="display:table;">
<div style="display:table-row;">
<div style="display:table-cell;">
<div class="group_input">
{{ form.assigned_by.errors }}
<label for="id_jassigned_by">Assigned by:</label>
{{ form.assigned_by }}
</div>
</div>
<div style="display:table-cell;"> <div>
<div style="display:table-cell;"> <div>
<div style="display:table-cell;"> <div>
<div style="display:table-cell;"> <div>
<div style="display:table-cell;"> </div>
</div>
<div style="display:table-row;">
<div style="display:table-cell;">
<div class="group_input">
{{ form.job_number.errors }}
<label for="id_job_number">job no:</label>
{{ form.job_number }}
</div>
</div>
<div style="display:table-cell;">
<div class="group_input">
{{ form.cell_number.errors }}
<label for="id_cell_number">cell:</label>
{{ form.cell_number }}
</div>
</div>
<div style="display:table-cell;">
<div class="group_input">
{{ form.job_name.errors }}
<label for="job_name">job name:</label>
{{ form.job_name }}
</div>
</div>
<div style="display:table-cell;">
<div class="group_input">
{{ form.request.errors }}
<label for="request">request:</label>
{{ form.request }}
</div>
</div>
<div style="display:table-cell;">
<div class="group_input">
{{ form.note.errors }}
<label for="id_note">note:</label>
{{ form.note }}
</div>
</div>
<div style="display:table-cell;">
<div class="container">
<!-- <div class='well'> -->
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<label for="id_date_due">date_due:</label>
{{ form.date_due}}
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<!-- </div> -->
<script type="text/javascript">
$(function () {
$('#datetimepicker1').datetimepicker();
});
</script>
</div>
</div>
</div> <!-- end css table-row -->
<div style="display:table-row;">
<div style="display:table-cell;">
<div class="group_input">
{{ form.box.errors }}
<label for="id_box">inbox:</label>
{{ form.box }}
</div>
</div>
<div style="display:table-cell;">
<div class="group_input">
{{ form.assigned_to.errors }}
<label for="assigned_to">assigned_to:</label>
{{ form.assigned_to }}
</div>
</div>
<div style="display:table-cell;">
<div class="group_input">
{{ form.basecamp_link.errors }}
<label for="id_basecamp_link">basecamp:</label>
{{ form.basecamp_link }}
</div>
</div>
<div style="display:table-cell;">
<div class="accepted_by">
{{ form.accepted_by.errors }}
<label for="accepted_by">accepted_by:</label>
{{ form.accepted_by }}
</div>
</div>
<div style="display:table-cell;">
<div class="group_input">
{{ form.status.errors }}
<label for="id_status">status:</label>
{{ form.status }}
</div>
</div>
<div style="display:table-cell;">
<div class="container">
<!-- <div class='well'> -->
<div class="form-group">
<div class='input-group date' id='datetimepicker2'>
<label for="id_completed_on">completed:</label>
{{ form.completed_on}}
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<!-- </div> -->
<script type="text/javascript">
$(function () {
$('#datetimepicker2').datetimepicker();
});
</script>
</div>
</div>
</div> <!-- end css table-row -->
<div style="display:table-row;">
<div style="display:table-cell;"> </div>
<div style="display:table-cell;">
<p><input id="inbox_submit_btn" type="submit" value="add" /></p>
</div>
<div style="display:table-cell;">
<p><input id="inbox_delete_btn" type="submit" value="delete" /></p>
</div>
</div>
</div> <!-- end css table -->
</form>
Can anyone help point me in the right direction. The docs seem to suggest that I need separate views and urls but I'm pretty sure this can be accomplished in a single view?
The docs seem to suggest that I need separate views and urls but I'm pretty sure this can be accomplished in a single view?
You could do this by passing in different POST parameters depending on which button was pressed, I guess. This is still quite a weird thing to want to do though. It's far neater and more maintainable to split them into different views.
You may be under a misapprehension when it comes to the views linking to templates. having two separate views (one for submissions, one for deletions) in no way affects your ability to display the two buttons that link to those view urls in your template.
If you're worried about code reuse (function-based views often share a lot of code, so this is a reasonable complaint) then I suggest looking into class based views
Edit:
It's just a case of linking to your second "delete" view with the button:
<div class="your-button-class" href="{% url "your-delete-view" pk=object.pk %}></div>