I have created an attendance system in Django but I cannot seem to retrieve all users that are currently present.
My code is displayed below:
Models:
class Meta:
model = User
fields = ("username", 'email', 'password1', 'password2')
class is_Present(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField(default=datetime.date.today)
is_present = models.BooleanField(default=False)
class clocked_Time(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField(default=datetime.date.today)
time = models.DateTimeField(null=True, blank=True)
signed_out = models.BooleanField(default=False)
views.py:
# Displays admin attendance portal functions
def attendance_portal(request):
if not request.user.is_authenticated:
messages.warning(request, f'Please sign in to mark attendance out')
return redirect('login')
elif not request.user.is_superuser or not request.user.is_staff:
messages.warning(request, f'Must be admin to access this feature')
return redirect('home')
elif request.user.is_superuser:
count_employees_all = count_employees() # shows count of employees
present_employee_all = present_employees() # shows count present employees today
present_employee_all_week = present_week_employees() # shows count present employees in last 7 days
# Gets the employees present today
today = datetime.today()
# Gets employees displayed and paginated
user = get_user_model()
user_list = user.objects.all()
p = Paginator(is_Present.objects.filter(date=today).filter(is_present=True).select_related('user').values('user__username'), 5)
page = request.GET.get('page', 1)
users = p.get_page(page)
try:
users = p.get_page(page) # returns the desired page object
except PageNotAnInteger:
# if page_number is not an integer then assign the first page
users = p.page(1)
except EmptyPage:
# if page is empty then return last page
users = p.page(p.num_pages)
# this_week_emp_count_vs_date()
# last_week_emp_count_vs_date()
return render(request, "users/adminReports.html",
{'count_employees_all': count_employees_all, 'present_employee_all': present_employee_all,
'present_employee_all_week': present_employee_all_week, 'user_list': user_list, 'users': users})
else:
messages.warning(request, f'Error - please see logs for details.')
return redirect(request, 'home')
HTML:
<div class="card" style="margin: 2em; background: lightcoral;border: solid 3px dimgrey; padding-bottom: 30px; width: 50%">
<div class="card-body">
<h4 style="text-align: center"> Employee's Present Today </h4><br />
{% for user in users %}
<table class="table align-left table-dark table-striped table-hover table-bordered">
<tbody>
<tr>
<td style="width: 25%;">{{ user.username }}</td>
</tr>
</tbody>
</table>
{% endfor %}
<div style="text-align: center;">
{%if users.has_previous %} {# whether the previous page exists #}
<button class="btn btn-outline-dark btn-sm">«</button> {# link to the prev page #}
{% endif %}
<span>{{users.number}}</span> {# the current page number #}
{%if users.has_next %} {# whether the next page exists #}
<button class="btn btn-outline-dark btn-sm">»</button> {# link to the next page #}
{% endif %}
</div>
There is currently one user present today, and it seems to grab the user as it inserts one table row, however it does not allow me to grab the username etc (please see image)
Seems that user.username was not getting referenced far enough. I was able to solve this by referencing using this:
user.user.username
user.user.username
Related
I created a system and in this system, there are several users and customers. What I want to create an assign function. A customer should assign to a user.
For example, I have a customer list. When the user clicks a button, the user will see a list that other users and select one of them. After that, the customer's name will be listed in the different assigned customers list of the selected user.
I wrote a code and this is working, but I cannot reach user from customer list. What I mean is when I click assign button it create a new customer. How can I reach user id or username?
views.py
def customer_list(request):
current_user = request.user
userP = UserProfile.objects.get_or_create(username=current_user)
customer_list = Customer.objects.filter(company=userP[0].company.comp_name)
# Assign
form = AssignForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('user:customer_list')
myFilter = TableFilter(request.GET, queryset=customer_list.all())
context = {
'customer_list': customer_list,
'myFilter': myFilter,
'form': form
}
return render(request, 'customer_list.html', context)
models.py
class Customer(models.Model):
customer_name = models.CharField(max_length=20)
country = models.CharField(max_length=20)
address = models.CharField(max_length=100)
VATnumber = models.CharField(max_length=10)
telephone = models.CharField(max_length=10)
email = models.CharField(max_length=30)
contact_person = models.CharField(max_length=30)
company = models.CharField(max_length=20)
id = models.AutoField(primary_key=True)
user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, blank=True, null=True)
class UserProfile(AbstractUser, UserMixin):
company = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True, unique=False)
user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True)
username = models.CharField(max_length=500, unique=True)
first_name = models.CharField(max_length=200)
customer_list.py
<table id="multi-filter-select" class="display table table-striped table-hover grid_" >
<thead>
<tr>
<th>Customer Name</th>
<th>Country</th>
<th>E-Mail</th>
<th>Phone</th>
<th>VAT Number</th>
<th>Operations</th>
</tr>
</thead>
<tbody>
{% for customer in customer_list %}
<tr>
<td>{{customer.customer_name}}</td>
<td>{{customer.country}}</td>
<td>{{customer.email}}</td>
<td>{{customer.telephone}}</td>
<td>{{customer.VATnumber}}</td>
<td>
<div class="row">
<button type="button" class="btn btn-info" data-toggle="collapse" data-target="#demo{{ forloop.counter }}">Assign</button>
<div id="demo{{ forloop.counter }}" class="collapse">
{% if customer.user == null %}
<form method="post">
{% csrf_token %}
{{ form|crispy }}
<button type="submit" class="btn btn-success ">Assign</button>
</form>
{% else %}
Assigned to {{ customer.user.first_name }} {{ customer.user.last_name }}
{% endif %}
</div>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
forms.py
class AssignForm(forms.ModelForm):
class Meta:
model = Customer
fields = ('user',)
views.py
def customer_list(request):
current_user = request.user
userP = UserProfile.objects.get_or_create(username=current_user)
customer_list = Customer.objects.filter(company=userP[0].company.comp_name)
# Assign
form = AssignForm(request.POST or None)
if request.POST:
customer_id = request.POST.get('customer_id', None)
customer = Customer.objects.get(id=customer_id)
user = UserProfile.objects.get(id=request.POST.get('user', None))
customer.user = user
customer.save()
form.save()
return redirect('user:customer_list')
context = {
'customer_list': customer_list,
'form': form
}
return render(request, 'customer_list.html', context)
customer_list.html
...
<button type="button" class="btn btn-success" data-toggle="collapse" data-target="#demo{{ forloop.counter }}">Assigned</button>
...
<form method="post">
{% csrf_token %}
{{ form|crispy }}
<input type="hidden" name="customer_id" value="{{ customer.id }}">
<button type="submit" class="btn btn-success ">Assign</button>
</form>
ValueError at /HomeFeed/slug-1/detail/
The QuerySet value for an exact lookup must be limited to one result using slicing.
interest_list = InterestList.objects.get(interestuser=account)
There are multiple errors in my code and this error is only one of them...
In my project, people get to post blog posts, and people that read the blog post and like it can send an "interest request" maybe to comment more about the blog post and the maker of the blog post can accept or reject that interest request. Its basically something like a friend request, except the request you are sending are your "thoughts" in a form. I am trying to tilt my code while building my relationship system to fit into this "submit interest system".
I have 4 models in total, one for the posts, one is my user account model, one is the interest list and the second one is the interestrequest.
There are 4 major functions, accept the request, decline the request (if you are the blog post maker) and send and unsend the request (if you are the interested user)
I find it difficult to link interest to blog post to account model such that the interest is sent to that particular blog post.
There are 5 things to note if you want to understand my code
is_myself = True means you are looking at your own post
is_others = True means you are looking at the accepted request's member's post (aka your interest has been accepted)
is_others = False can mean 3 things
Other people has sent a request to your post
you have sent a request to other people's post
no one has sent anything (which will be the default likely)
models.py
class InterestList(models.Model):
interestuser = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="interestuser")
interests = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="interests")
def __str__(self):
return self.interestuser.username
def add_interest(self, account):
if not account in self.interests.all():
self.interests.add(account)
self.save()
def remove_interest(self, account):
if account in self.interests.all():
self.interests.remove(account)
class InterestRequest(models.Model):
interestsender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="interestsender")
interestreceiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="interestreceiver")
is_active = models.BooleanField(blank=False, null=False, default=True)
timestamp = models.DateTimeField(auto_now_add=True)
my_name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
my_thoughts = models.TextField(max_length=5000, null=False, blank=False)
def __str__(self):
return self.interestsender.username
def accept(self):
receiver_interest_list = InterestList.objects.get(user=self.interestreceiver)
if receiver_interest_list:
receiver_interest_list.add_interest(self.interestsender)
sender_interest_list = InterestList.objects.get(user=self.interestsender)
if sender_interest_list:
sender_interest_list.add_interest(self.interestreceiver)
self.is_active = False
self.save()
def decline(self):
self.is_active = False
self.save()
def cancel(self):
self.is_active = False
self.save()
class BlogPost(models.Model):
chief_title = models.CharField(max_length=50, null=False, blank=False)
body = models.TextField(max_length=5000, null=False, blank=False)
likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='blog_posts', blank=True)
slug = models.SlugField(blank=True, unique=True)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Account(AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
views.py
def detail_blog_view(request, slug):
context = {}
#need to import a package get_object_or_404. return object or throw 404
blog_post = get_object_or_404(BlogPost, slug=slug)
total_likes = blog_post.total_likes()
liked = False
if blog_post.likes.filter(id=request.user.id).exists():
liked = True
context['liked'] = liked
context['blog_post'] = blog_post
context['total_likes'] = total_likes
account = Account.objects.all()
context['account'] = account
try:
interest_list = InterestList.objects.get(interestuser=account)
except InterestList.DoesNotExist:
interest_list = InterestList(interestuser=account)
interest_list.save()
interests = interest_list.interests.all()
context['interests'] = interests
is_myself = True
is_others = False
request_sent = InterestRequestStatus.NO_REQUEST_SENT.value
interest_requests = None
user = request.user
if user.is_authenticated and blog_post.author != user:
is_myself = False
if interests.filter(pk=user.id):
is_others = True
else:
is_others = False
#CASE 1: THEY HAVE SENT A REQUEST TO YOU
if get_interest_request_or_false(sender=account, receiver=user) != False:
request_sent = InterestRequestStatus.THEM_SENT_TO_YOU.value
context['pending_interest_request_id'] = get_interest_request_or_false(sender=account, receiver=user).id #or you can use pk instead of id
#CASE 2: REQUEST SENT FROM YOU TO THEM
if get_interest_request_or_false(sender=account, receiver=user) != False:
request_sent = InterestRequestStatus.YOU_SENT_TO_THEM.value
#CASE 3: NTH HAS BEEN SENT
else:
request_sent = InterestRequestStatus.NO_REQUEST_SENT.value
elif not user.is_authenticated:
is_myself = False
#when you are looking at your own post
else:
try:
interest_requests = InterestRequest.objects.filter(receiver=user, is_active=True)
except:
pass
context['is_myself'] = is_myself
context['is_others'] = is_others
context['request_sent'] = request_sent
context['interest_requests'] = interest_requests
context['BASE_URL'] = settings.BASE_URL
return render(request, 'HomeFeed/detail_blog.html', context)
utils.py
from HomeFeed.models import InterestRequest
def get_interest_request_or_false(interestsender, interestreceiver):
try:
return InterestRequest.objects.get(interestsender=interestsender, interestreceiver=interestreceiver, is_active=True)
except InterestRequest.DoesNotExist:
return False
interest_request.py
from enum import Enum
class InterestRequestStatus(Enum):
NO_REQUEST_SENT = -1 #no request sent in that blog post to you or to them. this is the constant, how it should normally look like for most posts
THEM_SENT_TO_YOU = 0
YOU_SENT_TO_THEM = 1
template html
{% if request.user.is_authenticated %}
<div class="d-flex flex-column mb-4" >
<!-- THEM to YOU -->
{% if request_sent == 0 %}
<div class="card m-2 p-4" >
<div class="d-flex flex-row align-items-center">
<span class="friend-text align-items-center mr-2">Accept Member Request</span>
<span id="id_cancel_{{id}}" class="decline-friend-request material-icons p-1" onclick='triggerDeclineFriendRequest("{{pending_friend_request_id}}")'>cancel</span>
<span id="id_confirm_{{id}}" class="confirm-friend-request material-icons p-1" onclick='triggerAcceptFriendRequest("{{pending_friend_request_id}}")'>check</span>
</div>
</div>
{% endif %}
<div class="card m-2 px-4 pb-4">
<!-- Cancel Friend Request / Send Friend Request / Remove Friend -->
{% if is_others == False and is_myself == False %}
<!-- You sent them a request -->
{% if request_sent == 1 %}
<div class="d-flex flex-column align-items-center pt-4">
<button class="btn btn-danger" id="id_cancel_friend_request_btn">
Cancel Interest Request
</button>
</div>
{% endif %}
<!-- No requests have been sent -->
{% if request_sent == -1 %}
<div class="d-flex flex-column align-items-center pt-4">
<button class="btn btn-primary" id="id_send_friend_request_btn">
Send Interest Request
</button>
</div>
{% endif %}
{% endif %}
{% if is_others %}
<div class="dropdown pt-4 m-auto">
<button class="btn btn-secondary dropdown-toggle friends-btn" type="button" id="id_friends_toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Accepted Members
</button>
<div class="dropdown-content" aria-labelledby="id_friends_toggle">
<a class="dropdown-item" href="#" onclick="removeFriend('{{id}}', onFriendRemoved)">Remove Member</a>
</div>
</div>
{% endif %}
{% endif %}
urls.py
path('<slug>/detail/', detail_blog_view, name= "detail"),
THE PROBLEM
This error you described in the beginning is appearing because you are tryng to query a model using a queryset. In your views.py in your detail_blog_view you have a line that says:
account = Account.objects.all()
Here the value of the account variable is a queryset of ALL the available accounts, then you are trying to query your database using this queryset with a get method here:
interest_list = InterestList.objects.get(interestuser=account)
Since your interestuser field is a one2one relationship it can only accept a **single **object in the query while you are passing a queryset.
THE SOLUTION
All you have to do is instead of using account = Account.objects.all() write a query that would make the account variable store a single object value, for example:
account = request.user # if you are logged in and trying to get your own account
Pass a variable pk (of the user you want to get the list for) to the url path like this:
urlpatterns = [
path('detail_blog_view/<int:pk>/', views.detail_blog_view, name="detail_blog_view"),
]
then where you create links to your detail_blog_view pages write it something like this:
{{ user.username }} # here i'm passing a known user.pk from the context of the view that stores this template.
and in the end in your view query your account with the pk passed in the url like this:
account = Account.objects.get(pk=pk)
I have seen many solutions for this on here but I can't seem to get any working as I am also new to django. Essentially as of now my files are uploading correctly by a user to media/documents but when I try to download the files from the directory, in terminal I get 404 and I end up downloading an empty file. Say the original file is "test.txt", right now it is downloading an empty "documents_test.txt". As of right now this is what I have for my code and how I am trying to download within my template.
models.py
class Program(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
description = models.CharField(max_length=128)
upload = models.FileField(upload_to='documents/')
category = models.ForeignKey(ProgramCategory, on_delete=models.CASCADE)
is_public = models.BooleanField()
views.py
def programs(request):
# Create some default categories if there aren't any.
if (not ProgramCategory.objects.all()):
ProgramCategory.objects.create(category="Hobby")
ProgramCategory.objects.create(category="School")
ProgramCategory.objects.create(category="Work")
'''if (request.method == "GET" and "toggle_completed" in request.GET):
id = request.GET["toggle_completed"]
task = Task.objects.get(id=id)
task.is_completed = not task.is_completed
task.save()'''
if (request.method == "GET" and "delete" in request.GET):
id = request.GET["delete"]
Program.objects.all().filter(id=id).delete()
return redirect("/programs/")
if (request.method == "POST"):
try:
user_profile = UserProfile.objects.filter(user=request.user).get()
except:
user_profile = UserProfile()
user_profile.user = request.user
#user_profile.tasks_view_hide_completed = False
#form = HideCompletedTasksForm(request.POST, instance=user_profile)
if (form.is_valid()):
form.save()
user_profile = UserProfile.objects.filter(user=request.user).get()
#hide_completed_form_data = HideCompletedTasksForm(instance=user_profile)
#except:
#hide_completed_form_data = HideCompletedTasksForm()
#hide_completed = hide_completed_form_data["tasks_view_hide_completed"].value()
#if (hide_completed):
#table_data = Task.objects.select_related().filter(user=request.user, is_completed=False)
else:
table_data = Program.objects.all().filter(user=request.user)
#filename = Program.objects.all().filter(user=request.user).values_list('upload')
context = {
#"hide_completed_form_data": hide_completed_form_data,
"table_data": table_data,
}
template(programs.html)
{% for row in table_data %}
<tr>
<td>{{ row.upload }}</td>
<td>{{ row.description }}</td>
<td>{{ row.category }}</td>
.
.
.
<td>
<a class="btn btn-primary" href="/programs/edit/{{ row.id }}/">Edit</a>
<a class="btn btn-primary" href="#" onclick="confirmDeleteModal({{ row.id }})">Delete</a>
<a class='btn btn-primary' href="{{ row.upload.url}}" download="{{ row.upload.url}}"> Download</a>
</tr>
{% endfor %}
{% endif %}
Any help would be greatly appreciated.
I'm creating a website for general education uses and one of the features is a calendar section where I would like the user to be able to store their events but then when they login they can view the events they created. This is for an academic assignment.
I can't seem to get this calendar to link to a user field. I would like each record in the calendar table to have a user_id which will be the same as the current_user. I understand that you can user the django default user auth but i have not done that due to not knowing about it and by the time I realized it was too late.
So all I really need to do is when the form is valid, I need to assign the value of the current_user id as the value for student in the calendar table. But for some reason I keep getting problems and the form isn't detected as being valid or the program just doesn't assign the value.
My main objective is to have each user view their own calendar. I don't mind changing the current student field to a foreign key field
Student.Views
def calendar(request):
student_obj = Student.objects.get(student_name=current_user)
print(student_obj)
if request.method == 'POST':
form = EventsForm(initial={'student': '3'} or request.POST)
print(form.errors)
if form.is_valid():
form.save()
all_events = Events.objects.filter(student=student_obj.id)
messages.success(request, 'Event Has Been Added')
return render(request, 'Student/calendar.html', {'all_events': all_events})
else:
messages.success(request, 'Event Has NOT Been Added')
all_events = Events.objects.filter(student=student_obj.id)
return render(request, 'Student/calendar.html', {'all_events': all_events})
Student.Models
class Student(models.Model):
student_name = models.CharField(max_length=59, default=None)
username = models.CharField(max_length=59)
password = models.CharField(max_length=59)
age = models.PositiveIntegerField()
date_of_birth = models.DateField(max_length=10)
form = models.CharField(max_length=3)
email = models.EmailField(max_length=59)
present = models.PositiveIntegerField(default=0)
late = models.PositiveIntegerField(default=0)
absent = models.PositiveIntegerField(default=0)
maths_grade = models.PositiveIntegerField(default=0)
english_grade = models.PositiveIntegerField(default=0)
science_grade = models.PositiveIntegerField(default=0)
behaviour_level = models.PositiveIntegerField(default=0)
def __str__(self):
return self.student_name
class Events(models.Model):
student = models.CharField(max_length=200)
date = models.DateField(max_length=10, default=None)
event = models.CharField(max_length=200)
completed = models.BooleanField(default=False)
Student.forms
class EventsForm(forms.ModelForm):
class Meta:
model = Events
fields = ["event", "completed", "date", "student"]
Calendar Template
<div class="container" style="color: #fff">
<br/>
{% if messages %}
{% for message in messages %}
<div class="alert alert-warning alert-dismissible" roles="alert">
<button class="close" data-dismiss="alert">
<small>x</small>
</button>
{{ message }}
</div>
{% endfor %}
{% endif %}
{% if all_events %}
<div>
<table class="table table-dark table-bordered">
{% for things in all_events %}
{% if things.completed %}
<style>
.striker {
text-decoration: line-through;
text-color: black;
}
</style>
<tr class="table-danger striker">
<td style="color: black">{{ things.date }}</td>
<td>{{ things.event }}</td>
<td><center>Delete</center></td>
</tr>
{% else %}
<tr>
<td>{{ things.date }}</td>
<td >{{ things.event }}</td>
<td><center>Delete</center></td>
</tr>
{% endif %}
{% endfor %}
</table>
</div>
{% endif %}
Change form.save() to
event = form.save(commit=False)
event.student = request.user
event.save()
That'll do it.
Don't make it complicated, this have to be easier. If I understood what are you trying to do I would create my models as following:
#model.py
from django.db.models.signals import post_save
from django.dispatch import receiver
class Student(models.Model):
user= models.OneToOneField(User, null=True) #student is user
#Define student fields...
class Calendar(models.Model):
#Defile calender fields here along with its default values ...
user = models.OneToOneField(Student)
'''
this signal populate calender table with user_id along with its
calender fields
'''
#receiver(post_save, sender=Student)
def create_student_calender(sender, instance, created, **kwargs):
if created and not kwargs.get('raw', False):
calendar = Calender(user=instance)
calendar.save()
class Event(models.Model):
calender = models.ForeignKey(Callender, null=True)
# Define event fields here ...
With models structure like this, whenever student create account Calendar model will be populated saved with calendar fields and student's id field.
So how do student create their events? Simply create an a inlineformset_factory form to create events on each student's calendar like this:
#form.py
from django.forms import inlineformset_factory
from django import forms
class EventForm(forms.ModelForm):
#Events form fields here...
class Meta:
model = Event
fields = ["Event's field"]
EventFormSet = inlineformset_factory(Calender, Event, form=EventForm,
max_num=1, can_delete=False)
Render this formset with a view for student to create their events,the formset automatically associate student's event to calendar.
So you can add your logic to do more.
I am trying to make a form for user creation through django. The user(henceforth developer) can choose from a list of supervisors to get himself registered. Problem is, I am not getting the list of all the supervisors from the query. When I use objects.get(), I receive an error that 2 objects were received. That means that the queries are getting the rows from the database.
models.py
from django.db import models
class UserProfile(models.Model):
name = models.CharField(max_length=50,verbose_name="Name")
login = models.CharField(max_length=(25),verbose_name="Login")
password = models.CharField(max_length=100, verbose_name="Password")
phone = models.CharField(max_length=20, verbose_name="Phone number", null=True, default=None, blank=True)
born_date = models.DateField(verbose_name="Born date" , null=True,default=None, blank=True)
last_connection = models.DateTimeField(verbose_name="Date of last connection" , null=True, default=None, blank=True)
email = models.EmailField(verbose_name="Email")
years_seniority = models.IntegerField(verbose_name="Seniority", default=0)
date_created = models.DateField(verbose_name="Date of Birthday", auto_now_add=True)
def __str__(self):
return self.name
class Supervisor(UserProfile):
specialisation = models.CharField(max_length=50, verbose_name="Specialisation")
class Developer(UserProfile):
supervisor = models.ForeignKey(Supervisor, verbose_name="Supervisor")
The form view create_developer.py -
from django.shortcuts import render
from django.http import HttpResponse
from TasksManager.models import Supervisor, Developer
# View for create_developer
def page(request):
error = False
# If form has posted
if request.POST:
if 'name' in request.POST:
name = request.POST.get('name', '')
else:
error=True
if 'login' in request.POST:
login = request.POST.get('login', '')
else:
error=True
if 'password' in request.POST:
password = request.POST.get('password', '')
else:
error=True
if 'supervisor' in request.POST:
supervisor_id = request.POST.get('supervisor', '')
else:
error=True
if not error:
supervisor = Supervisor.objects.get(id = supervisor_id)
new_dev = Developer(name=name, login=login, password=password,supervisor=supervisor)
new_dev.save()
return HttpResponse("Developer added")
else:
return HttpResponse("An error as occured")
else:
supervisors_list = Supervisor.objects.all()
return render(request, 'en/public/create_developer.html')
template create_developer.html
{% extends "base.html" %}
{% block title_html %}
Create Developer
{% endblock %}
{% block h1 %}
Create Developer
{% endblock %}
{% block article_content %}
<form method="post" action="{% url 'create_developer' %}" >
<table>
<tr>
<td>Name</td>
<td>
<input type="text" name="name" />
</td>
</tr>
<tr>
<td>Login</td>
<td>
<input type="text" name="login" />
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="text" name="password" />
</td>
</tr>
<tr>
<td>Supervisor</td>
<td>
<select name="supervisor">
{% for supervisor in supervisors_list %}
<option value="{{ supervisor.id }}">{{ supervisor.name}}</option>
{% endfor %}
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Valid" />
</td>
</tr>
</table>
</form>
{% endblock %}
The supervisor select list should show the list. But I am getting an empty list there. The output of {{ supervisors_list|length }} is zero.
How to debug this?
You have to pass context to the html:
from django.shortcuts import render
from django.http import HttpResponse
from TasksManager.models import Supervisor, Developer
# View for create_developer
def page(request):
error = False
# If form has posted
if request.POST:
if 'name' in request.POST:
name = request.POST.get('name', '')
else:
error=True
if 'login' in request.POST:
login = request.POST.get('login', '')
else:
error=True
if 'password' in request.POST:
password = request.POST.get('password', '')
else:
error=True
if 'supervisor' in request.POST:
supervisor_id = request.POST.get('supervisor', '')
else:
error=True
if not error:
supervisor = Supervisor.objects.get(id = supervisor_id)
new_dev = Developer(name=name, login=login, password=password,supervisor=supervisor)
new_dev.save()
return HttpResponse("Developer added")
else:
return HttpResponse("An error as occured")
else:
supervisors_list = Supervisor.objects.all()
return render(request, 'en/public/create_developer.html', {'supervisors_list' : supervisors_list})