Html select POST Django - python

Hello i'm new to django.
I have a model that looks like this.
Models.py
class CustomUser(AbstractUser):
pass
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
def __str__(self):
return self.username
class Campus(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Intervention(models.Model):
subject = models.CharField(max_length=200)
begin_date = models.DateField(default=datetime.datetime.today)
end_date = models.DateField(default=datetime.datetime.today)
description = models.TextField(blank=True)
speaker = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
campus = models.ForeignKey(Campus, on_delete=models.CASCADE)
class Meta:
verbose_name = 'Intervention'
verbose_name_plural = 'Interventions'
def __str__(self):
return self.subject
class Evaluation(models.Model):
interventions = models.ForeignKey(Intervention, on_delete=models.CASCADE)
student_id = models.CharField(max_length=20)
speaker_knowledge_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)])
speaker_teaching_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)])
speaker_answer_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)])
slide_content_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)])
slide_examples_mark = models.IntegerField(validators=[MaxValueValidator(20), MinValueValidator(0)])
comment = models.TextField(blank=True)
class Meta:
verbose_name = 'Evaluation'
verbose_name_plural = 'Evaluations'
So, basically what i'm trying to do is on home page i want to have a select box where student have to choose his campus then he will be redirected to a new page where he can see only the interventions that belongs to the campus he choosed
My home page looks like this:
<form method="post" action="/Mark/"/>
<select name="campus_id">
<option value="" disabled selected>Choose your Campus</option>
{% for camp in campus %}
<option value="camp.pk">{{ camp.name }}</option>
{% endfor %}
</select>
<input type="submit" />
</form>
I tried several things but none worked :/ if anybody can help or give me a hint.
Thanks.
Best regards.

I would suggest you to have a clear idea and define the flow:
You have a view that displays the form to select the campus (alternatively you might have a list of links)
Create a view (ListView) that displays a table (list) of Interventions
Create a Django form with choices from your Campus model
The view (FormView) that will process this form would get the selected value and redirect to another view using the provided value (id).
List items provided by the Intervention display view (ListView) filtered (get_queryset) by the respective campus id

Related

Unable to make Dynamic Django dependent dropdown

