Trying to build a simple search page in django.
I have a model:
class Person(models.Model):
ROLE_CHOICES = (
('Eng', 'Engineering'),
('Product', 'Product'),
('QA', 'QA'),
('Mrkt', 'Marketing'),
('Fin/Off', 'Finance / Office'), \
('Care', 'Care'),
('Sales', 'Sales'),
)
ROLE_TYPE = (
('Full', 'Full Time'),
('CooP', 'Co-Op'),
('Part', 'Part Time'),
('Intern', 'Intern'),
)
first_name = models.CharField(blank=True, max_length=100)
last_name = models.CharField(blank=True, max_length=100)
date_added = models.DateField(auto_now_add=True)
date_start = models.DateField(auto_now=False)
date_leaving = models.DateField(auto_now=False)
role = models.CharField(max_length=100, default = "", choices = ROLE_CHOICES)
manager = models.ForeignKey('self', limit_choices_to = {'is_manager': True}, null=True, blank=True)
title = models.CharField(blank=True, max_length=100)
role_type = models.CharField(max_length=100, default = "", choices = ROLE_TYPE)
laptop_needed = models.BooleanField(default=True)
phone_needed = models.BooleanField(default=True)
desk_loco = models.CharField(blank=True, max_length=100)
mail_lists = models.ManyToManyField(Mailists, blank=True, null=True)
notes = models.CharField(blank=True, max_length=500)
is_manager = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_leaving = models.BooleanField(default=False)
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
I have this view:
def search_people(request):
if request.method == 'POST':
search_text = request.POST['search']
else:
search_text = ''
persons=Person.objects.filter(last_name__contains=search_text)
return render(request, 'hireterm/search.html', {'persons': persons})
Which grabs from this form:
<form class="searchfield" method="get" action="/search/" autocomplete="off">
Search: <input type="text" name="search">
<input id="searchbuttonmain" type="submit" class="subbtn" value="Search">
</form>
And renders this page:
{% if persons.count %}
{% for p in persons %}
<p>{{ p.last_name }}<p>
{% endfor %}
{% else %}
<p> OH NOES <p>
{% endif %}
It always return all of the Perosns records, not the ones filtered by last name and I am not sure why. I am sure I have missed something trivial, but I can't see it. Thanks for your input.
your form method is GET, but it should be POST. This causes it to hit the else-part of the if-statement. Thus Person objects containing the empty string in their last_name field are selected, but this matches all of the objects.
Related
First of all, I apologize for using a translator because I am not familiar with English.
My Views.py
def my_create_view(request):
if "reg" in request.method == 'POST':
first_form = FirstRegForm(request.POST, prefix='firstform')
second_form = SecondRegForm(request.POST, prefix='secondform')
if all([first_form.is_valid(), second_form.is_valid()]):
form = first_form.save(commit=False)
form.created_name = request.user.user_name
form.save()
formm = second_form.save(commit=False)
formm.shop_seq = form
formm.save()
return redirect('someview')
else:
first_form = FirstRegForm(prefix='store')
second_form = SecondRegForm(prefix='input')
return render(request, 'app/template.html', {'first_form': first_form, 'second_form': second_form})
My Models.py
from django.db.models import Max
class My_user(AbstractBaseUser):
shop_seq = models.ForeignKey('My_shop', null=True, blank=True, on_delete=models.SET_NULL, db_column="shop_seq")
user_name = models.CharField(max_length=50)
class My_shop(models.Model):
shop_seq = models.CharField(primary_key=True, editable=False, max_length=5)
shop_name = models.CharField(max_length=20, null=True)
shop_code = models.CharField(max_length=15, null=True, unique=True)
shop_address = models.CharField(max_length=40, null=True)
shop_tel = models.CharField(max_length=20, null=True)
created_name = models.CharField(max_length=100, null=True)
def save(self, **kwargs):
if not self.shop_seq:
max = Rate.objects.aggregate(shop_seq_max=Max('shop_seq'))['shop_seq_max'] + 1
self.shop_seq = "{:05d}".format(max if max is not None else 1)
super().save(*kwargs)
class My_model(models.Model):
model_id = models.BigAutoField(primary_key=True)
my_field = models.CharField(max_length=20, null=True)
some_field = models.CharField(max_length=20, null=True)
shop_seq = models.ForeignKey('My_shop', on_delete=models.SET_NULL, null=True, db_column="shop_seq", related_name="shop_model")
My Forms.py
class FirstRegForm(forms.ModelForm):
class Meta:
model = My_shop
fields = ('shop_name', 'shop_code', 'shop_address', 'shop_tel',)
class SecondRegForm(forms.ModelForm):
class Meta:
model = My_model
fields = ('my_field', 'some_field',)
My Template.py
<form method="post">{% csrf_token %}
{{ first_form.shop_name }}
{{ first_form.shop_code }}
{{ first_form.shop_address }}
{{ first_form.shop_tel }}
{{ second_form.my_field }}
{{ second_form.some_field }}
<input class="btn btn-dark" name="reg" type="submit" value="reg">
</form>
If you submit it in this state, it will not be saved in the db.(no error message)
What's wrong with my code?
This line will always be evaluated to false:
if "reg" in request.method == 'POST'
You should change it to:
if request.method == 'POST':
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()
I need some help with Django please.
I am working on a questionnaire. I made a raw query where I made a summation with two cells of the same row. I can't find the method to print it to my HTML.
views.py
def query(request):
my_query = Stressz_teszt.objects.raw('SELECT ID, stressz_v05 + stressz_v06 FROM stressz_stressz_teszt')
context = {
'my_query': my_query,
}
return render(request, 'stressz/query.html', context)
query.html
{{ my_query }}
{% for i in my_query %}
{{ i.stressz_company }} --- {{ user }} --- {{ summation here !!! }}
{% endfor %}
models.py
class Stressz_teszt(models.Model):
def __str__(self):
return self.stressz_name
user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
stressz_name = models.CharField(max_length=100, verbose_name="Lorem ipsum")
stressz_company = models.CharField(max_length=100, verbose_name="Lorem ipsum")
stressz_v01 = models.IntegerField(verbose_name="Lorem ipsum", null=True, blank=True)
stressz_v02 = models.IntegerField(verbose_name="Lorem ipsum.", null=True, blank=True)
stressz_v03 = models.IntegerField(verbose_name="Lorem ipsum", null=True, blank=True)
stressz_v04 = models.IntegerField(verbose_name="Lorem ipsum", null=True, blank=True)
stressz_v05 = models.IntegerField(verbose_name="Lorem ipsum", null=True, blank=True)
stressz_v06 = models.IntegerField(verbose_name="Lorem ipsum", null=True, blank=True)
...
{{ my_query }} just prints out my queryset:
<RawQuerySet: SELECT ID, stressz_v05 + stressz_v06 FROM stressz_stressz_teszt>
Thank you for your reply in advance!
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")
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 %}