django ListView query_set code abbreviation - python

The codes are as
models.py
class Firm(models.Model):
name = models.CharField(unique=True, max_length=50, verbose_name="Firma Adı")
slug = models.SlugField(unique=True, editable=False, max_length=50)
class Worksite(models.Model):
firm = models.ForeignKey('Firm', verbose_name='Firma', related_name="worksites", on_delete=models.CASCADE)
name = models.CharField(unique=True, max_length=50, verbose_name="Şantiye Adı")
slug = models.SlugField(unique=True, editable=False, max_length=50)
class Subcontractor(models.Model):
worksite = models.ForeignKey('Worksite', on_delete=models.CASCADE)
firm = models.ForeignKey('Firm', related_name="subcontractors", on_delete=models.CASCADE)
Can the queryset code be written shorter?
views.py
class SubcontractorListView(ListView):
template_name = 'firm/subcontractor_list.html'
context_object_name = "firms"
def get_queryset(self):
ws = self.request.user.firm.worksites.values_list('id', flat=True)
ss = Subcontractor.objects.values_list('firm_id', flat=True).filter(worksite_id__in=ws)
return Firm.objects.filter(id__in=ss)
Do you have different and short solutions?
template
{% for firm in firms %}
<div class="btn btn-outline-secondary text-left button">{{ firm }} </div>
{% endfor %}

Related

How can I show a many-to-many field values in a form?

