Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why is django app creating huge keys in redis
I am running django app (wagtail) in kubernetes cluster along with redis. These two pieces are connected by django-redis. This is how my backend configuration look { "BACKEND":"django_redis.cache.RedisCache", "LOCATION":"redis://redis-service:6379/0", "OPTIONS":{ "CLIENT_CLASS":"django_redis.client.DefaultClient", "CONNECTION_POOL_KWARGS":{ "max_connections":1000 } } } This works just fine. I can see keys getting created in redis and app is also blazing fast thanks to redis. Now real issue is every once in a while app slows down for some time. Upong investigation we found out the real issue is a key of size ~90 MB is created in redis. to process this key app takes some time and slows down. To put a comparison other keys are less than 1 MB always just 1 key gets randomly created on one type of endpoint but not always. I tried to check the contents of the key after unpickling and it is normal amounts of data just like other keys. but running redis-cli --bigkeys gives output something like this Biggest string found '":1:views.decorators.cache.cache_page.XXXXXXX.GET.9b37c27c4fc5f19eb59d8e8ba7e1999e.83bf0aec533965b875782854d37402b7.en-us.UTC"' has 90709641 bytes has someone seen similar issue? Anyway to debug the root cause. django-redis version "==4.12.1" wagtail version "==2.11.1" django version "==3.1.3" -
GET API showing KeyError in browser, but working in Postman
I have encountered a strange problem where the GET API that I created was working fine in Postman, but not working at that specific URL when entered in the browser. Here is what the input and output should look like as shown successfully in Postman: Trying API in Postman Here is what the error is showing on my browser: Error in browser I am also getting this error in React about CORS headers even though I have added in code to try to handle that issue: Error in React about CORS Here is the code in settings.py in Django: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Prediction', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Here is the code in local_settings.py in Django: ######################################### ## IMPORT LOCAL SETTINGS ## ######################################### try: from .local_settings import * except ImportError: pass DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': '127.0.0.1', 'PORT': '5432', } } ################################################################# ## (CORS) Cross-Origin Resource Sharing Settings ## ################################################################# CORS_ORIGIN_ALLOW_ALL = True I also tried adding this code in index.js in React to handle the CORS headers problem but it didn't work: const express … -
Conditional formatting Datatables to specific values in specific columns
So I have the following template: <div class="table-responsive-sm" style="overflow:scroll"> <table class="table table-striped table-bordered table-hover" id="example"> <thead class="thead-dark"> <tr> <th colspan="12" scope="colgroup"></th> </tr> <tr> <th>A</th> <th>B</th> <th>C</th> <th>D</th> <th>E</th> <th>F</th> </tr> </tbody> <tfoot> <tr> <th>A</th> <th>B</th> <th>C</th> <th>D</th> <th>E</th> <th>F</th> <th>F</th> </tr> </tfoot> </table> </div> In columns C,D and E there are values displayed, being either: R, G, Y (red, green, yellow) I have the following script: <script> $(document).ready(function() { $('#example').DataTable( { initComplete: function () { this.api().columns().every( function () { var column = this; var select = $('<select><option value=""></option></select>') .appendTo( $(column.footer()).empty() ) .on( 'change', function () { var val = $.fn.dataTable.util.escapeRegex( $(this).val() ); column .search( val ? '^'+val+'$' : '', true, false ) .draw(); } ); column.data().unique().sort().each( function ( d, j ) { select.append( '<option value="'+d+'">'+d+'</option>' ) } ); } ); } } ); } ); What I would like to do is turn the colour in each cell of columns C,D and E corresponding to the value that is found in the respective cells (R=red, G=green, Y=yellow). I managed to make a working datatables by copying this script, but I have no clue how to implement the effective code that could make the table change the colours of the cell. … -
function in another file wont get mocked
I have this class in a file called local.py: def get_credentials(creds): data = creds return data class ClassA: def __init__(self): body = "not a json" self.credentials = get_credentials(body) def run(self): print(self.credentials) def main(): inst = ClassA() inst.run() if __name__ == "__main__": main() all it does is return the credentials passed to it. I want to mock the get_credentials function for which I have another file test_local.py: from local import ClassA import unittest from unittest.mock import patch def mock_get_credentials(creds): return "123" class NameTestCase(unittest.TestCase): patch('local.get_credessntials', new=mock_get_credentials("test")) def test_whatever(self): print("true") inst = ClassA() inst.run() self.assertEqual(1, 1) if __name__ == '__main__': unittest.main() The output I keep getting is this: true not a json . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK The fact that it spits out "not a json" to me shows that it is not taking in the mocked value. I don't understand why it's doing this as I feel I have follow the documentation. Would appreciate some help with this as to why its not getting mocked. -
TypeError: Object of type 'User' is not JSON serializable. Why is this happening?
I'm trying to create a new user using DRF. The code actually creates the user but I get a 500 error saying that user is not JSON serializable. I would like to get rid of this error. Here are how my files look views.py class UserCreateAPIView(ModelViewSet): queryset = EndUser.objects.all() serializer_class = NewUserSerializer permission_classes = (AllowAny,) serializers.py class NewUserSerializer(serializers.ModelSerializer): class Meta: model = models.EndUser fields = ('id', 'first_name', 'last_name', 'email', 'title', 'user_type', 'packages', 'practice_area', 'office_phone', 'level', 'companies', 'country', 'password', 'firm', 'sectors', 'verticals', 'user_ptr') def save(self, *args, **kwargs): user = super().save(*args, **kwargs) user.set_password(user.password) user.save() urls.py router.register('new-user', views.UserCreateAPIView) Enduser inherits User. Would anyone have any ideas on how to fix this? -
Django User form not showing up in the admin page
I've been trying to implement a simple register page, but all data doesn't show up in admin. here's my views.py: from django.shortcuts import render from registro.forms import UserForm from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.contrib.auth.decorators import login_required from django.contrib.auth import authenticate, login, logout # Create your views here. def registro(request): registered = False if request.method == "POST": user_form = UserForm(request.POST) if user_form.is_valid(): #user = user_form.save() #user.set_password(user.password) user_form.save() registered = True else: print(user_form.errors) else: user_form = UserForm() return render(request,'registro/registro.html',{'user_form':user_form,'registered':registered}) forms.py: from django import forms from django.contrib.auth.models import User from registro.models import UserProfileInfo class UserForm(forms.ModelForm): class Meta(): model = User fields = ('first_name', 'last_name', 'email', 'password') labels = { 'first_name': 'Nombre', 'last_name': 'Apellidos', 'email': 'Correo Electrónico', 'password': 'Contraseña' } widgets = { 'first_name': forms.TextInput(attrs={'class': 'form-control'}), 'last_name': forms.TextInput(attrs={'class': 'form-control'}), 'email': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'e.g. algo@unison.mx'}), 'password': forms.PasswordInput(attrs={'class': 'form-control'}), } models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.email and admin.py: from django.contrib import admin from registro.models import UserProfileInfo # Register your models here. admin.site.register(UserProfileInfo) and finally, my .html page: <!DOCTYPE html> {% extends "home/base.html" %} {% block body_block %} <div class="container"> <div class="jumbotron"> {% … -
Error 403 while installing Commercial SSL certificate using nginx
Whenever the website scholarx.co is visited it throws the error 403 message. I tried adding SSL to my configuration folder. From the commercial platform where I bought the SSL, everything is working fine including the HTTPS redirect. This is how my /etc/nginx/sites-enabled/my_domain looks like server { listen 443; ssl on; ssl_certificate /path/to/certificate.chained.crt; ssl_certificate_key /path/to/certificate.key; root webroot; server_name IP_Address mydomain.co www.mydomain.co; } server { listen 80; server_name IP_Address mydomain.co www.mydomain.co; return 301 https://$host$request_uri; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /mystatic folder; } location /media/ { root /my media folder; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } The website shows that it secured and properly redirects just that I keep seeing that error. Note this is a Django application. Whenever I run sudo nginx -t, I get this nginx: [warn] conflicting server name "IP_Adddress" on 0.0.0.0:80, ignored nginx: [warn] conflicting server name "mydomain.co" on 0.0.0.0:80, ignored nginx: [warn] conflicting server name "www.mydomain.co" on 0.0.0.0:80, ignored nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful Someone should kindly help out with this. Thanks -
Best approach to use Many to Many in Django + SQL
I am making a web app and i wish to use many to many fields in models.I haven't given much thought before and have simply used many to many field in models but now i am thinking how actually these many to many are stored in database and what would be the best approach when using Many to Many Fields in Models. Approach 1: class Company(models.Model): name = models.CharField(max_length = 190,blank = False,null = False) about = models.CharField(max_length = 260,blank = False,null = True) website = models.URLField(blank = False) address = models.OneToOneField(Address,related_name="org_address",on_delete=models.SET_NULL,null=True) admin = models.ManyToManyField(User,related_name="org_admin",blank = False) created_on = models.DateTimeField(default = timezone.now) updated_on = models.DateTimeField(default = timezone.now) OR Approach 2: class Company(models.Model): name = models.CharField(max_length = 190,blank = False,null = False) about = models.CharField(max_length = 260,blank = False,null = True) website = models.URLField(blank = False) address = models.OneToOneField(Address,related_name="org_address",on_delete=models.SET_NULL,null=True) created_on = models.DateTimeField(default = timezone.now) updated_on = models.DateTimeField(default = timezone.now) class CompanyAdmin(models.Model): admin = models.ManyToManyField(User,related_name="org_admin",blank = False) company = models.ForeignKey(Company,related_name="company",on_delete=models.CASCADE) Do both methods handle many to many fields in the same way ? I am using MySQL as Database -
Right way for copying MPTT trees
Imagine I have some tree (MPTTTModel): Root | -- Node 1 -- Node 2 | -- Node 2-1 -- Node 2-2 -- Node 2-3 | --Node 2-3-1 -- Node 3 | -- Node 3-1 -- Node 4 This tree also has some common custom fields like for example 'name', 'category' and some FK field and M2M field(technologies). Here is my model btw: class Product(MPTTModel): objects = CustomProductManager() code = models.CharField(max_length=50) quantity = models.PositiveIntegerField(default=1) name = models.CharField(max_length=255) slug = AutoSlugField(_('slug'), max_length=255, unique=True, populate_from=('name', 'pk')) status = models.CharField(max_length=255, default='Exists') parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') technologies = models.ManyToManyField('Technology', blank=True) category = TreeForeignKey('Category', on_delete=models.SET_NULL, null=True, blank=True, related_name='sub_products') description = models.TextField(blank=True, null=True) manufactured = models.BooleanField(default=False) purchased = models.BooleanField(default=False) assembly = models.BooleanField(default=False) class MPTTMeta: order_insertion_by = ['code'] def __str__(self): return f'{self.code} {self.name}' How can I copy a full tree with its structure and all the fields? I tried to do bulk create in this way: A model for creating dummy PKs for bulk_create'ed products: class DummyProductId(models.Model): pass Function to do a dict from node: def recursive_node_to_dict(node): """For copying trees.""" latest_created_dummy_id = DummyProductId.objects.last().pk new_id = latest_created_dummy_id + latest_created_dummy_id if node.parent_id: new_parent_id = node.parent_id + latest_created_dummy_id else: new_parent_id = None result = { 'id': new_id, 'code': … -
The view app.views.services didn't return an HttpResponse object. It returned None instead
I have looked for an answer and all I can find are answers related to forms. I haven't seen anything related to a model object. I have a model called PanelType and I am trying to loop through every object to display relevant information pertaining to each panel type on a html template. I have created 3 PanelType objects through the admin page, so there is not "None". I believe I have this setup correctly but it's returning an error. I'd appreciate any help. models.py class PanelType(models.Model): name = models.CharField('Name', max_length=150, default='') slug = models.SlugField(unique=True) description = models.TextField('Description', null=True, blank=True) date_created = models.DateTimeField( 'Date Created', auto_now_add=True, null=True) display = models.BooleanField(default=True) image = models.ImageField('Panel Image', null=True, blank=True) def get_absolute_url(self): return reverse("model_detail", kwargs={"pk": self.pk}) def __str__(self): return f'{self.name}' def save(self, *args, **kwargs): if not self.slug or self.slug != slugify(self.name): self.slug = slugify(self.name) return super().save(*args, **kwargs) views.py def services(request): context = {'panels': PanelType.objects.all()} render(request, 'app/services.html', context) html <div class="service-container"> {% for panel in panels %} <div class="card"> <div class="serviceBx" data-text="{{panel.name}}"> <img src="{{panel.image.url}}" alt=""> </div> <div class="service-content"> <div> <h3>{{panel.name}}</h3> <p>{{panel.description}}</p> <a href="#">Get Quote</a> </div> </div> </div> {% endfor %} </div> -
Django: Reset model field value at start of certain time (e.g., End of Day, Start of month, etc.)
Let's say I have a model Person who has some amount of money (starting with 0): #myapp/models.py from decimal import Decimal class Person(models.Model): name = models.CharField(max_length=255) money = models.DecimalField(max_num=6, decimal_places=2, default=Decimal('0.00')) And throughout the day the user can collect money: person = Person.objects.create(name="Jeff") person.money += 100 print(person.money) # 100.00 But at the end of the day, the number should automatically go back to zero: # At 12:00 AM the next day >>> person = Person.objects.get(name="Jeff") >>> person.money = 0.00 Or say at the start of the month the person is automatically given $100 (instead of resetting). # At 12:00 AM on first day of month >>> person = Person.objects.get(name="Jeff") >>> person.money # 200.00 How would you do this on a Django model? -
Django, download static fiels
I'm new to Django and trying to create a simple button to download some files from a database. I have a simple schema class DataSets(models.Model): name = models.CharField(max_length=120) csv_blob = models.FileField(upload_to='uploads/') json_blob = models.FileField(upload_to='uploads/') And an index.html which uses data from the database {% for document in file_list %} <a href="{{ document.csv_blob.url }}" download class="btn">{{ document.name }}_CSV</a> <a href="{{ document.json_blob.url }}" download class="btn">{{ document.name }}_JSON</a> {% endfor %} I uploaded a sample entry but when I click the button to download it I get Not Found: /uploads/test_csv.txt [17/Nov/2020 19:22:11] "GET /uploads/test_csv.txt HTTP/1.1" 404 2113 What am I missing? -
"NoReverseMatch" Reverse for 'by_rubric' with arguments '('',)' not found
I'm extremely new to Python and Django. I tried to make a code from exercise work, and it was fine for a while, but since I tried to implement templates inheritance I've got this error on my homepage. Rest are working fine...for now. I tried to find solution in similar topics and django docs.,but it didn't help me. Please give me a hand on this one, cause having error at line 0 when I have only 1,2,3.. is really frustrating. Due to my lack of knowledge it's hard to understand even which file is responsible for this error. Error: NoReverseMatch at /bboard/ Reverse for 'by_rubric' with arguments '('',)' not found. 1 pattern(s) tried: ['bboard/(?P<rubric_id>[0-9]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/bboard/ Django Version: 3.1.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'by_rubric' with arguments '('',)' not found. 1 pattern(s) tried: ['bboard/(?P<rubric_id>[0-9]+)/$'] Exception Location: D:\django\venv_1\lib\site-packages\django\urls\resolvers.py, line 685, in _reverse_with_prefix Python Executable: D:\django\venv_1\Scripts\python.exe Python Version: 3.8.5 My views.py: from django.shortcuts import render from django.views.generic.edit import CreateView from django.urls import reverse_lazy from .models import Rubric from .models import Bb from .forms import BbForm def index(request): bbs = Bb.objects.all() rubrics = Rubric.objects.all() context = {'bbs': bbs, 'rubrics': rubrics} return render(request, 'bboard/index.html', context) def by_rubric(request, rubric_id): … -
Django Cannot Assign Database Relation Error
I have read many entries but couldn't find the answer. Here are my models: class Branches(models.Model): branch_name = models.CharField(max_length=200) def __str__(self): return self.branch_name class Agents(models.Model): branch_name = models.ForeignKey(Branches, null=True, on_delete=models.SET_NULL) agent_name = models.CharField(max_length=200) def __str__(self): return self.agent_name class Policies(models.Model): policy_n = models.CharField(max_length=100) account = models.CharField(max_length=100) agent_name = models.ForeignKey(Agents, null=True, on_delete=models.SET_NULL) branch_name = models.ForeignKey(Branches, null=True, on_delete=models.SET_NULL) And the code that inserts data into related tables in my view.py file: policies = pd.read('policies.xlsx') for i in policies.branches.unique(): branch = Branches() branch.branch_name = i branch.save() for j in policies.agents.unique(): agent = Agents() agent.agent_name = j agent.save() for i in range(len(policies)): policy = Policies() policy.policy_n = policies.policy_num[i] policy.account = policies.account[i] policy.branch_name = Branches.objects.get(branch_name=policies.branch[i]) policy.agent_name = Agents.objects.get(agent_name=policies.agent_name[i]) I am getting the error: ValueError: Cannot assign "(<Branches: Copenhagen>,)": "Policies.branch_name" must be a "Branches" instance. Can anybody help please. -
django 3.1 model based menu three line treemenu
1 What I want to do is menu (if menu.parentId == Null) |_menu (if menu.parentId != Null and menu.parentId == menu.Id) |_ menu (if menu.parentId == menu.Id) model view result -
Django Open rendered HTML file
Guys i want to open rendered HTML file when i am clicking a image on my HTML page. How i should use it? HTML code fragment <header> <nav class="headlist"> <a href='{% url **Link to home_view** %}'><img id = "img1" src="{% static 'css/logo.png' %}" alt="logo"></a> <ul> <li><a href="{% url **Link to about_view** %}">O nas</a></li> <li><a href="{% url **Link to contact_view** %}">Kontakt</a></li> <li><a>Zajęcia</a></li> </ul> </nav> </header> main app urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), ] pages app urls.py from django.urls import path from . import views urlpatterns = [ path('kontakt/', views.contact_view), path('o_nas/', views.about_view), path('', views.home_view), ] pages app views.py from django.shortcuts import render def home_view(reqest): return render(reqest, "index.html") def about_view(reqest): return render(reqest, "about.html") def contact_view(reqest): return render(reqest, "contact.html") -
How can i set domain name in absolute url for imagefield drf?
Now if i get some data via swagger, ImageField looks like http://api.some.com/media/picture.jpg. How can i change http://api.some.com to https://api2.some.com for all ImageField's i can get from my API? -
Is there a way to filter the form views in django to show only the ones available?
How do i span through some form fields if they are not filled in and only show the filled ones alone?? I could have used a for loop but that's a long process. Which is the easy way?? When the user fills in some of the i.feature i need to only display the filled in ones alone My html file {% for i in psts %} <div class="card p-3"> <img class="card-img-top" src="{{ i.image_p.url }}" alt=""> <div class="card-body"> <h5 class="card-title">{{ i.post_title }}</h5> <p class="card-text"> {{ i.some_info }} </p> <ul> <li> <i class="fa fa-check"></i> {{ i.feature1 }} </li> <li> <i class="fa fa-check"></i> {{ i.feature2 }} </li> <li> <i class="fa fa-check"></i> {{ i.feature3 }} </li> <li> <i class="fa fa-check"></i> {{ i.feature4 }} </li> <li> <i class="fa fa-check"></i> {{ i.feature5 }} </li> </ul> <p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> </div> </div> {% endfor %} My models.py from django.db import models class posts(models.Model): post_title = models.CharField(max_length=50) image_p = models.ImageField(default='default.jpg', upload_to='post_images') some_info = models.CharField(max_length=200, blank=True) feature1 = models.CharField(max_length=100, blank=True) feature2 = models.CharField(max_length=100, blank=True) feature3 = models.CharField(max_length=100, blank=True) feature4 = models.CharField(max_length=100, blank=True) feature5 = models.CharField(max_length=100, blank=True) def __str__(self): return self.post_title -
Not able to run the coverage with pytest
Facing issues in running the pytest with coverage, I have gone through the SO posts and not able to fix this, I believe I'm missing something here.. !! Getting the following errors where users is an app of my project ModuleNotFoundError: No module named 'users' django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. My pytest.ini file contents [pytest] DJANGO_SETTINGS_MODULE = cloudstack.settings python_files = tests.py test_*.py *_test.py addopts = -v --ignore=venv --cov=. --cov-report=html I have tried adding DJANGO_SETTINGS_MODULE as environment variable too then I'm getting different error saying that cloudstack module is not found. I'm in the activated environment while performing these tests. -
urls not overlapping -- How to fix
I am trying to filter products either by brand or category but the url path will only execute path('<slug:brand_slug>/', views.product_list,name='product_list_by_brand'), since it appears first and would not execute the second. Is there a way I can probably merge both paths or cause both paths to work independently without taking order into consideration. from . import views app_name = 'shop' urlpatterns = [ path('', views.product_list, name='product_list'), path('<slug:brand_slug>/', views.product_list,name='product_list_by_brand'), path('<slug:category_slug>/', views.product_list,name='product_list_by_category'), ] Thank you in advance for your response. -
Django Tutorial Add/Remove Polls Questions
I am working through the Django tutorial of creating an app, found at: https://docs.djangoproject.com/en/3.1/intro/tutorial01/ I have completed the tutorial just as the link has instructed and I have a site that takes the polls. It runs well, however I would like to make the polls more interactive to the user by allowing users to add and remove questions on the polls page, without having to go through the admin page. How can I go about this? Thank you! -
Display & Update in same Django form
[A newbie Question] I have a form that shows the student details (query filtered by learner_code). I have an edit button that removes the "disabled" tag from fields & let user edit the form details. I have a Save button as well. I want to save the update back to the same entry in Student model. My views.py : query = None if 'learner_code' in request.GET: query = request.GET['learner_code'] try: student_details = Student.objects.get(learner_code=query) except: messages.error(request, f'Student Not Found !') return redirect('viewstudent') else: context = { 'student_details' : student_details} return render(request, 'students/viewstudent.html', context) elif 'learner_code' in request.POST : # Save the data back to the table else: return render(request, 'students/createstudent.html') My model looks like : class Student(models.Model): pay = (('FULL', 'FULL'),('EMI', 'EMI')) learner_code = models.CharField(max_length=15, null=False, primary_key=True) certificate_name = models.CharField(max_length=150, null=False) contact1 = models.CharField(max_length=10, null=False) contact2 = models.CharField(max_length=10) batch = models.CharField(max_length=10) doj = models.DateField(null=False, default=localtime(now()).date()) payment_method = models.CharField(choices=pay, max_length=4, default='FULL') total_paid = models.IntegerField(default=0) def __str__(self): return self.learner_code My forms.py is : class StudentCreationForm(forms.ModelForm): class Meta: model = Student fields = '__all__' My Template looks like : {% block content %} <div class="container mx-auto mt-3"> {% block form %} <form class="form-row mr-auto" action="" method="get"> <input type="text" class="form-control" name="learner_code" id="search" placeholder="Learner Code" style="width: … -
Django FileField uploads a "None" File to the directory?
I have a Classworks Model and in it I have added FileField to upload files in the media root, and I have tried to add a classwork using the admin, but when I checked the directory it said None!!! can someone explain why did this happen?? How can I upload it correctly and if it is uploaded correctly how can it be retrieved ?? here is the model : def classwork_add_file(instance, *args, **kwargs): return f'uploads/{instance.Type}/{instance.Teacher}/{instance.Class}/{instance.questionNumber}/' class ClassWorks(models.Model): Type = models.CharField(max_length=20, default="ClassWorks") Class = models.ForeignKey(Classes, on_delete=models.CASCADE, null=True) Teacher = models.CharField(max_length=100, null=True, blank=True) questionNumber = models.AutoField(primary_key=True) Title = models.CharField(max_length=100) Definition = models.CharField(max_length=200) File1 = models.FileField(upload_to=classwork_add_file, null=True, blank=True) File2 = models.FileField(upload_to=classwork_add_file, null=True, blank=True) File3 = models.FileField(upload_to=classwork_add_file, null=True, blank=True) File4 = models.FileField(upload_to=classwork_add_file, null=True, blank=True) File5 = models.FileField(upload_to=classwork_add_file, null=True, blank=True) DateAdded = models.DateTimeField(auto_now_add=True) DateOfSubmission = models.DateTimeField() def clean(self): if self.Teacher is None: self.Teacher = self.Class.Teacher -
Django pagination. How can I improve performance in order to load a subset of 100 from 150k rows?
I am trying to paginate over 150k records with a subset of 100 items per page, however since I am using mongo + Redis. my query handler uses .limit() to speed up the data display. so it will be 100, 200, 300 in a subset of that items per page . eg. page=1 , 100 , page=2, another 100, but the user will only see page?={page_number}. I want to make the use of from django.core.paginator import InvalidPage, Paginator or a global paginator in DRF or as last option make a custom overwrite of the class to paginate over limit, and let the user paginate in a friendly format class UserViewSet(viewsets.GenericViewSet): queryset = [] http_method_names = ['get'] def list(self, request): start_time = time.time() limit = 100 * (1-1) # this makes 0 , and freeze the database , to it needs to start from 2 cves = getCVEs(limit=1) # return a big json of data see below elapsed_time = time.time() - start_time print(elapsed_time) return Response(cves) def getCVEs(limit=False, query=[], skip=0, , cve=None, collection=None): [..] cve = col.find().sort("Modified", pymongo.DESCENDING).limit(limit).skip(skip).allow_disk_use(True) [..] return {"results": sanitize(cve), "total": cve.count()} json obj from getCVES { "results":[ { "id":"xxxxxxxx", "assigner":"xxxxxx", "Published":"2020-02-20T20:15:00", "Modified":"2020-11-17T00:15:00", "last-modified":"2020-11-17T00:15:00", "summary":"", "access":{ "authentication":"xxxxxxxx", "complexity":"xxxxxxxx", "vector":"xxxxxxxx" }, … -
'NoneType' object has no attribute 'is_staff'
I have created a login page and the related code in views.py and the associated code in views.py and the html login page is as follows: views.py: def Login_User(request): error = "" if request.method == "POST": u = request.POST['uname'] p = request.POST['pwd'] user = authenticate(username=u, password=p) sign = "" if not user.is_staff: try: sign = Customer.objects.get(user=user) except: pass if sign: login(request, user) error = "pat1" else: error = "not" elif user.is_staff: login(request,user) error="admin" else: error="not" d = {'error': error} return render(request, 'login.html', d) login.html: {% ifequal error "pat1" %} <script> alert('logged in successfully'); window.location=('{% url 'home' %}'); </script> {% endifequal %} {% ifequal error "admin" %} <script> alert('logged in successfully'); window.location=('{% url 'admin_home' %}'); </script> {% endifequal %} {% ifequal error "not" %} <script> alert('Invalid username or password'); </script> {% endifequal %} On entering a wrong username or password, it should return an alert message saying 'Invalid Username or password'. Instead it's showing an error like this: AttributeError at /login 'NoneType' object has no attribute 'is_staff'