I am new to Django and I am struggling to make a dynamic Django dependent select dropdown for 'Categories', and I have been making a CRUD with Products having categories ,sub categories ,colors ,size
below is the code for my Products model:
from tkinter import CASCADE
from django.db import models
from rest_framework import serializers
# Create your models here.
CATEGORY_CHOICES = [('ninesixwear','9-6WEAR'),('desiswag','DESI SWAG'),('fusionwear','FUSION WEAR'),
('bridalwear','BRIDAL WEAR')]
class Products(models.Model):
Categories = serializers.ChoiceField(choices = CATEGORY_CHOICES)
sub_categories = models.CharField(max_length=15)
Colors = models.CharField(max_length=15)
Size = models.CharField(max_length=15)
image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True)
title = models.CharField(max_length=50)
price = models.CharField(max_length=10)
sku_number = models.CharField(max_length=10)
prod_details = models.CharField(max_length=300)
quantity = models.IntegerField(default=0)
isactive = models.BooleanField(default=True)
model file create Category field
class Category (models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(max_length=255, unique=True)
def __str__(self):
return self.name
class Meta:
verbose_name_plural= 'Categories'
viwe file query all category from database
def category(request):
categories = Category.objects.all()
html file code
<div class="col-md-12">
<label>Category</label>
<select name="category" class="form-control">
<option value="">select category</option>
{% for category in categories %}
<option value="{{category.id}}">{{category.name}}</option>
{% endfor %}
</select>
</div>
If you still don't understand then check this repo Github

How to print data in template django of a diffrent table joined by foreign key?

Hello Everyone i have Two model first one is as following:
class Item(models.Model):
title = models.CharField(max_length=100)
price = models.FloatField()
bargainprice = models.FloatField(default=0)
discount_price = models.FloatField(blank=True, null=True)
category = models.CharField(choices=CATEGORY_CHOICES, max_length=2)
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
slug = models.SlugField()
description = models.TextField()
image = models.ImageField()
and i am getting this model data using the following view:
class ItemDetailView(DetailView):
model = Item
template_name = "product.html"
and in product.html i am accessing Item objects like this:
<span class="mr-1">
<del>₹ {{ object.price }}</del>
</span>
<span>₹ {{ object.discount_price }}</span>
{% else %}
<span> ₹ <span id="pp">{{ object.price }}</span></span>
and so on..
everything working fine up here. but problem arises when i created the following model:
class BargainModel(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
itemId = models.IntegerField()
bprice = models.FloatField()
i joined this with foreign key as mentioned.
**what i want to do is print the " bprice " in the product.html of the same user but i am not able to do it **
can anyone help me with this i am new to Django.
Thanks in advance
in this case you need to import User like
from django.contrib.auth.models import User
class BargainModel(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
itemId = models.ForeignKey(Item, on_delete=models.CASCADE)
bprice = models.FloatField()
in product.html you can call the model of BargainModel it also contains the Item with user
It is better to work with a ForeignKey since this will guarantee referential integrity. You thus shoudl define the BargainModel as:
from django.conf import settings
class Bargain(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
item = models.ForeignKey(
Item,
on_delete=models.CASCADE
)
bprice = models.FloatField()
class Meta:
constraints = [
models.UniqueConstraint(fields=['item', 'user'], name='unique_user_item')
]
In the DetailView, we can then look if there is a Bargain record for the given item and user with:
class ItemDetailView(DetailView):
model = Item
template_name = "product.html"
def get_bargain(self):
if self.request.user.is_authenticated():
return Bargain.objects.filter(item=self.object, user=request.user).first()
Then you can render this with:
{{ view.get_bargain.bprice }}
if there is a related Bargain, then it will show the corresponding bprice.
Note: Models normally have no Model suffix. Therefore it might be better to rename BargainModel to Bargain.

get latest object from databse regardless of user in django

I am learning python and django and I am coding a project similar to IMDB.
I am using python 3.8.2 64 bit and django 3
I want to display the latest review a movie received regardless of the user that wrote it.
Now it shows the user's own latest review and after logging the user out the review remains without displaying the user that wrote it. I have tried to clear cache and history, didn't help. this is the model:
from django.db import models
from django.contrib.auth.models import User
class Movie(models.Model):
movie_title = models.CharField(max_length=250)
movie_poster = models.ImageField(default='default.png', blank=True)
movie_short_description = models.TextField()
director = models.CharField(max_length=250)
actor1 = models.CharField(max_length=250)
actor2 = models.CharField(max_length=250)
actor3 = models.CharField(max_length=250)
actor4 = models.CharField(max_length=250)
year = models.IntegerField()
def __str__(self):
return self.movie_title + ' - ' + str(self.year)
class Review(models.Model):
movie = models.ForeignKey(Movie, on_delete=models.CASCADE)
user = models.ForeignKey(User, default = None, on_delete=models.DO_NOTHING)
score = models.IntegerField()
review_title = models.CharField(max_length=250, default="")
movie_review = models.TextField()
date = models.DateTimeField(auto_now_add=True)
class Meta:
get_latest_by = 'date'
def __str__(self):
return self.review_title
views.py
def movie_detail(request, pk):
try:
movie = Movie.objects.get(pk=pk)
review = Review.objects.all().latest()
except Exception as e:
print(e)
return render (request, 'movies/movie_detail.html', {'movie': movie, 'review': review})
html code:
</table>
</p>
<p>User Reviews</p>
<h3>Score: {{review.score}} {{review.review_title}}</h3>
<h6>{{review.date}}, by {{ user.get_username }}</h6>
<p>{{review.movie_review}}</p>
Review this title
</div>
</div>
{% endblock %}
I would create a property on Movie that gives you all reviews and then get the latest Review from this queryset. Here' the code:
# models.py
class Movie(models.Model):
# your other code
#property
def reviews(self) -> QuerySet:
return self.review_set.all()
# views.py
def movie_detail(request, pk):
movie = get_object_or_404(Movie, pk=pk)
latest_review = movie.reviews.latest()
# return
Ps: I would rename movie_title, movie_poster and movie_short_description to just title, poster and short_description. It is obvious that the title on Movie is the movies' title. I would also strongly suggest to change the 4 actors to a single model with a ManyToMany-relation (but I think you will read on that in the documentation later).

Using render field for select option in django

I am using widget_tweaks in my django project. For an input tag, I am using it like :
{% render_field form.enrollment_no class='form-control' id='id_enrollment_number' placeholder='Enrollment Number' type='text' %}
Now, I want to achieve something similar for <select> tag:
<select class='form-control' id='id_faculty'>
{% for faculties in faculty %}
<option value="{{ faculties }}">{{ faculties }}</option>
{% endfor %}
</select>
But, I think I am doing something wrong, because it would not help while checking the validity on form submit. Please help me to solve this.
Edit 1:
Also, I am getting faculty from a different model:
form = StudentForm()
faculty = Faculty.objects.all()
return render(request, 'index.html',{'form' : form,'faculty' : faculty}).
Studen Model :
class Student(models.Model):
"""here goes model for users"""
def __str__(self):
return self.name
name = models.CharField(max_length=200)
enrollment_no = models.CharField(max_length=10)
Faculty Name:
class Faculty(models.Model):
faculty_name = models.TextField()
def __str__(self):
return self.faculty_name
Student Form class:
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = '__all__'
Other tables:
class Faculty(models.Model):
faculty_name = models.TextField()
def __str__(self):
return self.faculty_name
class Department(models.Model):
faculty = models.ForeignKey(Faculty,on_delete=models.CASCADE)
department_name = models.TextField()
def __str__(self):
return self.department_name
class Course(models.Model):
student = models.ForeignKey(Student,on_delete=models.CASCADE)
department = models.ForeignKey(Department,on_delete=models.CASCADE)
course_name = models.TextField()
def __str__(self):
return self.course_name

Django To Filter distinct content with counts

In Django I need to filter the data and display the result like. for example
Alabama(20)
Iowa(12)
Here "Alabama,Iowa" are State Names and inside the brackets "20,12" are no. of jobs available by the particular States.
models.py
class User(models.Model):
first_name= forms.CharField(max_length=30,widget=forms.TextInput())
last_name = forms.CharField(max_length=30,widget=forms.TextInput())
username = forms.CharField(max_length=30,widget=forms.TextInput())
email = forms.EmailField(widget=forms.TextInput())
password = forms.CharField(widget=forms.PasswordInput())
companyname = forms.CharField(max_length=30,widget=forms.TextInput())
class jobs(models.Model):
emp = models.ForeignKey(User, unique=False)
title = models.CharField(max_length=30)
referencecode = models.CharField(max_length=30)
jobsummary = models.TextField()
jobdetails = models.TextField()
key_skills = models.CharField(max_length=30)
states = models.CharField(max_length=30)
I tried to give views.py is like
def search_result(request):
details = jobs.objects.annotate().order_by('state')
return render_to_response('searchresult.html', {'details': details})
templates
<ul>
{% for d1 in details %}
<li>{{ d1.state }}({{ d1.count }})</li>
{% endfor %}
</ul>
It displays only State name not a count. Give some clarification.
You can do this:
from django.db.models import Count
jobs.objects.values('states').annotate(count=Count('states'))
It seems to be tricky, but u can do this by refer "https://docs.djangoproject.com/en/dev/ref/models/querysets/"

Categories