When im deleting from customer table and employee table im getting this error:
DoesNotExist at /delete/2 Customer matching query does not exist.
Below is the view function code to that wrote to delete the row in each table.
Please, can any one help me to get out from this, any help would be greatly appreciated.
def delete(request, user_id):
delCust = Customer.objects.get(user_id = user_id)
delEmp = Employee.objects.get(user_id = user_id)
delEmp.delete()
delCust.delete()
return redirect("/admins")
Employee table html code:
<table class="table table-responsive d-md-table mb-0">
<thead>
<tr>
<th scope="col" class="border-bottom-0">Job Id</th>
<th scope="col" class="border-bottom-0">Designation</th>
<th scope="col" class="border-bottom-0">Experience</th>
<th scope="col" class="border-bottom-0">Action</th>
</tr>
</thead>
<tbody>
{% for items in Customer %}
<tr>
<td nowrap="">{{items.user_id}}</td>
<td nowrap="">{{items.designation}}</td>
<td nowrap="" class="text-capitalize">{{items.experience}} years</td>
<td nowrap="" class="d-flex">
<button type="submit" class="btn btn-success mr-2 text-capitalize"
data-toggle="modal" data-target="#exampleModal">
Send request
</button>
<!--send request-->
<button type="button" class="btn btn-outline-info mr-2 text-capitalize"
data-toggle="modal" data-target="#studentdetailsmodal">
view
</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
Here is my model for Customer and employee:
class User(AbstractUser):
is_customer = models.BooleanField(default=False)
is_employee = models.BooleanField(default=False)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
class Customer(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True)
phone_number = models.CharField(max_length=20)
location = models.CharField(max_length=20)
email = models.EmailField(max_length=20)
designation = models.CharField(max_length=20)
experience = models.IntegerField(null=True)
salon_name = models.CharField(max_length=20)
salon_category = models.CharField(max_length=20)
class Employee(models.Model):
user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True)
phone_number = models.CharField(max_length=20)
designation = models.CharField(max_length=20)
email = models.EmailField(max_length=20)
current_salary = models.IntegerField()
expected_salary = models.IntegerField()
work_experience = models.CharField(max_length=20)
salon_category = models.CharField(max_length=20)
Related
Django learner here, I am trying to build a simple blog website in which i have created two models:
one is Post:
class Post(models.Model):
title = models.CharField(max_length=255)
author= models.ForeignKey(User, null=True, blank=True , on_delete=models.CASCADE)
article = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
slug = AutoSlugField(populate_from='title', unique=True, null=True, default=None)
category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE )
def __str__(self):
return self.title
second is category:
class Category(models.Model):
categories = models.CharField(max_length=24, blank=True)
def __str__(self):
return self.categories
all i am trying to do is to show Category on home page, and when someone click on any category it will open up all the post related to that category.
This is home.html :
{% extends 'blog_pages/base.html' %}
{% block content %}
<div class = "container p-3">
<h3> This is your home page</h3>
</div>
<div class = "container p-1">
<table class="table table-hover table-bordered">
<thead>
<tr>
<th scope="col">Categories</th>
<th scope="col">About</th>
</tr>
</thead>
<tbody>
{% for c in cat %}
<tr>
<th scope="row"><a href="{% url 'all_articles' c %}" ><p> {{c}}</P></a></th>
<td> How you can win in life</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
this is views.py :
def home(request):
cat = Category.objects.all()
return render(request, 'blog_pages/home.html',{'cat': cat})
def all_articles(request, c):
post = Post.objects.filter(category__contains = c).values()
return render(request,"blog_pages/all_articles.html",{'post':post})
I am getting this error " FieldError(
django.core.exceptions.FieldError: Related Field got invalid lookup: contains"
i have tried many possible ways to solve this problem, but nothing works.
how can i get data from this below django html template
<form action="{% url 'purchase_order_item' p_order.id %}" method="post" enctype="multipart/form-data" class="form-group">
{% csrf_token %}
<table id="example-datatable" class="table table-vcenter table-condensed table-bordered">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Brand Name</th>
<th>Product Type</th>
<th>Category</th>
<th>SubCategory</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for p in product %}
<tr>
<td>{{p.id}}</td>
<td>
{{p.name}}
</td>
<td>{{p.brand}}</td>
<td>{{p.ptype}}</td>
<td>{{p.catname}}</td>
<td>{{p.supplier}}</td>
<td>
<input type="text" id="quantity" name="quantity" value="1" class="form-control">
</td>
<td>
<input type="text" id="unitprice" name="unitprice" value="1" class="form-control">
</td>
<td>
<button type="submit" class="btn btn-primary btn-xs">Add</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</form>
views.py
def purchase_order_item(request,id):
now = datetime.datetime.now()
year = now.year
month = now.month
day = now.day
if (len(str(day))) == 1:
day = '0' + str(day)
if (len(str(month))) == 1:
month = '0' + str(month)
date = str(year) + '-' + str(month) + '-' + str(day)
randstrn = ""
for i in range(5):
randstrn = randstrn + random.choice(string.digits)
# catid = Cat.objects.get(name=name).pk
# news = News.objects.filter(ocatid=catid) # showing post based on master category
supplier = Supplier.objects.all()
p_order = Purchase_order.objects.get(pk=id)
product = Parts.objects.all()
# this is the form for getting data from html
if request.method == 'POST':
quantity = request.POST.get('quantity')
unit_price = request.POST.get('unitprice') # itemid = pk type
nameid = request.POST.get('quantity')
ref_num = Purchase_order.objects.get(pk=id).order_id
order_id = Purchase_order.objects.get(pk=id).order_id # get Purchase Order Id for Relational Referance
sv = Purchase_order_item(
ref_number=ref_num,
product_name='sample_name',
# product_brand='product_brand',
# product_type = 'product_type',
# product_cat = 'product_cat',
# product_sub_cat = 'k',
quantity=quantity,
unit_price = unit_price,
total_price = '12',
order_id=order_id
)
sv.save()
# return redirect('purchase_order_item_list')
return render(request,'back/purchase/assign_purchas_item.html',
{'p_order':p_order,'supplier':supplier,
'product':product}
)
This is my Models.py
class Purchase_order_item(models.Model):
# order_id = models.IntegerField(default=0) # this is a purchase order id for referance purpose and relation both
ref_number = models.IntegerField(default=0)
product_name = models.CharField(max_length=50) # generate an unique Rendome number for farther relation for invoice item
product_brand = models.CharField(max_length=50)
product_type = models.CharField(max_length=50) # genuine or after market
product_cat = models.CharField(max_length=50) # product name
product_sub_cat = models.CharField(max_length=50) # product name
quantity = models.IntegerField(default=0)
unit_price = models.FloatField(default=250)
total_price = models.FloatField()
order_id = models.IntegerField(default=0)
This is my Html screenshot
Now my question is that ..
how can i get all the listed data after click add button as like Name , brand name , product type , category , subcat , quantity , unit price , etc save to purchase_order_item table .
thanks in advance
I have Two Modeks, Employee Type and Employees:
class EmployeeType(models.Model):
type = models.CharField(max_length=500)
enable = models.BooleanField(default=True)
class Employee(models.Model):
date = models.DateTimeField(default=timezone.now)
emptype = models.ForeignKey(EmployeeType, on_delete=models.CASCADE, verbose_name='Type')
male = models.IntegerField(verbose_name='Male', default=0)
female = models.IntegerField(verbose_name='Female', default=0)
others = models.IntegerField(verbose_name='Others', default=0)
This is the relevant view from my forms.py
class EmployeeForm(forms.ModelForm):
class Meta:
model=Employee
exclude = ('date',)
def __init__(self, *args, **kwargs):
super(EmployeeForm, self).__init__(*args, **kwargs)
self.fields['emptype'].widget.attrs = {'class':'form-control'}
self.fields['male'].widget.attrs = {'class':'form-control','placeholder':'Male'}
self.fields['female'].widget.attrs = {'class':'form-control','placeholder':'Female'}
self.fields['others'].widget.attrs = {'class':'form-control','placeholder':'Others'}
and here is views.py:
def addEmployee(request):
employee = EmployeeForm(request.POST or None)
context = {
'employees':employee,
}
return render(request,'add_employee.html',context)
and here is my add_employee.html
<div class="form-group">
<table class="table">
<thead>
<tr>
<th scope="col">Type</th>
<th scope="col">Male</th>
<th scope="col">Female</th>
<th scope="col">Others</th>
</tr>
</thead>
<tbody>
{% for em in employees.emptype %}
<tr>
<td>{{em}}</td>
<td><input type="number" name="male_{{em.id}}" step="any" required="" id="id_male" class="form-control" value="0" ></td>
<td><input type="number" name="female_{{em.id}}" step="any" required="" id="id_female" class="form-control" value="0" ></td>
<td><input type="number" name="others_{{em.id}}" step="any" required="" id="id_others" class="form-control" value="0"></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
Now I am facing problem in getting EmployeeType ID in name field i.e. {{em.id}}. How I can fix this?
You can overrides the default name of the objects of this class by using str method inside the model to show the whatever name you want.
class EmployeeType(models.Model):
type = models.CharField(max_length=500)
enable = models.BooleanField(default=True)
def __str__(self):
return self.type
this way the context will show whatever name is defined in the method or you can user the context_name.field_name which in you case is {{em.type}}
I have the following models
AcsObject class
class AcsObjects(models.Model):
object_id = models.IntegerField(primary_key=True)
object_type = models.ForeignKey('AcsObjectTypes', db_column='object_type')
context = models.ForeignKey('self', blank=True, null=True)
security_inherit_p = models.BooleanField()
creation_user = models.IntegerField(blank=True, null=True)
Projects class
class ImProjects(models.Model):
project = models.ForeignKey('AcsObjects',related_name='project', on_delete=False, primary_key=True)
project_name = models.CharField(max_length=1000)
project_nr = models.CharField(max_length=100)
project_path = models.CharField(max_length=100)
TimesheetTasks class
class TimesheetTasks(models.Model):
task = models.ForeignKey('Projects', related_name='t_task', on_delete=False, primary_key=True)
uom = models.ForeignKey('Categories', related_name='u_uom', on_delete=False)
planned_units = models.FloatField(blank=True, null=True)
billable_units = models.FloatField(blank=True, null=True)
I wrote the following code into views.py file.
class TimesheetData(TemplateView):
template_name = 'timesheet.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["da"] = TimesheetTasks.objects.all()
return context
I want to print a project_name but it is giving me a task_id ( task_id and project_id are same) using jinja template.
timesheet.html
<body>
<p> {{da}} </p>
<table class="table table-light">
<thead class="thead-light">
<tr>
<th>Task </th>
</tr>
</thead>
<tbody>
{% for timesheet in da %}
<tr>
<td> {{timesheet.task}} </td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
It is giving me a blank output
Output
That's simply just because you're not access to product_name field yet.
<tbody>
{% for timesheet in da %}
<tr>
<td> {{timesheet.task}} </td>
</tr>
{% endfor %}
</tbody>
With this, Jinja just render the task id (project id), because Jinja think that you're not need any other information but just the foreign key value. So to be able to see the project_name, you should use this instead: timesheet.task.project_name, it does the job.
<tbody>
{% for timesheet in da %}
<tr>
<td> {{timesheet.task.project_name}} </td>
</tr>
{% endfor %}
</tbody>
Just want to mention that this could lead to another issue (performance issue) when Jinja have to query the data when render the template. To get rid of that, consider to use select_related which is an API of Django Queryset, check it out and gain some experiment that API, it really useful when using Django.
Following the suggestions from my last post I got this far:
Post model:
class Post(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()
Group model:
class Group(models.Model):
title = models.CharField(max_length=200)
url = models.URLField(unique=True)
contact_updated = models.DateField(auto_now=False, auto_now_add=True)
group_status = models.CharField(max_length=20)
admin = models.CharField(max_length=20)
admin_status = models.CharField(max_length=20)
frequency = models.IntegerField() # allowed post frequency
frq_scale = models.CharField(max_length=20, blank=True)
obs = models.TextField(blank=True)
posts = models.ManyToManyField(Post, through='control.Control')
Control model:
class Control(models.Model):
published = models.DateField(auto_now=False, auto_now_add=False)
post = models.ForeignKey('posts.Post', on_delete=models.CASCADE)
group = models.ForeignKey('groups.Group', on_delete=models.CASCADE)
This is control for posts in groups. I can have 1 post published in many groups controlled from Control model.
CORRECTION:
It is possible for a Post to be published in many groups.
How can I produce the table (link above) with those models? Or perhaps there is something I need to change?
The table I want to produce
class Control(models.Model):
published = models.DateField(auto_now=False, auto_now_add=False)
post = models.ForeignKey('posts.Post', on_delete=models.CASCADE)
group = models.ForeignKey('groups.Group', on_delete=models.CASCADE)
class Meta:
unique_together = (post, group )
I ended up creating a dictionary in the view to be passed to the template.
I haven't changed the models.
This is the view:
def control_list(request):
group_status = STATUS_LIST
group_query_idx = 1
period_initial = date.today()-timedelta(days=30)
period_final = date.today()
if request.method == "POST":
filter_form = FilterControl(request.POST)
if filter_form.is_valid():
group_query_idx = int(filter_form.cleaned_data['group_status'])
period_initial = filter_form.cleaned_data['period_initial']
period_final = filter_form.cleaned_data['period_final']
else:
filter_form = FilterControl()
if group_query_idx:
filtered_groups = Group.objects.filter_by_status(group_status[group_query_idx])
queryset_list = Control.objects.filter_by_group_status(group_status[group_query_idx])\
.filter(published__range=[period_initial, period_final])
query = request.GET.get("q")
if query:
queryset_list = queryset_list.filter(
Q(post__content__icontains=query) |
Q(post__title__icontains=query) |
Q(group__title__icontains=query) |
Q(group__admin__icontains=query) |
Q(group__obs__icontains=query)
).distinct() # avoid duplicated items
controls_per_group = {}
for group in filtered_groups:
control = queryset_list.filter(group_id=group.id)
controls_per_group[group.title] = control
context = {
"object_list": queryset,
"title": "Control",
"controls_per_group": controls_per_group,
"column": range(10),
"group_status": group_status,
"filter_form": filter_form,
}
return render(request, "control_list.html", context)
And this is the template:
<table class="table table-hover table-striped">
<thead class="thead-inverse">
<tr>
<th class="text-center">Action</th>
<th class="text-center">Group</th>
{% for value in column %}
<th class="text-center">#</th>
{% endfor %}
</tr>
</thead>
{% for key, value in controls_per_group.items %}
<tr>
<td class="text-center"><a class='btn btn-info btn-xs disabled' href="#"><i class="fa fa-pencil"></i></a>
<i class="fa fa-trash-o"></i></td>
<th class="text-center">{{ key }}</th>
{% for control in value %}
<th class="text-center">{{ control.published | date:"d/m/y" }}<br>{{ control.post.id }}</th>
{% endfor %}
</tr>
{% endfor %}