Error message: Employee matching query does not exist - django

I have model Employee and same table in my local database. I need to have the possibility to edit any record and save it locally. When I have something in the webflow_id field I got this error when I tried to select the edit option: Employee matching query does not exist.
When I tried to edit record without this webflow_id it doesn't change, but creates a new record.
my views.py:
def staff_edit(request, webflow_id):
#employees = Employee.objects.all()
#print(employees)
if request.method == 'GET':
if webflow_id == 0:
form = EmployeeEditForm()
else:
try:
#employees = Employee.objects.get(pk=webflow_id)
employees = Employee.objects.get(pk=webflow_id)
except Employee.DoesNotExist:
raise Http404("Employee DoesNotExist")
form = EmployeeEditForm(instance=employees)
return render(request, 'staffedit.html', {'form': form})
else:
if webflow_id == 0:
form = EmployeeEditForm(request.POST)
else:
employees = Employee.objects.get(pk=webflow_id)
form = EmployeeEditForm(request.POST, instance=employees)
if form.is_valid():
form.save()
return redirect('feedback:staff')
context = {'form': form} #when the form is invalid
return render(request, 'staffedit.html', context)
models.py:
class Employee(models.Model):
webflow_id = models.CharField(max_length=100, primary_key=True, default=True)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100, default=True)
email = models.EmailField(max_length=100)
user_type = models.CharField(max_length=100)
status = models.CharField(max_length=100, default=True)
roles = models.ManyToManyField('Role', through='EmployeeRole')
def __str__(self):
return self.webflow_id + " " + self.email + " " + self.first_name + " " + self.last_name
this is my general html staff.html:
$(document).ready(function() {
var data;
fetch("http://192.168.2.85:8000/fetchapi_employees/")
.then(response => response.json())
.then(json => data = json)
.then(() => {console.log(data); //this gave me Array of objects from my database
$('#datatable').DataTable( {
data: data.employees,
deferRender: true,
scrollY: false,
scrollX: false,
scrollCollapse: true,
scroller: true,
"columns": [
{ data: "webflow_id" },
{ data: "first_name" },
{ data: "last_name" },
{ data: "email" },
{ render: function ( data, type, row ) {
return '<i class="far fa-edit fa-lg" aria-hidden="true"></i>';
} },
{ render: function ( data, type, row ) {
return '<i class="fa fa-plus-circle" aria-hidden="true"></i>';
} },
],
"order": [[1, 'asc']]
} )
})
} );
staffedit.html:
<div class="container">
<div class="col-md-10.offset-md-1 mt-5">
<div class="jumbotron">
<h1 class="display-4">Edit employee</h1>
<hr class="my-4">
<form action="" method="post" autocomplete="off">
{% csrf_token %}
{{form.as_p}}
<button type="submit" class="btn btn-success"><i class="far fa-save"></i> Save</button>
</form>
</div>
</div>
</div>
forms.py:
class EmployeeEditForm(ModelForm):
class Meta:
model = Employee
fields = [
'webflow_id',
'first_name',
'last_name',
'roles',
]
and this is my urls.py:
path('staff/edit/<int:webflow_id>', views.staff_edit, name="staffedit"),
Can anyone see what I'm missing?
Best regards!

webflow_id is a CharField
webflow_id = models.CharField(max_length=100, default=True)
Url parameter must be contain string:
path('staff/edit/<str:webflow_id>', views.staff_edit, name="staffedit"),
Also your webflow_id is not primary key. If you want to use it as primary key, you have to add primary_key=True.
webflow_id = models.CharField(max_length=100, primary_key=True)
I would also use Try Except for get method:
from django.http import Http404
try:
Employee.objects.get(webflow_id=webflow_id)
except Employee.DoesNotExist:
raise Http404("Employee DoesNotExist")

Related

How to display your queries using filter?

