Call another model field in url django - python

My problem is have two models job and company and i want to get all jobs in this company
My urls.py:
url(r'^jobs/(?P<slug>[\w-]+)/$', views.job_at_company, name='job_at_company'),
My views.py:
def job_at_company(request, slug):
return render(request, 'jobs.html')
My models.py:
class Company(models.Model):
title = models.CharField(max_length=100, blank=False)
slug = models.SlugField(blank=True, default='')
city = models.CharField(max_length=100, blank=False)
contact_info = models.CharField(max_length=100, blank=False, default=0)
facebook = models.CharField(max_length=100, blank=True)
twitter = models.CharField(max_length=100, blank=True)
linkedin = models.CharField(max_length=100, blank=True)
logo = models.ImageField(upload_to="logo", default=0)
class Jobs(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(blank=True, default='')
company = models.ForeignKey(Company, on_delete=models.CASCADE)
price = models.IntegerField(default='')
Description = models.TextField(blank=True, null=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
job_type = models.CharField(max_length=100, choices=(('Full Time', 'Full Time'),('Part Time', 'Part Time')),default='Full Time')

in the views.py we can add this
def job_at_company(request, slug):
results = Jobs.objects.filter(company__slug=slug)
context = {'items':results}
return render(request, 'jobs.html',context)

Suppose you pass id in the url. The id is the primary key of the company. You would have to modify your url to accept id like -
url(r'^jobs/(?P<slug>[\w-]+)/(?P<pk>[\d]+)$', views.job_at_company, name='job_at_company')
And modify your views.py -
def job_at_company(request, slug, pk):
jobs_qs = Jobs.objects.filter(company__id=pk)
return render(request, 'jobs.html', {'jobs': jobs_qs})
And use it in your html like -
{% for job in jobs %}
{{job.title}}
{% endfor %}
Look at this link. Django's documentation is helpful, follow that

Related

How to get username field automatically in Django

I am working on a Django project which is something similar to Fiverr in its working. I have used abstractuser where there is a buyer and seller. The seller creates a gig then the buyer will go through the gig before placing an order. My issue is how to get the seller and place him in the order that the buyer will create from reading the gig. Currently I am using the system whereby the buyer will have to manually choose a gig from a list, which I think is not effective.
Here is my Models.py
`class User(AbstractUser):
is_buyer=models.BooleanField(default=False)
is_seller=models.BooleanField(default=False)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(default='avatar.jpg', null=True, blank=True)
about = models.CharField(max_length=100)
def __str__(self):
return self.user.username
class Gig(models.Model):
seller = models.ForeignKey(Profile, on_delete = models.CASCADE, null=False, blank=False)
category = models.ForeignKey('Category', on_delete = models.CASCADE, null=False, blank=False)
title = models.CharField(max_length=500, null=True, blank=True)
description = models.CharField(max_length=500, null=True, blank=True)
gig_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class Order(models.Model):
buyer = models.ForeignKey(Profile, on_delete=models.CASCADE, null=False, blank=False)
seller = models.ForeignKey(Gig, on_delete=models.CASCADE, related_name='+', null=False, blank=False)
title = models.CharField(max_length=500, null=True, blank=True)
description = models.CharField(max_length=500)
amount = models.IntegerField(max_length=50, blank=False)
is_ordered = models.BooleanField(default=False)
order_id = models.UUIDField(default=uuid.uuid4, unique=True, db_index=True, editable=False)
slug = models.SlugField(null=True)
def __str__(self):
return self.title`
And views.py where I am getting the submissions;
def createOrder(request):
profile = request.user.profile
form = CreateOrderForm()
if request.method == 'POST':
form = CreateOrderForm(request.POST, request.FILES)
if form.is_valid:
order = form.save(commit=False)
order.buyer = profile
order.save()
# form.save()
messages.info(request, 'Order Succesfully Created')
return redirect('create_order')
else:
messages.error(request, 'Order Not Created! Try Again Later')
context = {'form':form}
return render(request, 'users/create_order.html', context)
Any help will he highly appreciated.

TypeError: __str__ returned non-string (type NoneType). Not sure how to solve this

[![Nurse admin page[![][1]][1][models.py
from django.db import models
#Work Related aka Department and Work Shift
class Department(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return self.name
class WorkShift(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
start_datetime = models.DateTimeField(null=True, blank=True)
end_datetime = models.DateTimeField(null=True, blank=True)
def __str__(self):
return self.name
#Personel Related aka Employees and Patients
class Doctor(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True)
department = models.ForeignKey(Department, default="", null=True, blank=True, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Nurse(models.Model):
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True)
department = models.ForeignKey(Department, default="", null=True, blank=True, on_delete=models.CASCADE)
reports_to = models.OneToOneField(Doctor, default="", blank=True, null=True, on_delete=models.CASCADE)
work_shift = models.OneToOneField(WorkShift, default="", blank=True, null=True, on_delete=models.CASCADE)
def __str__(self):
return str(name)
class Patient(models.Model):
STATUS = (
('Sick', 'Sick'),
('Healing', 'Healing'),
('Cured', 'Cured'),
('Deceased', 'Deceased'),
)
name = models.CharField(max_length=200, null=True, blank=True)
description = models.TextField(blank=True, null=True)
status = models.CharField(max_length=200, null=True, blank=True, choices=STATUS)
department = models.ForeignKey(Department, default="", null=True, blank=True, on_delete=models.CASCADE)
care = models.ForeignKey(Nurse, default="", blank=True, null=True, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True)
def __str__(self):
return self.name
views.py
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render
from .models import Doctor, Nurse, Patient
from django.http import HttpResponse
# Create your views here.
def index(request):
patient = Patient.objects.all()
nurse = Nurse.objects.all()
doctor = Doctor.objects.all()
total_patient = patient.count()
sick = patient.filter(status='Sick').count()
healing = patient.filter(status='Healing').count()
cured = patient.filter(status='Cured').count()
total_nurse = nurse.count()
# if request.method == 'POST':
# form =
context = {
'patient':patient, 'nurse':nurse,
'doctor':doctor, 'total_patient':total_patient,
'sick':sick, 'healing':healing, 'cured':cured,
'total_nurse':total_nurse
}
return render(request, 'lifesaver/index.html', context)
def patient(request):
patient = Patient.objects.all()
total_patient = patient.count()
context = {
'patient':patient,
'total_patient':total_patient
}
return render(request, 'lifesaver/patient.html', context)][1]
forms.py
from django import forms
from .models import Doctor, Nurse, Patient
from django.auth.contrib.forms import UserCreationForm
class DoctorForm(forms.ModelForm):
name = forms.CharField(widget = forms.TextInput(attrs =
{
'placeholder': 'Add a New Doctor',
'class': 'form-control'
}
))
department = forms.ModelChoiceField(queryset=department.objects.all)
class NurseForm(forms.ModelForm):
name = forms.CharField(widget = forms.TextInput(attrs =
{
'placeholder': 'Add a New Nurse',
'class': 'form-control'
}
))
class PatientForm(forms.ModelForm):
name = forms.CharField(widget = forms.TextInput(attrs =
{
'placeholder': 'Add a New Patient'
'class': 'form-control'
}))
HTML for patient
{% extends 'lifesaver/main.html' %}
{% block content %}
<h1>SUPERSTAR</h1>
{% for patient in patient %}
{{patient.name}}
{% endfor %}
{% endblock content %}
I get this error when I go to try to add another Nurse. The URL is http://127.0.0.1:8000/admin/lifesaver/nurse/add/. Everything else behaves as expected, except the adding the Nurse part.
If I try to remove the def __str___ part, the error still displays. I believe the error lies in the:
work_shift = models.OneToOneField(WorkShift, default="",
blank=True,
null=True,
on_delete=models.CASCADE)
part since when I included that code, the error spawned. Furthermore, the code is to add a work shift to certain employees and the goal is that the employees shift will display in their profile.
How do I fix this issue?
EDIT: When accessing the HTML template, the web page behaves as expected and has no issues.
In your Nurse model replace this:
def __str__(self):
return str(Nurse.name)
with this:
def __str__(self):
return self.name

Unable to Cancel Orders in Django

I would like to add the option for customers on my site to cancel their orders, but I'm having trouble getting it to work. I've created the view and the URL, but something is evidently wrong with them. Here's how it looks on the site:
delete_order View:
def delete_order(request, pk):
""" Cancel an order from the profile page """
order = Order.objects.get(id=pk)
if request.method == "POST":
order.delete()
return redirect('/')
return render(request, "delete_order.html", {'item': order})
Order Model:
class Order(models.Model):
STATUS = (
('Pending', 'Pending'),
('Out for delivery', 'Out for delivery'),
('Delivered', 'Delivered'),
)
customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL)
product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL)
full_name = models.CharField(max_length=50, blank=False)
phone_number = models.CharField(max_length=20, blank=False)
country = models.CharField(max_length=40, blank=False)
postcode = models.CharField(max_length=20, blank=True)
town_or_city = models.CharField(max_length=40, blank=False)
street_address1 = models.CharField(max_length=40, blank=False)
street_address2 = models.CharField(max_length=40, blank=False)
county = models.CharField(max_length=40, blank=False)
date = models.DateField()
date_created = models.DateTimeField(auto_now_add=True, null=True)
status = models.CharField(max_length=200, null=True, choices=STATUS)
def __str__(self):
return "{0}-{1}-{2}".format(self.id, self.date, self.full_name)
Django Url:
url(r'^delete_order/(?P<pk>\d+)/$', delete_order, name="delete_order")
Html Url:
<a class="btn btn-sm btn-danger" href="{% url 'delete_order' order.id %}">Cancel</a>
This is the error I am getting:
Any feedback is greatly appreciated!
Maybe you just forgot to add end slash in the main urls.py file?
When you connect app urls to main urls.py file you need to check that url link looks like:
path('checkout/', include('checkout.urls')),
def order_remove(request,pk):
order = Order.objects.filter(pk=pk).first()
order.delete()
return redirect('#your path#',pk)
user first to get that particular order
path('delete/<int:pk>', views.delete_order, name="delete_order")

Django Multiple classes in Model.py

I am new to Django and Python. I am trying to create a database of babysitters and one of the objects which can have multiple fields is Education. My first Babysitter has 2 qualifications which produces an error an will not display.
Error Message
views.py
from django.shortcuts import render, get_object_or_404, get_list_or_404
from .models import Babysitter, Education, Work, Reference
# Create your views here.
def all_babysitters(request):
babysitters = Babysitter.objects.all()
return render(request, "babysitters.html", {"babysitters": babysitters})
def babysitter_profile(request, id):
"""A view that displays the profile page of a registered babysitter"""
babysitter = get_object_or_404(Babysitter, id=id)
reference = get_object_or_404(Reference)
education = get_object_or_404(Education)
return render(request, "babysitter_profile.html", {'babysitter': babysitter, 'education': education, 'reference': reference} )
models.py
from django.db import models
from datetime import datetime
# Create your models here.
class Babysitter(models.Model):
list_display = ('firstName', 'lastName', 'minderType')
firstName = models.CharField(max_length=50, blank=True, null=True)
lastName = models.CharField(max_length=50, blank=True, null=True)
minderType = models.CharField(max_length=50, blank=True, null=True)
image = models.ImageField(upload_to='images')
phone = models.CharField(max_length=20, blank=True, null=True)
email = models.CharField(max_length=50, blank=True, null=True)
address1 = models.CharField(max_length=100, null=True)
address2 = models.CharField(max_length=100, null=True)
city = models.CharField(max_length=20, null=True)
county = models.CharField(max_length=100, null=True)
eircode = models.CharField(max_length=7, null=True)
biography = models.TextField(max_length=280,blank=True)
def __str__(self):
return self.firstName + ' ' + self.lastName
class Education(models.Model):
babysitter = models.ForeignKey(Babysitter)
school = models.CharField(max_length=50)
qualification = models.CharField(max_length=50)
fieldOfStudy = models.CharField(max_length=50)
dateFrom = models.DateField(auto_now=False, auto_now_add=False)
dateTo = models.DateField(
auto_now=False, auto_now_add=False, null=True, blank=True)
current = models.BooleanField(default=False)
graduated = models.BooleanField(default=False)
def __str__(self):
return self.school
class Work(models.Model):
babysitter = models.ForeignKey(Babysitter)
family = models.CharField(max_length=50)
role = models.CharField(max_length=50)
location = models.CharField(max_length=50)
dateFrom = models.DateField(auto_now=False, auto_now_add=False)
dateTo = models.DateField(
auto_now=False, auto_now_add=False, null=True, blank=True)
current = models.BooleanField(default=False)
def __str__(self):
return self.work
class Reference(models.Model):
babysitter = models.ForeignKey(Babysitter)
refFamily = models.CharField(max_length=50)
contact = models.CharField(max_length=50)
location = models.CharField(max_length=50)
email = models.CharField(max_length=50, blank=True, null=True)
reference = models.CharField(max_length=300)
date = models.DateField(auto_now=False, auto_now_add=False)
def __str__(self):
return self.refFamily
Can somebody help? I am going to pull my hair out. Thanks
You aren't passing enough information into the calls to get a Reference and Education object:
babysitter = get_object_or_404(Babysitter, id=id)
reference = get_object_or_404(Reference, babysitter_id=babysitter.id)
education = get_object_or_404(Education, babysitter_id=babysitter.id)
The get_object_or_404() function is a shortcut that calls get() underneath, and get() only ever returns a single object (returning more than one will result in the Exception you are seeing).
If you want to see more than one object, then don't use the get_object_or_404 shortcut method (I find those "shortcut" methods to be ugly, personally). Instead, change it to something like:
education_qs = Education.objects.filter(babysitter_id=babysitter.id)
Then loop over that queryset to get the results:
for ed in education_qs:
# Get some data
school = ed.school
You can loop over the queryset in your HTML template, if that's easier.
Update: Here's a better answer that shows how to use querysets:
def babysitter_profile(request, id):
"""A view that displays the profile page of a registered babysitter"""
babysitter = get_object_or_404(Babysitter, id=id)
reference_qs = Reference.objects.filter(babysitter_id=babysitter.id)
education_qs = Education.objects.filter(babysitter_id=babysitter.id)
return render(request, "babysitter_profile.html", {
'babysitter': babysitter,
'education_qs': education_qs,
'reference_qs': reference_qs}
)
Then, in your HTML template, you could do something like the following to show the schools the Babysitter has attended (in a bulleted list):
<ul>
{% for ed in education_qs %}
<li>{{ ed.school }}</li>
{% endfor %}
</ul>
You could do something similar for the Reference data.
I think you should set some parameters to get a specific object, rather than get a bunch of objects.
Just do it like the first instance for get_object_or_404.
reference = get_object_or_404(Reference,id=xx)
education = get_object_or_404(Education,id=yy)
get_object_or_404 returns just 1 object. Use get_list_or_404 if babysitter has "2 qualification" to prevent exception.
babysitter = get_object_or_404(Babysitter, id=id)
education = get_list_or_404(Education, id=babysitter.id)
To prevent MultipleObjectReturned exception.

Display only creator's files - Django/Python

I would like to display only the pictures uploaded by the creator (user) on their individual profiles.
How would I alter my code to display that?
Thank you!
models.py:
class Photo(models.Model):
creator = models.ForeignKey(MyUser, null=False, blank=False)
category = models.ForeignKey("Category", default=1, null=True, blank=True)
title = models.CharField(max_length=30, null=True, blank=True)
description = models.TextField(max_length=120, null=True, blank=True)
image = models.ImageField(upload_to='user/photos/', null=True, blank=True)
slug = models.SlugField(null=False, blank=False)
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False, null=True)
updated = models.DateTimeField(auto_now_add=False, auto_now=True, null=True)
class Meta:
unique_together = ('slug', 'category')
ordering = ['-timestamp']
def __unicode__(self):
return "%s" %(self.creator)
def get_image_url(self):
return "%s/%s" %(settings.MEDIA_URL, self.image)
def get_absolute_url(self):
return "%s/%s" %(self.creator, self.slug)
views.py:
#login_required
def account_home(request, username):
try:
u = MyUser.objects.get(username=username)
except:
u = None
photo_set = Photo.objects.all()
context = {
"photo_set": photo_set,
"notifications": notifications,
"transactions": transactions
}
return render(request, "accounts/account_home.html", context)
.html:
{% for photo in photo_set %}
<img src="{{ photo.get_image_url }}" class='img-responsive'>
<hr/>
{% endfor %}
You have a ForeignKey to user, so you can just filter the photos by that:
photo_set = Photo.objects.filter(creator=u)
or even better use the reverse relationship:
photo_set = u.photo_set.all()
Also, never ever ever ever use a blank except statement in your code. The only exception you are expecting the get to raise is MyUser.DoesNotExist, so you should catch that only.

Categories

Resources