i wrote a code about music and used Many-To-Many-Field() as genre but when i try to show genres it just shows : Genre['a number']
template:
{% extends 'pages/base.html' %}
{% block content %}
<form>
{% if mdata.image %}
<img src="mdata.image.url" height="500" width="500">
{% endif %}
{% for field in form %}
<p>{{ field.label }} : {{ field.value}}</p>
}
{% endfor %}
</form>
edit
{% endblock %}
models is here:(i didnt know which one u need so pasted both of them)
from django.db import models
from django.contrib.auth.models import User
class Genre(models.Model):
name = models.CharField(unique=True,max_length=20)
def __str__(self):
return self.name.title()
class Mdata(models.Model):
name = models.CharField(max_length=100)
artist = models.CharField(max_length=150)
album = models.CharField(max_length=100)
nation = models.CharField(max_length=100)
duration = models.DecimalField(max_digits=4,decimal_places=2)
released_in = models.DecimalField(max_digits=4,decimal_places=0)
uploaded_at = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to='images/',blank=True,null=True)
audio = models.FileField(upload_to='audios/',null=True,blank=True)
genre = models.ManyToManyField(Genre)
uploader = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.name.title()+" by "+self.artist.title()
forms.py:(its just a simple form im using)
[![class MdataForm(ModelForm):
class Meta:
model = Mdata
fields =\[
'name',
'artist',
'album',
'genre',
'nation',
'duration',
'released_in',
'image',
'audio',
]
and here the render :dunno if this is enough
[1]: https://i.stack.imgur.com/T5eK2.png
This could be that you don't have a __str__ method on your Genre model. Add a __str__ method and return the genre name. That would be something like:
def __str__(self):
return self.name
self.name here being the field on your genre model used to specify the name. In the sample image below, I set the custom user to return the username by default, that way anywhere I call a user it will automatically show the name of the genre.
class CustomUser(AbstractUser):
id = models.UUIDField(primary_key=True, editable=False, default=uuid4)
email = models.EmailField(_("email address"), unique=True, null=True)
phone_number = PhoneNumberField(unique=True, null=True)
username = models.CharField(max_length=100, unique=True, null=True)
password = models.CharField(_("password"), max_length=128, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = "User"
verbose_name_plural = "Users"
def __str__(self):
return self.username

How to categorize content in Django ? Where is the problem with my work?

I wanted to categorize my site content. Show the category titles in the menu and the contents of each category in the body. I have used these codes.
#urls
path('category/<slug:slug>', views.category, name="category")
#views
def category(request, slug):
context = {
"categorys": get_object_or_404(Category, slug=slug, status=True)
}
return render(request, "blog/category.html", context)
#models
class PostManager(models.Manager):
def published(self):
return self.filter(status='p')
class Category(models.Model):
title = models.CharField(max_length=100, verbose_name="عنوان دسته بندی")
slug = models.SlugField(max_length=200, unique=True, verbose_name="آدرس")
status = models.BooleanField(
default=True, verbose_name="آیا نمایش داده شود؟")
position = models.IntegerField(verbose_name="پوزیشن")
class Meta:
verbose_name = "دسته بندی"
verbose_name_plural = "دسته بندی ها"
ordering = ['position']
def __str__(self):
return self.title
class Post(models.Model):
STATUS_CHOICES = [
('d', 'پیش نویس'),
('p', 'منتشر شده'),
]
title = models.CharField(max_length=100, verbose_name="عنوان")
slug = models.SlugField(max_length=200, unique=True, verbose_name="آدرس")
category = models.ManyToManyField(
Category, verbose_name="دسته بندی", related_name="postcat")
description = models.TextField(verbose_name="توضیحات")
thumbnail = models.ImageField(
upload_to="imgpost", height_field=None, width_field=None, max_length=None, verbose_name="تصویر")
publish = models.DateTimeField(
default=timezone.now, verbose_name="زمان انتشار")
created = models.DateTimeField(
auto_now_add=True, verbose_name="زمان ایجاد")
updated = models.DateTimeField(
auto_now=True, verbose_name="زمان بروزرسانی")
status = models.CharField(
max_length=1, choices=STATUS_CHOICES, verbose_name="وضعیت")
def __str__(self):
return self.title
class Meta:
verbose_name = "پست"
verbose_name_plural = "پست ها"
objects = PostManager()
#template
{% for posts in categorys.postcat.published %}
<p>
posts.title
</p>
<p>
posts.description
</p>
{%endfor%}
The problem is that despite the filter I have set for not displaying draft posts, that post is not displayed in the category section. If you can help. my project in my github
{% for posts in categorys.postcat.published %}
<p>
{{ posts.title }}
</p>
<p>
{{ posts.description }}
</p>
{%endfor%}
try this!
We have to put this line of code in the model, the post class. It was a back fever.
objects = PostManager()

How to render data from multiple models django

I want to render data to my webpage from my django app however only two of the required slots are being rendered
my models are:
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
date_ordered = models.DateTimeField(auto_now_add=True)
complete = models.BooleanField(default=False)
transaction_id = models.CharField(max_length=100, null=True)
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True)
quantity = models.IntegerField(default=0, null=True, blank=True)
date_added = models.DateTimeField(auto_now_add=True)
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
class Product(models.Model):
name = models.CharField(max_length=200)
price = models.DecimalField(max_digits=7, decimal_places=2)
digital = models.BooleanField(default=False,null=True, blank=True)
image = models.ImageField(null=True , blank=True)
description = models.TextField(max_length=5000, null=True)
points = models.DecimalField(max_digits=5,decimal_places=0, null=True)
and my views are
def admin_dashboard (request):
order_list = Order.objects.all()
context = {'order':order_list}
template = "admin_dashboard.html"
return render(request, 'store/admin_dashboard.html', context)
my HTML is:
{% extends 'store/admin_main.html' %}
{% load static %}
{% block content %}
{% for order in order %}
<h6>{{ order.transaction_id }}</h6>
<p>{{ order.customer }}</p>
<p>{{ order.shippingaddress }}</p>
<p>{{ order.orderitem }}</p>
{% endfor%}
{% endblock content %}
1598061443.212917
userNew
which is just the transaction id and user.
how can I have all the rest of fields filled

Need to build a Django queryset based on more models

So what I say might seem complicated, but I think the answer is easy. I just can't figure it out. I have a form for a Lecture model, which a logged in teacher can use to post a lecture for his specific courses only. Thing is that in my database I have a TeacherData model which contains a teacher_ID field used for verification, so a teacher cannot create his account on the other Teacher model, if teacher_ID entered doesn't match. But when a course is created in database, the teacher used is the one from TeacherData. So to create my query I have to filter the courses based on TeacherData and then using teacher_ID, to link to Teacher model. I just don't know how to build this queryset but I replicated the wanted behaviour in the template:
{% if user.is_authenticated and user.is_teacher %}
<ul>
{% for data in teacher_data %}
{% if data.teacher_ID == user.teacher.teacher_ID %}
{% for course in courses %}
{% if course.teacher1 == data or course.teacher2 == data %}
<li>
{{ course.name }}
</li>
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
</ul>
{% endif %}
class Teacher(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
name = models.CharField(max_length=30, null=True, blank=True, default=None)
surname = models.CharField(max_length=50, null=True, blank=True, default=None)
email = models.EmailField(unique=True, null=True, blank=True, default=None)
teacher_ID = models.CharField(unique=True, max_length=14,
validators=[RegexValidator(regex='^.{14}$',
message='The ID needs to be 14 characters long.')],
null=True, blank=True, default=None)
class TeacherData(models.Model):
name = models.CharField(max_length=30)
surname = models.CharField(max_length=50)
teacher_ID = models.CharField(unique=True, max_length=14)
notes = models.CharField(max_length=255, default=None, blank=True)
class Lecture(models.Model):
LECTURE_CHOICES = (
('Courses', 'Courses'),
('Seminars', 'Seminars'),
)
course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures', )
lecture_category = models.CharField(max_length=10, choices=LECTURE_CHOICES, default='Courses', )
lecture_title = models.CharField(max_length=100, blank=True, null=True)
content = models.TextField(blank=False, default=None)
class Course(models.Model):
study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE, default='')
name = models.CharField(max_length=50, unique=True)
ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)])
description = models.TextField()
year = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)])
semester = models.IntegerField(choices=((1, "1"),
(2, "2"),
), default=None)
teacher1 = models.ForeignKey('TeacherData', on_delete=models.CASCADE, default=None,
verbose_name="Course Teacher", related_name='%(class)s_course_teacher')
teacher2 = models.ForeignKey('TeacherData', on_delete=models.CASCADE, default=None, null=True,
verbose_name="Seminar Teacher", related_name='%(class)s_seminar_teacher')
class LectureForm(forms.ModelForm):
lecture_title = forms.CharField(max_length=100, required=True)
course = forms.ModelChoiceField(initial=Course.objects.first(), queryset=Course.objects.filter(
Q(teacher1__id__in=[t.id for t in TeacherData.objects.filter(
teacher_ID__iexact=[t.teacher_ID for t in Teacher.objects.all()])])))
class Meta:
model = Lecture
fields = ('course', 'lecture_category', 'lecture_title', 'content')
try this,
from django.contrib.auth.decorators import permission_required
from .models import Teacher
#permission_required( # permission class to check 'is_authenticated' and 'is_teacher')
def my_view(request):
queryset = Teacher.objects.filter(teacher_ID=request.user.teacher_ID)
if queryset:
# do something with teacher data ('queryset' holds those data)
else:
return HttpResponse("teacher id not found")

