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})
Related
I have previously figured out how to send and save notifications by many to many fields to send to users, now i can't specifically call the notifications by current user logged in i.d.
Models.py
class Notifications(models.Model):
id=models.AutoField(primary_key=True)
sent_to = models.ManyToManyField(CustomUser)
message = models.TextField(null=True)
message_reply = models.TextField(null=True)
created_at=models.DateTimeField(auto_now_add=True)
updated_at=models.DateTimeField(auto_now=True)
The notifications_sent_to is the created table after I created the many to many save
Notifications_sent_to table (which is not created in the models)
Notifications table (which stores the message)
Views.py
def add_notification(request):
notifs = Notifications.objects.all()
users = CustomUser.objects.filter(is_staff=True)
if request.method == 'POST':
form = AddNotifForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.message_reply = "none"
instance.save()
form.save_m2m()
sent_to = form.cleaned_data.get('sent_to')
messages.success(request, f'Message has been successfully sent .')
return redirect('add_notif')
else:
form = AddNotifForm()
context={
'notifs' : notifs,
'form' : form,
'users' : users,
}
template_name ='main-admin/add-notif.html'
return render(request, template_name, context)
Forms.py
class AddNotifForm(forms.ModelForm):
sent_to = forms.ModelMultipleChoiceField(
queryset=CustomUser.objects.filter(is_staff=True).exclude(is_superuser=True),
widget=forms.CheckboxSelectMultiple,
required=True)
class Meta:
model = Notifications
fields = ['sent_to', 'message']
Templates view
{% for sent_to_users in sent_to_users %}
<tr>
<td>{{ sent_to_users.id }}</td>
<td>{{ sent_to_users.sent_to }}</td>
<td>{{ sent_to_users.message }}</td>
<td>
{% if sent_to_users.message_reply == "none" %}
<button type="button" class="btn btn-primary reply_open_modal" data-bs-toggle="modal" data-bs-target="#replyModal">Reply</button>
{% else %}
{{ sent_to_users.message_reply }}
{% endif %}
</td>
<td>{{ sent_to_users.created_at }}</td>
</tr>
{% endfor %}
My form:
class TestCaseUpdateForm(forms.ModelForm):
class Meta:
model = TestCase
fields = ( 'name', 'executable', 'parameter_list', 'executable_type', 'test_type' , 'project_name', 'created_by')
My views:
class EditCaseView(UpdateView):
model = TestCase
form_class = TestCaseUpdateForm
template_name_suffix = '_update_form'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
pk = self.kwargs.get(self.pk_url_kwarg)
queryset = self.get_queryset().filter(pk=pk)
case = queryset.get()
context['my_case'] = case
context['my_exetype'] = TestCase.EXECUTABLE_TYPE_CHOICES
context['my_ttype'] = TestCase.TEST_TYPE_CHOICES
context['projnames'] = PROJNAME_CHOICES
return context
def get_success_url(self):
print("get_success_url")
return reverse("integratedTest:testCase")
My model:
PROJNAME_CHOICES = (
('Name1', 'Name1'),
('Name2','Name2'),
('Name3','Name3')
)
class TestCase(models.Model):
EXECUTABLE_TYPE_CHOICES = (
('e_type1', 'e_type1'),
('e_type2', 'e_type2'),
('e_type3', 'e_type3'),
)
TEST_TYPE_CHOICES = (
('t_type1', 't_type1'),
('t_type2','t_type2'),
('others', 'others'),
)
name = models.CharField(max_length=200, unique=True)
executable = models.CharField(max_length=1023)
parameter_list = models.TextField(blank=True, default = "")
project_name = models.CharField(max_length=200, choices = PROJNAME_CHOICES, default="Name1")
executable_type = models.CharField(max_length=200, choices = EXECUTABLE_TYPE_CHOICES, default = "e_type1")
test_type = models.CharField(max_length=200, choices = TEST_TYPE_CHOICES, default = "t_type1")
created_by = models.CharField(max_length=200, default = "sb")
create_datetime = models.DateTimeField("testcase created on", auto_now = True)
My template:
<form method="post">{% csrf_token %}
<h1 >Edit Test Case:</h1>
<table>
<tr>
<th>Name:</th>
<th>executable:</th>
<th>parameter_list:</th>
</tr>
<tr>
<td><input type="text" id="id_name" name="name" value = "{{my_case.name}}"
placeholder="short_unique_string" required>
</td>
<td>
<input type="text" id="id_executable" name="executable" value = "{{my_case.executable}}"
placeholder="FilenameWithoutPath.py" required>
</td>
<td><textarea id="id_parameter_list" name="parameter_list" value = "{{my_case.parameter_list}}"
placeholder="Copy your parameter string here directly"></textarea>
</td>
</tr>
<tr>
<th>executable_type:</th>
<th>test_type:</th>
<th>project_name:</th>
<th>created_by:</th>
</tr>
<tr>
<td>
<select name="executable_type" id="id_executable_type" required>
{%for key, value in my_exetype %}
{%if my_case.executable_type == key %}
<option value={{value}} selected>{{key}}</option>
{%else%}
<option value={{value}}>{{key}}</option>
{%endif%}
{%endfor%}
</select>
</td>
<td>
<select name="test_type" id="id_test_type" required>
{%for key, value in my_ttype %}
{%if my_case.test_type == key %}
<option value={{value}} selected>{{key}}</option>
{%else%}
<option value={{value}}>{{key}}</option>
{%endif%}
{%endfor%}
</select>
</td>
<td>
<select name="project_name" id="id_project_name" >
{%for key, value in projnames %}
{%if my_case.project_name == key %}
<option value={{value}} selected>{{key}}</option>
{%else%}
<option value={{value}}>{{key}}</option>
{%endif%}
{%endfor%}
</select>
</td>
<td><input type="text" id="id_created_by" name="created_by" value = "{{my_case.created_by}}"
placeholder="some name like 'sb'" required></td>
</tr>
</table>
{% for i in form.errors %}
{{i}}
{% endfor %}
<br>
{% if form.errors %}
error!
{% endif %}
<input type="submit" value="Update">
</form>
MY issue: The page displays well. I changed something and clicked update. The page refreshed to unchanged page, without calling get_success_url() as I expected. I checked the database, record didn't update either. I checked the template again and again but didn't find error.
Following Selcuk advice, I add print form.errors. When the editing page is display, it prints all field names as error like below:
When I update, print as:
I'm not sure what's that means.
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>
I'm trying to create an admin panel where the admin can search for a user by username, first_name, last_name, zip_code (from profile model), etc. For some reason, the paginator works, but when I try to search using django-filter, nothing happens. The results don't change and I still see the whole list of all the users.
Models.py:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
birthdate = models.DateField(null=True, blank=False, max_length=8)
phone_number = PhoneNumberField(null=True, blank=False, unique=True)
filters.py
import django_filters
from django_filters import CharFilter
from django.contrib.auth.models import User
from .models import *
class AdminUserFilters(django_filters.FilterSet):
first_name_bitch = CharFilter(field_name='first_name', lookup_expr='icontains')
# last_name = CharFilter(field_name='last_name', lookup_expr='icontains')
# zip_code = User.profile.objects.filter(author__user__profile__screenname__icontains=w)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email',)
views.py
User_list = User.objects.all().order_by('username')
User_filter = AdminUserFilters(request.GET, queryset=User_list)
paginator = Paginator(User_filter.qs, 10)
page_num = request.GET.get('page', 1)
try:
User_list = paginator.page(page_num)
except PageNotAnInteger:
User_list = paginator.page(1)
except EmptyPage:
User_list = paginator.page(paginator.num_pages)
context = {'User_list': User_list, 'User_filter':User_filter, 'paginator':paginator, 'page_num':page_num,}
return render(request, "admin/listusers.html", context)
listusers.html
{{ User_filter.form }}
<br>
<button type="submit" type="button" style="height:40px; width:120px" class="btn btn-primary">Search</button>
<br><br>
{% for user in User_list %}
<tr>
<td><a href='/edit_user?edit_username={{ user.username }}'>{{ user.username }}</a></td>
<td style="min-width: 110px">{{ user.date_joined}}</td>
<td><a href='/add_household?username={{ user.username }}'>Edit Household</td>
<td>{{ user.first_name }}</td>
<td>{{ user.last_name }}</td>
<td>{{ user.profile.birthdate }}</td>
<td>{{ user.email }}</td>
<td>{{ user.profile.phone_number }}</td>
<td>{{ user.profile.zip_code }}</td>
</tr>
{% endfor %}
</table>
<p>
<br>
{% if User_list.has_previous %}
Previous
{% endif %}
{% if User_list.has_next %}
Next
{% endif %}
<br><br>
{% for pg in User_list.paginator.page_range %}
{% if page_num|slugify != pg|slugify %}
<input type="button" style="height:50px; width:40px;display: inline-block;" class="btn-primary" onclick="location.href='?page={{pg}}';" value="{{ pg }}" />
{% endif %}
{% endfor %}
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.