So I am trying to set up a filter for my website and it is not working; It does not give me an error and the url updates like a query is being made but when I click "submit" it still shows all of the content in the page. I can't quite figure out what is wrong.
filters.py
import django_filters
from django_filters import DateFilter
from .models import *
class UserpostFilter(django_filters.FilterSet):
start_date = DateFilter(field_name = "date_published", lookup_expr='gte')
end_date = DateFilter(field_name = "date_published", lookup_expr='lte')
class Meta:
model = Userpost
fields = '__all__'
exclude = ['image', 'user', 'date_published']
models.py
class Userpost(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
Year = models.CharField(max_length = 4)
Mileage = models.CharField(max_length = 8)
Make = models.CharField(max_length = 50)
Model = models.CharField(max_length = 50)
Price = models.DecimalField(max_digits=15, decimal_places=2)
email = models.EmailField()
date_published = models.DateField(default = timezone.now)
image = models.ImageField(null = True, blank = True, upload_to = r"C:\Users\gabri\Desktop\test\ecommerce\static\images")
def __str__(self):
return self.Year + " " + self.Make + " " + self.Model
#property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
views.py
def posts(request):
cars = Userpost.objects.all()
p = Paginator(Userpost.objects.all(), 9)
page = request.GET.get('page')
cars_list = p.get_page(page)
nums = "a" * cars_list.paginator.num_pages
myFilter = UserpostFilter(request.GET, queryset = cars)
cars = myFilter.qs
context = {'cars':cars, 'cars_list':cars_list, "nums":nums, "myFilter":myFilter}
return render(request, 'store/userposts.html', context)
userposts.html
<div class = "row">
<div class="col">
<div class = "card card-body">
<form method="get">
{{myFilter.form}}
<button class="btn btn-primary" type="submit">Search</button>
</form>
</div>
</div>
</div>
<br>
<div class="row">
{% for car in cars_list %}
<div class="col-lg-4">
<img class="thumbnail" src="{{car.imageURL|default:'/images/transparentLogo.png'}}">
<div class="box-element product">
<h6><strong>{{car.Year}} {{car.Make}} {{car.Model}}</strong></h6>
<hr>
<a class="btn btn-outline-success" href="{% url 'post_detail' car.pk %}">View</a>
<h4 style="display: inline-block; float: right"><strong>${{car.Price|floatformat:2}}</strong></h4>
</div>
</div>
{% endfor %}
</div>
I would really appreciate if you guys could help me
EDIT
So I changed the order of the views to first filter and then paginate but it still does the same thing. I get no error, but display all the content from the page rather than the filtered ones.
def posts(request):
cars = Userpost.objects.all()
myFilter = UserpostFilter(request.GET, queryset=cars)
cars = myFilter.qs
p = Paginator(Userpost.objects.all(), 9)
page = request.GET.get('page')
cars_list = p.get_page(page)
nums = "a" * cars_list.paginator.num_pages
context = {'cars':cars, "myFilter":myFilter, 'cars_list':cars_list, "nums":nums}
return render(request, 'store/userposts.html', context)
The paginator should work on the cars not on the orignal queryset, since you are paginate over the filtered results
def posts(request):
cars = Userpost.objects.all()
myFilter = UserpostFilter(request.GET, queryset=cars)
if not myFilter.is_valid():
raise ValidationError('filter is invalid')
cars = myFilter.qs
# This is the change
p = Paginator(cars, 9)
page = request.GET.get('page')
cars_list = p.get_page(page)
nums = "a" * cars_list.paginator.num_pages
context = {'cars':cars, "myFilter":myFilter, 'cars_list':cars_list, "nums":nums}
return render(request, 'store/userposts.html', context)

Send date to Template of django

in my project, user after register can complete his information in another form. after completed this form and submitted it every time he visits this page, he sees the completed form. but i have a problem in this form, calender of user's birthday field works well at the first time when field is empty, but after the form is completed and submitting when the user wants to change it the calendar looks like this:
models.py:
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
ED_CHOICES = [
('hs', 'High school'),
('bc', 'Bachelor'),
('ms', 'Master'),
('do', 'Doctor'),
]
user = models.OneToOneField(User, on_delete=models.CASCADE)
phone = models.CharField(max_length=13)
birthday = models.DateField()
education = models.CharField(max_length=20, choices=ED_CHOICES)
gender = models.CharField(max_length=15)
forms.py:
class ProfileForm(forms.ModelForm):
ED_CHOICES = [
('hs', 'High school'),
('bc', 'Bachelor'),
('ms', 'Master'),
('do', 'Doctor'),
]
phone = forms.CharField(
widget=forms.TextInput(attrs={'class': 'input--style-4'}),
label=''
)
birthday = forms.DateField(
widget=forms.DateInput(attrs={'class': 'input--style-4 js-datepicker'}),
label=''
)
education = forms.CharField(
widget=forms.Select(choices=ED_CHOICES, attrs={'class': 'select-dropdown'}),
label=''
)
gender = forms.CharField(
widget=forms.TextInput(attrs={'class': 'radio-container m-r-45'}),
label=''
)
class Meta:
model = models.UserProfile
fields = ['phone', 'birthday', 'education', 'gender']
views.py:
from django.shortcuts import render, redirect
from . import forms, models
from django.contrib.auth import get_user_model
my_user = get_user_model()
my_profile = models.UserProfile
first = True
def profile(request, slug):
global first
user = my_user.objects.get(username=slug)
if first:
pro_form = forms.ProfileForm(request.POST or None)
else:
pro = my_profile.objects.get(user=user)
pro_form = forms.ProfileForm(request.POST or None, instance=pro)
form = forms.UserProfile(request.POST or None, instance=user)
context = {'FORM': form, 'PRO': pro_form, 'USER': user}
if form.is_valid() and pro_form.is_valid():
form.save()
pro = pro_form.save(commit=False)
pro.user = user
pro.save()
first = False
if 'gender' in request.POST:
pro_form.gender = request.POST.get('gender')
return redirect('HOME')
return render(request, 'accounts/index.html', context)
template:
<div class="row row-space">
<div class="col-2">
<div class="input-group">
<label class="label">Birthday</label>
<div class="input-group-icon">
{{ PRO.birthday }}
<i class="zmdi zmdi-calendar-note input-icon js-btn-calendar"></i>
</div>
</div>
</div>
js:
(function ($) {
'use strict';
/*==================================================================
[ Daterangepicker ]*/
try {
$('.js-datepicker').daterangepicker({
"singleDatePicker": true,
"showDropdowns": true,
"autoUpdateInput": false,
locale: {
format: 'DD/MM/YYYY'
},
});
var myCalendar = $('.js-datepicker');
var isClick = 0;
$(window).on('click',function(){
isClick = 0;
});
$(myCalendar).on('apply.daterangepicker',function(ev, picker){
isClick = 0;
$(this).val(picker.startDate.format('DD/MM/YYYY'));
});
$('.js-btn-calendar').on('click',function(e){
e.stopPropagation();
if(isClick === 1) isClick = 0;
else if(isClick === 0) isClick = 1;
if (isClick === 1) {
myCalendar.focus();
}
});
$(myCalendar).on('click',function(e){
e.stopPropagation();
isClick = 1;
});
$('.daterangepicker').on('click',function(e){
e.stopPropagation();
});
} catch(er) {console.log(er);}
/*[ Select 2 Config ]
===========================================================*/
try {
var selectSimple = $('.js-select-simple');
selectSimple.each(function () {
var that = $(this);
var selectBox = that.find('select');
var selectDropdown = that.find('.select-dropdown');
selectBox.select2({
dropdownParent: selectDropdown
});
});
} catch (err) {
console.log(err);
}
})(jQuery);

Django - Select option from two dropdown menu and display filtered result in a third dropdown menu

I have got two dropdown options, country and number service location. Options for both can be selected from their respective dropdown.
My objective is to display correct telephone number based on the selected country and number service location. You will also see my attempt to implement this functionality using Ajax in views below.
Model created here -
class DID_Number_Assignment_Model(models.Model): #DID Number Assignment
country = models.ForeignKey(Country_Model, on_delete=models.CASCADE)
number_service_location = models.ForeignKey(Number_Service_Location_Model, on_delete=models.CASCADE)
did_selector = models.ForeignKey(DID_Definition_Model, on_delete=models.CASCADE)
Views.py
def did_assignment_form(request, id=0, *args, **kwargs):
if request.method =="POST":
if id==0:
form = DID_Number_Assignment_Model_Form(request.POST)
if request.is_ajax():
country = request.GET.get('country')
number_service_location = request.GET.get('number_service_location')
filters = {'country': country, 'number_service_location': number_service_location}
dids_searched = DID_Definition_Model.objects.filter(**filters)
data = []
for dids in dids_searched:
data.append({
'country': dids.country,
'number_service_location': dids.number_service_location})
return HttpResponse({
'success': True,
'data': data,
}, content_type=content_type)
else:
return HttpResponse({
'success': False,
'message': 'Only AJAX method is allowed.'
}, content_type=content_type)
template html file here -
<form action="" method="post" autocomplete="off">
{%csrf_token%}
<!--{{form|crispy}} !-->
<div class="row", style = "position:relative; left:57px; top:100px">
<div class="col-md-7"> {{ form.country | as_crispy_field }} </div>
<div class="col-md-7"> {{ form.number_service_location | as_crispy_field }} </div>
<script type="text/javascript">
$(document).on('change', '.filter-dropdown', function() {
var country = $('#countryDropdown').children('option:selected').val();
var number_service_location = $('#number_service_locationDropdown').children('option:selected').val();
if (country !== "" && number_service_location !== "" ) {
var data = {
'country': country,
'number_service_location': number_service_location
}
$.ajax({
url: '/did_definition_list/',
type: 'GET',
data: data,
dataType: 'json',
success: function(response) {
if (response.success) {
// render did_number from `response.data`
} else {
// show message from `response.message`
}
},
error: function(errorResponse) {
// show error message
}
});
} else {
return;
}
});
</script>
Model form below -
class DID_Number_Assignment_Model_Form(forms.ModelForm):
class Meta:
model = DID_Number_Assignment_Model
fields = ('country','number_service_location','did_selector', 'usage_assignment', 'employee_fullname', 'employee_email', 'subscriber_department' )
def __init__(self, *args, **kwargs):
super(DID_Number_Assignment_Model_Form,self).__init__(*args, **kwargs)
defs_with_no_assignments = DID_Definition_Model.objects.filter(did_number_assignment_model__isnull=True)
available_did= defs_with_no_assignments.values_list('did_number', flat=True)
# TO SET drop down default text for a field , optional -
self.fields['did_selector'].empty_label = "Select"
self.fields['did_selector'].queryset = DID_Definition_Model.objects.filter(did_number__in=available_did)

How to open an uploaded file in another template - Django?

my django app acts as an emailing service, emails that are sent are view-able and it's possible to send html emails. How do I display the html emails on the view-mail page rather than just displaying the name of the file ? (the following is the mail-view for an html email):
How would I display the actual html in the body of this page?
This is my views.py:
def outbox(request):
#Mail_Item.objects.all().delete()
if request.method == "POST" and request.POST.get('Username', False)!=False:
username = request.POST.get('Username')
password = request.POST.get('Password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user, backend='django.contrib.auth.backends.ModelBackend')
print(username + " has logged in")
messages = Mail_Item.objects.filter(user=request.user.username)
args = {'messages':messages}
return render(request, 'outbox.html', args)
else:
return render(request, '404.html')
elif request.POST.get('Username', False) == False and request.POST.get('mail_body_field', False) == False:
pass
elif request.method == "POST" and request.POST.get('mail_subject_field')!=False:
subject = request.POST.get('mail_subject_field')
body = request.POST['mail_body_field']
file = ""
try:
file = request.FILES['filename']
except:
pass
print("sending mail:")
for i in range(1, len(Res)+1):
y = Res['ID' + str(i)].email
print("sent to " + y )
msg = EmailMessage(subject, body, 'email#example.com', [y])
msg.content_subtype = "html"
if (str(file)) != "" and (str(file))[-4:] != 'html':
msg.attach_file(str(file))
obj = Mail_Item(subject=subject, body=body, user=request.user.username, file_name=(str(file)))
obj.save()
print("email stored in database")
elif (str(file)) != "" and (str(file))[-4:] == 'html' :
uploaded_file = file
fs = FileSystemStorage()
fs.save((str(file)), uploaded_file)
html_message = render_to_string((str(file)), {'context': 'values'})
plain_message = strip_tags(html_message)
from_email = 'From <email2#example.com>'
mail.send_mail(subject, plain_message, from_email, [y], html_message=html_message)
obj = Mail_Item(subject=subject, body=body, user=request.user.username, file_name=(str(file)))
obj.save()
else:
obj = Mail_Item(subject=subject, body=body, user=request.user.username, file_name='None')
obj.save()
print("email stored in database")
#msg.send()
i += 1
messages = Mail_Item.objects.filter(user=request.user.username)
args = {'messages':messages}
return HttpResponseRedirect('../templates/outbox.html', args, request)
else:
print("pleeeeeaassee")
return render(request, '404.html')
messages = Mail_Item.objects.filter(user=request.user.username)
args = {'messages':messages}
return render(request, 'outbox.html', args)
def login_page(request):
if request.method == "POST":
username = request.POST['sign-up-name']
email = request.POST['sign-up-email']
password = request.POST['sign-up-password']
user = User.objects.create_user(username, email, password)
user.save()
print(username + " has been added to the user database.")
else:
pass
return render(request, 'login.html')
def signup_page(request):
return render(request, 'signup.html')
def mail_view(request, id=None):
if id:
email = Mail_Item.objects.get(id=id)
args = {'email':email}
else:
pass
return render(request, 'mail-view.html', args)
def log_out(request):
logout(request)
return render(request, 'log-out.html')
def delete(request):
Mail_Item.objects.filter(id=id).delete()
messages = Mail_Item.objects.filter(user=request.user.username)
args = {'messages':messages}
return render(request, 'outbox.html', args)
This is the code for my mail-view template where I'd like to place the html that is being sent:
<div class="mail-view">
<h4 class="m-0">{{ email.subject }}</h4>
<div class="divid"></div>
<div class="media">
<div class="media-left">
<div class="avatar avatar-lg avatar-circle">
<img class="img-responsive" src="{% static '../static/assets/images/221.jpg' %}" alt="avatar"/>
</div><!-- .avatar -->
</div>
<div class="media-body">
<div class="m-b-sm">
<h4 class="m-0 inline-block m-r-lg">
Access Bank
</h4>
</div>
<p><b>Attachment: </b>{{ email.file_name }}</p>
</div>
</div>
<div class="divid"></div>
<div class="row">
<div class="col-md-12">
<div class="m-h-lg lh-xl">
<p>{{ email.body }}</p>
</div>
</div>
</div>
</div>
Models.py:
from django.db import models
class Details(models.Model):
email = models.CharField(max_length=200)
def __str__(self):
return self.email
class Mail_Item(models.Model):
subject = models.CharField(max_length=200)
body = models.CharField(max_length=300)
time = models.DateTimeField(auto_now=True)
user = models.CharField(max_length=15)
file_name = models.CharField(max_length=100, null=True, default=None)
def __str__(self):
template = '{0.subject} {0.body} {0.time} {0.user} {0.file_name}'
return template.format(self)

Django custom button counter

I want to have 2 buttons at the bottom of my each post like that:
I need suggestions how could I achieve that. I tried django-vote library, but it does not work for me.
My code:
<--template.html-->
<div class="post-bottom overflow">
<ul class="nav navbar-nav post-nav">
<li><i class="fa fa-tag"></i>0 Creative</li>
<li><i class="fa fa-heart"></i>32 Love</li>
</ul>
</div>
_
###**VIEWS.PY**###
class IndexView(generic.ListView):
template_name = 'web_serv/index.html'
context_object_name = 'post_list'
paginate_by = 10
def get_queryset(self):
queryset = Post.objects.all()
if self.request.GET.get('category'):
queryset = queryset.filter(category=self.request.GET.get('category', ''))
return queryset
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['category_list'] = Category.objects.all()
return context
_
#models.py#
class Post(VoteModel, models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=40)
category = models.ForeignKey(Category)
picture = ImageWithThumbsField(sizes=((850, 400), (66, 66)))
content = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
class Meta:
ordering = ['-created_date']
def __str__(self):
return self.title + ' - ' + str(self.created_date.date())
Any suggestions are welcome :)
What you are asking is a bit of work, so here's the rough outline. You can duplicate PostLove if you want to add a PostCreative as well.
models.py
class PostLove(models.Model):
user = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='postlovesAsUser')
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='postlovesAsPost')
total_loves = models.IntegerField(default=0)
def __str__(self):
return '{0}'.format(self.post.title)
views.py
class PostLoveView(View):
def post(self, request):
data = {}
user = request.user
post_id = int(request.POST['post_id'])
post = get_object_or_404(Post, id=post_id)
loved, created = PostLove.objects.get_or_create(post=post)
user_loved = get_object_or_none(PostLove, user=user, post=post)
if user_loved:
loved.user.remove(user)
PostLove.objects.filter(post=post).update(total_loves=F('total_loves')-1)
data['success'] = 'unloved'
else:
loved.user.add(user)
PostLove.objects.filter(user=user, post=post).update(total_loves=F('total_loves')+1)
data['success'] = 'loved'
return JsonResponse(data)
urls.py
url(r'^post-love/$', views.PostLoveView.as_view(), name='post_love'),
html
<div class="post-bottom overflow">
<ul class="nav navbar-nav post-nav">
<li><i class="fa fa-tag"></i>0 Creative</li>
<li><a id="love-button" data-post-id="{{ post.id }}" href="#"><i class="fa fa-heart"></i><span id="love-count">32</span> Love</a></li>
</ul>
</div>
javascript
$("#love-button").click(function(e) {
e.preventDefault();
var $this = $(this),
postID = $this.data('post-id'),
$totalLoves = $('#love-count'),
total = parseInt($totalLoves.html()),;
$.ajax({
type: "POST",
url: "{{ url 'post_love' }}",
data: {"post_id": postID}
})
.done(function(response) {
alert("Success")
var is_loved = JSON.parse(response)['success'];
if (is_loved == "loved") {
$totalLoves.html(total + 1);
} else if (is_loved = "unloved") {
$totalLoves.html(total - 1);
}
})
.fail(function() {
alert("Failure")
})
})
You can then migrate your DB to create the new models and you should be done.