How can I filter in django so I can sort each object into its correct parent?

I am building a location specific app. What I would like to do is display a list of schools by city and state. The pages are organized by state. In turn, the state pages display schools that are sorted by city.
State
--- City
------ School
--- City
------ School
I can get the state page to display the list of cities just fine. But rather than sorting out cities from different states, I get a list of all the cities without them being sorted into their correct states. I also can't get the list of schools to filter into the correct city. The cities and schools appear in every state - even the incorrect ones.
models.py
class SchoolList(models.Model):
school_list_image = models.ForeignKey(Photo, default='')
school_list_state = models.ForeignKey('place.state', default='')
school_list_city = models.ForeignKey('place.city', default='')
school_list_zip_code = models.ForeignKey('place.zip', default='')
school_list_address = models.ForeignKey('place.address', default='')
school_list_contact = models.ForeignKey(Contact)
school_list_university = models.ForeignKey('place.university', default='')
school_list_professionalschool = models.ForeignKey('place.professionalschool', default='')
school_list_summary = models.ForeignKey(Summary, default='')
def __str__(self):
return self.school_list_university.university_name
class State(models.Model):
state_name = models.CharField(max_length=20, default='')
state_abbreviation = models.CharField(max_length=2, default='')
class Meta:
ordering = ['-state_name']
def __str__(self):
return self.state_name
class City(models.Model):
city_name = models.CharField(max_length=55, default='')
class Meta:
ordering = ['-city_name']
verbose_name_plural = 'Cities'
def __str__(self):
return self.city_name
class Zip(models.Model):
zipcode = models.CharField(max_length=15, default='')
class Meta:
ordering = ['-zipcode']
def __str__(self):
return self.zipcode
class University(models.Model):
university_name = models.CharField(max_length=55, default='')
university_summary = models.CharField(max_length=255, default='')
university_image = models.ForeignKey(Photo, default='')
class Meta:
verbose_name_plural = 'Universities'
ordering = ['-university_name']
def __str__(self):
return self.university_name
class ProfessionalSchool(models.Model):
school_name = models.CharField(max_length=100, default='')
class Meta:
verbose_name_plural = 'Professional Schools'
ordering = ['-school_name']
def __str__(self):
return self.school_name
class Address(models.Model):
address = models.CharField(max_length=100, default='')
address2 = models.CharField(max_length=100, default='', blank=True)
address3 = models.CharField(max_length=100, default='', blank=True)
class Meta:
verbose_name_plural = 'Addresses'
def __str__(self):
return self.address
views.py
class StateDetail(ListView):
model = StateSchoolListArticle
template = 'state_detail.html'
context_object_name = 'article_state_list'
def get_context_data(self, **kwargs):
context = super(StateDetail, self).get_context_data(**kwargs)
context['school_list'] = SchoolList.objects.all().order_by('school_list_city')
return context
urls.py
url(r'^(?P<slug>[-\w]+)/$', StateDetail.as_view(), name='state_detail'),
template.html
{% for school in school_list %}
<h2>{{ school.school_list_city.city_name }}</h2>
<div class="school_image">
{% cloudinary school.school_list_image.image format="jpg" crop="fill" %}
</div>
<div class="demo_wrapper">
<div class="row">
<div class="medium-4 columns">
<div class="school_data_wrapper">
<h3>{{ school.school_list_university.university_name }}</h3>
<h4 style="margin-bottom: 10px;">
{{ school.school_list_professionalschool.school_name }} </h4>
<h4>{{ school.school_list_address.address }}</h4>
<h4>{{ school.school_list_city.city_name }}, {{ school.school_list_state.state_name }} {{ school.school_list_zipcode.zipcode }}</h4>
<h4>{{ school.school_list_contact.telephone }}
</h4>
<h4><a href="" rel="external nofollow">
{{ school.school_list_contact.website }}</a>
</h4>
</div>
</div>
<div class="medium-8 columns">
<h3>Summary</h3>
<p style="padding: 20px 0;">{{ school.school_list_summary.summary }}...more</p>
</div>
</div>
</div>
It's not really an answer, but it was too long to put it in the comment.
I dont like the SchoolList model at all. It is violating Normal Forms, and it will bite you sooner or later. The models should represent the real world. So when you have a zip code, it doesnt exist just like that. It is related to a city. And when you have city, it is related to a state. So the models should look like this:
class State(models.Model):
state_name = models.CharField(max_length=20, default='')
state_abbreviation = models.CharField(max_length=2, default='')
class City(models.Model):
city_name = models.CharField(max_length=55, default='')
state = models.ForeignKey(State)
class Zip(models.Model):
zipcode = models.CharField(max_length=15, default='')
city = models.ForeignKey(City)
class Address(models.Model):
zip = models.ForeignKey(Zip)
...
Now, when you have address, you want to have a ForeignKey(Zip) there. This way you will have transitively defined Zip, City and State in there, so you can (or more like should) remove them from the SchoolList model.
Then when you want to filter the schools by state, you can do it this way:
SchoolList.objects.filter(address__zip__city__state=state_object)

Categories

Resources