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>
Related
Please I’m having issue with register vendor, all was working fine before, so I just decided to retest everything have done, to my surprise the code thats working perfectly before is no more working. please help me out guys.............................................................................................................................................................
views.py
def registerRestaurant(request):
# this restrict user from going to Vendor Registration Page after Logged in
if request.user.is_authenticated:
messages.warning(request, "You are already logged in!")
return redirect('dashboard')
if request.method == 'POST':
form = UserForm(request.POST, request.FILES)
v_form = vendorForm(request.POST, request.FILES or None)
if form.is_valid() and v_form.is_valid():
password = form.cleaned_data['password'] # clean_data will return 'dict value'
user = form.save(commit=False)
user.set_password(password)
user.role = User.VENDOR
user.save()
vendor = v_form.save(commit=False)
vendor.user = user
user_profile = UserProfile.objects.get(user=user)
vendor.user_profile = user_profile
vendor.save()
mail_subject = 'Please Activate your Account'
email_template = 'accounts/emails/account_verification_email.html'
send_verification_email(request, user, mail_subject, email_template) #send_verification_email is function created in utils.py
messages.success(request, "Your Account has been Registered Successfully, Please Wait for Approval")
return redirect('registervendor')
else:
messages.error(request, 'An Error occurred during registration!')
else:
form = UserForm()
v_form = vendorForm()
context = {
'form': form,
'v_form': v_form,
}
return render(request, 'vendor/registervendor.html', context)
model.py (vendor)
class Vendor(models.Model):
user = models.OneToOneField(User, related_name='user', on_delete=models.CASCADE)
user_profile = models.OneToOneField(UserProfile, related_name='userprofile', on_delete=models.CASCADE)
vendor_name = models.CharField(max_length=50)
vendor_lincense = models.ImageField(upload_to='vendor/lincense')
is_approved = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.vendor_name
model.py (UserProfile)
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True)
profile_picture = models.ImageField(upload_to='users/profile_pictures', blank=True, null=True)
cover_photo= models.ImageField(upload_to='users/cover_photos', blank=True, null=True)
address = models.CharField(max_length=250, blank=True, null=True)
country = models.CharField(max_length=20, blank=True, null=True)
state= models.CharField(max_length=20, blank=True, null=True)
city = models.CharField(max_length=20, blank=True, null=True)
pin_code = models.CharField(max_length=6, blank=True, null=True)
latitude = models.CharField(max_length=20, blank=True, null=True)
longitude = models.CharField(max_length=20, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now_add=True)
# # Concatenate Address 1 and Address 2
# def full_address(self):
# return f'{self.address_line_1}, {self.address_line_2}'
def __str__(self):
return self.user.email
template
<div id="restaurant-sets-holder">
<form class="form-fields-set foodbakery-dev-restaurant-form" action = "{% url 'registervendor' %}" method = 'post' enctype = 'multipart/form-data'>
{% csrf_token %}
<ul class="register-add-restaurant-tab-container restaurant-information-tab-container">
<li>
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="row">
<ul >
<li>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="field-holder">
<label>First name</label>{{form.first_name}}
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="field-holder">
<label>Last name</label>{{form.last_name}}
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="field-holder">
<label>Restaurant name</label>{{v_form.vendor_name}}
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="field-holder">
<label>Restaurant lincense</label>{{v_form.vendor_lincense}}
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="field-holder">
<label>Email Address</label>{{form.email}}
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="field-holder">
<label>Username</label>{{form.username}}
</div>
</div>
</li>
<li>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
<div class="field-holder">
<label>Password</label>
{{form.password}}
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
<div class="field-holder">
<label>Confirm Password</label>
{{form.confirm_password}}
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</li>
<li>
<ul class="errorlist">
<!-- Fields Error -->
{% for field in form %}
{% if field.errors %}
{% for error in field.errors %}
<li style="color: red">{{error}}</li>
{% endfor %}
{% endif %}
{% endfor %}
<!-- Non Field Error -->
<li style="color: red">{{form.non_field_errors}}</li>
</ul>
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="field-holder">
<div class="payment-holder">
<input type="submit" value="Submit" id="btn-next-restaurant-information" class="bgcolor">
</div>
</div>
</div>
</div>
<!-- Success Message Display -->
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<!-- Load Message -->
{% include 'alerts.html' %}
</div>
</div>
</li>
</ul>
</form>
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 %}
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}]
I am making a blog but I am stuck on a comment replies function. I don't know how to make a Reply function from which users can reply to the comments. I tried a lot but it's still displaying those comments like other comments not as replies to that specific comment.
Here,s the models.py
class Comment(models.Model):
post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name = "comments")
name = models.CharField(max_length = 200)
body = models.TextField(default = True)
pub_date = models.DateTimeField(auto_now_add = True)
reply = models.ForeignKey('Comment',null = True,blank = True,on_delete=models.CASCADE)
class Meta:
ordering = ['-pub_date']
def __str__(self):
return self.name
#property
def get_replies(self):
return self.replies.all()
class Reply(models.Model):
post = models.ForeignKey(Comment,on_delete=models.CASCADE,related_name = "replies")
name = models.CharField(max_length = 200)
body = models.TextField(default = True)
Here's the views.py
def BlogDetail(request,pk):
post = get_object_or_404(Post,pk = pk)
comment = CommentForm(request.POST or None)
subscribe = Subscribe()
reply = ReplyForm(request.POST or None)
if request.method == 'POST':
subscribe = Subscribe(request.POST)
comment = CommentForm(request.POST)
reply = ReplyForm(request.POST)
if comment.is_valid():
comment.instance.post = post
comment.save()
elif subscribe.is_valid():
subscribe = subscribe.save(commit = True)
return redirect('index')
elif reply.is_valid():
reply.instance.com = com
reply = reply.save(commit = True)
return redirect('index')
return render(request,'app/blog.html',{'blog_object':post,'comment':comment,
'subscribe':subscribe,'reply':reply,
})
Here,s the blog.html
<form method='POST' action=".">
{%csrf_token%}
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-4">
<div class="col-inner ts-20 m-sm">
<input type="submit" value="Subscribe to my daily letter" class="btn btn-primary subscribe">
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-8">
<div class="ts-20">
<div class="form-group form-group-with-icon comment-form-email">
{{subscribe.email}}
</form>
<div class="form-control-border"></div>
</div>
</div>
</div>
</div>
<h3 style="color: #ff714a; font-weight:300;">
Leave a comment
</h3>
{% if request.user.is_authenticated %}
<div class="comments">
<div class="row">
<div class="container">
</div>
<form action="." method="post" id="commentform" class="comment-form">
{% csrf_token %}
<div class="col">
<div class="form-group form-group-with-icon comment-form-email">
{{comment}}
<div class="form-control-border"></div>
</div>
</div>
<div class="col">
<p class="form-submit">
<input name="submit" type="submit" id="submit" class="submit" value="Post Comment">
</p>
</div>
</form>
</div>
{% endif %}
<div class="post-comments">
<h3 style="color: #ff714a; font-weight:300;">See the latest comments</h3>
{% for comment in blog_object.get_comments %}
<div class="container">
<div class="row">
<div class="col comment_head">
<strong>{{comment.name}}</strong>
<div class="col comment_body">
<p>{{comment.body}}</p>
</div>
</div>
</div>
<div class="border"></div>
</div>
<form action="." method='POST'>
{% csrf_token %} {{reply}}
<input type="submit" value="submit">
</form>
{% endfor %} {% for reply in com.get_replies %}
<div class="container">
<div class="row">
<div class="col comment_head">
<strong>{{reply.name}}</strong>
<div class="col comment_body">
<p>{{reply.body}}</p>
</div>
</div>
</div>
<div class="border"></div>
<div class="reply">
</div>
</div>
</form>
{% endfor %}
</div>
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>