Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serializers VS ModelForms in User Registration, Django Rest Framework
What to use while registering a user ? Serializer or ModelForms ? I have been using DRF since a long time now but I have been opting for old school ModelForm (forms.ModelForm) method for user registration. I just want to know that is it necessary to use modelForm for user Registration or we could use serializer as well like we do for all the APIs ? PS : I have overriden the user Modal along with the Managers : class MyAccountManager(BaseUserManager): def create_user(self, email, name, password): if not email: raise ValueError('User must have an email address') if not name: raise ValueError('User must have a name') user = self.model( email=self.normalize_email(email), name=name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name, password): user = self.create_user( name=name, email=self.normalize_email(email), password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.is_customer = False user.save(using=self._db) return user ` class User(AbstractBaseUser, CreationUpdationMixin): first_name = None last_name = None date_joined = None email = models.EmailField(unique=True) name = models.CharField(max_length=200) phone = models.CharField(max_length=20, default='') is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_customer = models.BooleanField(default=True) is_seller = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] objects = MyAccountManager() ` -
django custom save insert to multiple table
I have an Item table and TransactionLog table, When I create an item it should also create a log this is my models.py class Item(models.Model): itemid = models.CharField(primary_key=True, max_length=20) name = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'items' def save(self, *args, **kwargs): TransactionLog.objects.create(itemid=self.cl_itemid, trans_desc="Add Clearance Item", trans_recorded=timezone.now()) super(Item, self).save(*args, **kwargs) class TransactionLog(models.Model): log_id = models.AutoField(primary_key=True) itemid = models.ForeignKey('Item', models.DO_NOTHING, db_column='itemid', blank=True, null=True) trans_desc = models.TextField(blank=True, null=True) trans_recorded = models.DateField(blank=True, null=True) class Meta: managed = False db_table = 'transaction_log' but When I try to insert it's saying Cannot assign "'CL-20221106-0000'": "TransactionLog.itemid" must be a "Item" instance. maybe because the Item isnt created yet? -
Send email in Django now that Google changed the policy . WinError 10061] No connection could be made because the target machine actively refused it
I'm working on a Django project. I need to send my users the emails and receive the contact us form when users submit the form. I'm using Gmail. As I watched tutorials, the email which receives the emails need to turn on less secure on security section. However, as May 2022 google changed the policy and now the option is not there. https://support.google.com/accounts/answer/6010255?authuser=1&hl=en&authuser=1&visit_id=638033119094066220-3031639860&p=less-secure-apps&rd=1 So, now when I'm trying to send an email I face the following error. ConnectionRefusedError at /contact/ [WinError 10061] No connection could be made because the target machine actively refused it Request Method: POST Request URL: http://127.0.0.1:8000/contact/ Django Version: 4.1.2 Exception Type: ConnectionRefusedError Exception Value: [WinError 10061] No connection could be made because the target machine actively refused it Exception Location: C:\Users\Sed AKH\AppData\Local\Programs\Python\Python38\lib\socket.py, line 796, in create_connection Raised during: main.views.contact Python Executable: C:\Users\Sed AKH\AppData\Local\Programs\Python\Python38\python.exe Python Version: 3.8.1 Python Path: ['E:\\Projects\\Python\\Django\\weblimey', 'C:\\Users\\Sed AKH\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip', 'C:\\Users\\Sed AKH\\AppData\\Local\\Programs\\Python\\Python38\\DLLs', 'C:\\Users\\Sed AKH\\AppData\\Local\\Programs\\Python\\Python38\\lib', 'C:\\Users\\Sed AKH\\AppData\\Local\\Programs\\Python\\Python38', 'C:\\Users\\Sed ' 'AKH\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages', 'C:\\Users\\Sed ' 'AKH\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\win32', 'C:\\Users\\Sed ' 'AKH\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\win32\\lib', 'C:\\Users\\Sed ' 'AKH\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages\\Pythonwin'] Server time: Sun, 06 Nov 2022 06:26:20 +0000 And here my code : def contact(request): if request.method == 'POST': try: contact = ContactForm() name = request.POST.get('name') email = request.POST.get('email') message = request.POST.get('message') contact.name = name contact.email = … -
django custom save auto increament id
I posted a question few months ago django create custom id def save() I want to create an custom id using auto-increment but when I try to use his code into mine def get_default_id(): last_id = Item.objects.last().cl_itemid split_id = last_id.split('-') split_id[-1] = str(int(split_id[-1])+1) new_id = '-'.join(split_id) return new_id class ClearanceItem(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=20, default=get_default_id) studid = models.CharField(max_length=9, blank=True, null=True) office = models.ForeignKey('ClearingOffice', models.DO_NOTHING, blank=True, null=True) sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) remarks = models.TextField(blank=True, null=True) resolution = models.TextField(blank=True, null=True) resolve = models.BooleanField(blank=True, null=True) resolve_date = models.DateField(blank=True, null=True) resolve_by = models.CharField(max_length=8, blank=True, null=True) recorded_by = models.CharField(max_length=8, blank=True, null=True) record_date = models.DateField(default=datetime.now, blank=True, null=True) class Meta: managed = False db_table = 'clearance_item' After I insert data via postman { "office": "OSA", "sem": "1", "sy": "2022-2023", "remarks": "TEST from November 6", "resolution": "TEST", "studid": "2012-5037" } When I open my clearance_item table, this is the row displayed |cl_itemid |studid |office|sem|sy |remarks |resolution| |WTF2022-20223-10|2012-5037|OSA |1 |2022-2023|TEST from November 6|TEST My Question is where is that WTF's coming from? it should be OSA2022-20232-10 based on this format officesy-sem-10 Second is when I try to insert the same data it's saying (cl_itemid)=(WTF2022-20223-10) already exists. instead of WTF2022-20223-11 but then I change … -
DRF - Testing, error while hitting sinlgle data from id
Urls.py router = routers.DefaultRouter() router.register('zone', views.ZoneViewSet, basename='zone') app_name = 'address' API. urlpatterns = [ path('', include(router.urls)), ] Test.py RECIPES_URL = reverse('address:zone-list') def details_url(id): print(RECIPES_URL,id) return reverse(RECIPES_URL.strip(),args=[id]) print -> /api/address/zone/ 1 def test_zone_details(self): task = sample_payload() url = details_url(task.id) res = self.client.get(url) self.assertEqual(res.status_code, status.HTTP_200_OK) ERROR: test_zone_details (address.tests.ZoneApiTestCase) raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for '/api/address/zone/' not found. '/api/address/zone/' is not a valid view function or pattern name. -
Django Postgres database not updating fields anymore
I have the following for loop to iterate over a dictionary and save it to the database, and it used to work, but randomly stopped. I'm not getting any errors, and my database logs show that there is an UPDATE query happening, so everything seems to be working correctly but whenever I check the database if the information is updated, it isn't. It looks like INSERT and SELECT queries are still working. for key, value in data.items(): if value == 'null': pass else: UserModel.objects.filter(id=user.id).update(**{key: value}) This is the SQL query: [DATABASE] [605-1] sql_error_code = 00000 time_ms = "2022-11-06 04:02:47.750 UTC" pid="235484" proc_start_time="2022-11-06 03:58:51 UTC" session_id="636730fb.397dc" vtid="2/1215752" tid="0" log_line="595" database="d7dd2o7lqkb580" connection_source="18.206.16.69(43354)" user="u571qd3ks8ldkb" application_name="[unknown]" LOG: statement: UPDATE "accounts_account" SET "first_name" = 'testing' WHERE "accounts_account"."id" = 3323 My database is a Postgres database attached to my server and is hosted on Heroku. I would really appreciate any help in resolving this issue. -
I tried to create a Django view with async but it shows SynchronousOnlyOperation errors
I am trying to create an async django view which fetch status code from multiple urls. This is my views.py async def get_page(session, url, urlMain): async with session.get(url) as response: st_code= await response.status return url, st_code, urlMain async def create_search(request): form = SearchForm() if request.method == 'POST': name = request.POST['name'] tasks = [] async with aiohttp.ClientSession() as session: for item in data: url = data[item]['url'] urlMain = data[item]['urlMain'] tasks.append(get_page(session, url, urlMain)) results = await asyncio.gather(*tasks) for url, st_code, urlMain in results: if st_code == 200: site_data = SearchResult( url = urlMain, sitename = item, ) site_data.save() context = {'form':form} return render(request, 'index.html', context ) While running django it shows me this error. SynchronousOnlyOperation at /create-search/ You cannot call this from an async context - use a thread or sync_to_async. -
Django Admin Inline Form Fails in Test but Works in Admin Interface
So I am at a loss as to why the following example fails in a test case, but works perfectly fine in the admin interface. I have a very basic User and Login models. The Login simply records user logins into the system via Django signal. class User(AbstractUser): company = models.CharField( max_length=100, blank=True, null=True ) class Login(models.Model): """Represents a record of a user login event.""" user = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name="logins" ) ip = models.GenericIPAddressField() user_agent = models.TextField() date = models.DateTimeField(auto_now_add=True, db_index=True) domain = models.CharField(max_length=255) http_host = models.CharField(null=True, max_length=255) remote_host = models.CharField(null=True, max_length=255) server_name = models.CharField(null=True, max_length=255) In the admin.py I define a UserAdmin with inlines = [LoginInline]. Basically when viewing the user I can see the login history. from django.contrib import admin from django.contrib.auth import admin as auth_admin from django.contrib.auth import get_user_model from django.urls import reverse from django.utils.html import format_html from users.models import Login User = get_user_model() class ReadOnlyModelMixin: def has_add_permission(self, request, obj=None): return False def has_change_permission(self, request, obj=None): return False def has_delete_permission(self, request, obj=None): return False class LoginAdmin(ReadOnlyModelMixin, admin.ModelAdmin): list_display = ( 'id', 'user_link_with_name', 'user_email', 'user_company', 'domain', 'date', 'ip', 'remote_host', 'http_host', 'server_name', 'user_agent', ) @admin.display(description='Name', ordering='user__first_name') def user_link_with_name(self, obj): url = reverse("admin:users_user_change", args=[obj.user.id]) return format_html(f'<a href="{url}">{obj.user}</a>') @admin.display(description='Email', ordering='user__email') … -
AttributeError: 'list' object has no attribute 'startswith' python manage.py collectstatic
hello when I do python3 manage.py collectastatic I get this error and I can't find how to fix it. In the terminal I get this: /usr/local/lib/python3.8/dist-packages/environ/environ.py:615: UserWarning: Engine not recognized from url: {'NAME': 'postgres://paycoin*-postgres.render.com/paycoin', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', 'ENGINE': ''} warnings.warn("Engine not recognized from url: {}".format(config)) Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/lib/python3/dist-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/usr/lib/python3/dist-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/lib/python3/dist-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/lib/python3/dist-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.8/importlib/__init__.py", line 118, in import_module if name.startswith('.'): AttributeError: 'list' object has no attribute 'startswith' when I do python3 manage.py collectastatic I get this error and I can't find how to fix it. I was expecting a folder named static to be created in VSC but I get this error -
How to implement like/dislike button (for non-logged-in users) in django
Am trying how to implement like and dislike feature in django without an end user logging into a account, using django. I have not seen documentation for the non-logging end user for like and dislike feature in django -
Additional save button on Django admin pages
How can you add an extra Save-button on admin list view pages, like shown on the image, that saves the changes but also does something extra before or afterwards? I know that it possible to achieve this functionality via "actions" but it is cumbersome to select the correct action from select-box, when you need to do it repetitively. It would be beneficial to be able to add extra save button both to the list view and the change view. -
Require minimum password complexity in django allauth
I am trying to implement a minimum set of criteria for passwords. However, even with the below, users are able to sign up with a single character password. How can I require a certain minimum password complexity when using django-allauth with a custom adapter. # adapter.py from typing import Any from allauth.account.adapter import DefaultAccountAdapter from allauth.socialaccount.adapter import DefaultSocialAccountAdapter from allauth.exceptions import ImmediateHttpResponse from django.conf import settings from django.forms import ValidationError from django.http import HttpRequest class AccountAdapter(DefaultAccountAdapter): def is_open_for_signup(self, request: HttpRequest): return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True) def clean_password(self, password, user=None): special_characters = "[~\!@#\$%\^&\*\(\)_\+{}\":;'\[\]]" min_length = 1 if len(password) < 8: raise ValidationError('Password length must be greater than 8 characters.') if not any(char.isdigit() for char in password): raise ValidationError('Password must contain at least %(min_length)d digits.') % {'min_length': min_length} if not any(char.isalpha() for char in password): raise ValidationError('Password must contain at least %(min_length)d letters.') % {'min_length': min_length} if not any(char in special_characters for char in password): raise ValidationError('Password must contain at least %(min_length)d special characters.') % {'min_length': min_length} return password class SocialAccountAdapter(DefaultSocialAccountAdapter): def is_open_for_signup(self, request: HttpRequest, sociallogin: Any): return getattr(settings, "ACCOUNT_ALLOW_REGISTRATION", True) # settings.py # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_ADAPTER = "project.adapters.user.AccountAdapter" # https://django-allauth.readthedocs.io/en/latest/forms.html ACCOUNT_FORMS = {"signup": "project.forms.user.UserSignupForm"} # https://django-allauth.readthedocs.io/en/latest/configuration.html SOCIALACCOUNT_ADAPTER = "project.adapters.user.SocialAccountAdapter" -
SQLite Django views.py syntax confusion for posting to database
I am learning Django and following a tutorial by Telusko. Earlier in the course he switched to Postgresql but I couldnt get it to work so I decided to move on with SQLite since it was already installed. He showed this code to Add User to the database: def register(request): if request.method == "POST": firstname= request.POST['firstname'] lastname= request.POST['lastname'] email= request.POST['email'] phone= request.POST['phone'] username= request.POST['username'] password1= request.POST['password1'] password2= request.POST['password2'] dob= request.POST['dob'] gender= request.POST['gender'] user = User.objects.create_user(username=username, email=email, phone=phone, password=password1, dob=dob, gender=gender, firstname=firstname, lastname=lastname,) user.save(); print('user created') return redirect("/") else: return render(request, 'register.html') ; But this does not work for me I get this error when I submit Environment: Request Method: POST Request URL: http://127.0.0.1:8000/register Django Version: 4.1.3 Python Version: 3.11.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'login.apps.LoginConfig'] Installed Middleware: ['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'] Traceback (most recent call last): File "C:\Users\yuri\Desktop\naisuback\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\yuri\Desktop\naisuback\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\yuri\Desktop\naisuback\login\views.py", line 30, in register user = User.objects.create_user(username=username, email=email, phone=phone, password=password1, dob=dob, gender=gender, firstname=firstname, lastname=lastname,) Exception Type: AttributeError at /register Exception Value: 'Manager' object has no attribute 'create_user' Sorry if I provided too much information this is … -
Como desplegar Django con React [closed]
hice una web con una plantilla en react y el back con Django, los tengo en carpetas separadas pero ahora nose como desplegarlo. Es mi primer cliente y mi primer despliego estoy medio perdido, se que tengo que usar un VPS, pero nose como hostearlo, ya que ambos funcionan en un localhost diferentes, gracias! -
Django error: Invalid block tag on line 28: 'endfor'. Did you forget to register or load this tag?
I'm stuck on this error I am a new user of Django I am following the steps correctly and learning through YT. When I run python manage.py runserver the HTML shows My index.html file <!DOCTYPE html> <header> CRUD Operation with PostgreSQL </header> <body> <center> <h1>How to create CURD Ops with PostgreSQL</h1> <h3>Learning Django and CURD</h3> <hr/> <table border = "1"> <tr> <th>Employee Id</th> <th>Employee Name</th> <th>Email</th> <th>Occupation</th> <th>Salary</th> <th>Gender</th> </tr> {% for results in data% } <tr> <td>{{result.id}}</td> <td>{{result.name}}</td> <td>{{result.email}}</td> <td>{{result.occupation}}</td> <td>{{result.salary}}</td> <td>{{result.gender}}</td> </tr> {% endfor %} </table> </center> </body> I tried to change endfor to endblock nothing works. I don't know how to solve this, Please help. -
Django - annotate the most frequent field taken from another model linked with foreignKey
I have a model of users and a model with a survey in which users express their opinion with a vote with an integer number that identified a particular color of eyes. A srcID user describes the color of the eyes of a dstID user according to his opinion. A user can votes himself. It's possible that a user doesn't receive any votes so there isn't a tuple with dstID equal to his ID. The integer number of eyeColor rapresent a specific color, for instance: 1 => blue eyes 2 => lightblue eyes 3 => brown eyes 3 => green eyes ecc. class user: userID = models.AutoField(primary_key = True, auto_created = True, unique = True) name = models.CharField(max_length=100) class survey: srcID = models.ForeignKey(user, on_delete = models.CASCADE, related_name='hookSrc') dstID = models.ForeignKey(user, on_delete = models.CASCADE, related_name='hookDst') eyesColor= models.IntegerField() My goal is to annotate in the user model the most frequent type of eyeColor voted, so the eyesColor that other people think is the eyesColor of that user. If a user doesn't receive any votes I want to annotate 0. In case there are more than one color with the same voting frequency, if the user has voted himself (tuple with srcID = … -
Will I need to create a virtualenv every time I runserver with Django?
Currently taking CS50 Web Programming with Python and Javascript. I'm on the Week 3 Django lecture and trying to follow along but I'm running into trouble while trying to run python manage.py run server. I'm getting the "ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?" error. I'm using Windows, Django IS installed and I've reinstalled it multiple times. I've found a workaround by following the steps from https://www.youtube.com/watch?v=eJdfsrvnhTE&t=296s to set up a virtual env and can proceed after that, but in the lecture Brian doesn't need to setup a virtual env? It just loads straight through for him? Yes I have scoured through reddit, stackoverflow, youtube, and other articles online before asking this here. It's not too much trouble to do so but I'm just wondeirng why he didn't need to make a virtualenv and if I'm actually going to have to make a virtual env for every Django project going forward? Is it because things have changed with python/pip/Django? I would just find it more convenient if I could just run the run server command without having to run the extra 4 commands … -
hi, i have this error when i try to make migrations comand with django project: [duplicate]
I have not been able to find a solution to this problem since the database or mysql is not right, I do not understand it, if anyone knows a solution for this, my OS is mojave on Mac, I do not know if it is because of the version or what problem it has this bash: : command not found (base) MacBook-Pro-de-andrex:python_web andrexbaldion$ python3 manage.py makemigrations Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/MySQLdb/_mysql.cpython-311-darwin.so, 2): Library not loaded: @rpath/libmysqlclient.18.dylib Referenced from: /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/MySQLdb/_mysql.cpython-311-darwin.so Reason: image not found During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/andrexbaldion/Desktop/djangoproyecto2/python_web/manage.py", line 22, in <module> main() File "/Users/andrexbaldion/Desktop/djangoproyecto2/python_web/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked … -
Django static files not working in localhost
I have my Django app running on a development server. The HTML templates are serving fine but I'm really having a lot of trouble getting the static files to serve. I've tried lots of ideas from Stack Overflow but not getting anywhere. I just get a 404 error on the image. Can anyone help me please? My urls.py is: from django.contrib import admin from django.urls import path from app import views from django.contrib.auth import views as auth_views from django.conf.urls.static import static from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns # The rest of my urls here... urlpatterns = [ path('', views.index, name='index'), path('admin/', admin.site.urls), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) my settings has included: STATIC_ROOT = "/home/me/django-test/djangoproject/static" STATIC_URL = 'static/' and my template has: <!doctype html> {% load static %} <img src="{% static 'e.png'%}"> -
Django serializer very slow takes 8-10 seconds
I'm trying to develop dashboard API which requires fetching data from several tables for each product, lets I have 5 products I need to query 5-6 other tables to get the data for each table. Those 5 tables are very large table in future it might even reach to 1-2M records.(they are added every minute) I used prefetch related for the backward relation - I agree query time gets reduced a lot, but serializer gets very slow no matter how many fields I have. For dashboard I need to pick the latest record related to entities I'm displaying in dashboars. My Model Class Product(): name Slug Class ProductViewedByUser()// need last user who viewed the product Users Time Similar to ProductViewedByUser I have 5-6 tables from which I need to fetch latest record. I tried Prefetch Related query time is 115 ms for 3 products and nearly 500000 cached rows. When I pass this to serializer no matter what fields are there even with one CharField- time goes to 3seconds When I have multiple fields time goes to 10 seconds I'm expecting serialization to be fast as possible. Is it good idea to create one another table for storing latest records … -
A site on cPanel loaded perfectly, but when I downloaded the latest update to the site, this error appears .How to solve this problem؟
A site on cPanel loaded perfectly, but when I downloaded the latest update to the site, this error appears .How to solve this problem؟ Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at webmaster@localhost to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. -
Tweepy .get_me() error when using OAuth 2.0 User Auth flow with PKCE
Trying to get an authenticated user's Twitter ID and Twitter username via the Tweepy package. With authentication through the OAuth 2.0 flow (using a Django view). I've been able to create an instance of the Tweepy pkg's Client class using the OAuth 2.0 User Context flow, but when I use the .get_me() method on it, I get an error. The error is: "Consumer key must be string or bytes, not NoneType" The error would suggest that the method wants a Consumer Key, but in this case, I initialized the Class using the OAuth 2.0 User Context flow with PKCE, which doesn't require it. I created the instance with the snippet below (in the same way it's specified in the Tweepy docs here): import tweepy oauth2_user_handler = tweepy.OAuth2UserHandler( client_id="Client ID here", redirect_uri="Callback / Redirect URI / URL here", scope=["follows.read", "users.read", "tweet.read", "offline.access"], client_secret="Client Secret here" ) access_token = oauth2_user_handler.fetch_token( "Authorization Response URL here" ) client = tweepy.Client("Access Token here") The Client object doesn't appear to be the issue, as I'm getting redirected to Twitter to authorize and redirected back via the callback as it should work. The Consumer Key is a requirement of the OAuth 1.0 User Context flow, but that's … -
CSS Grid with Django
I am studying Django and I have a question regarding CSS Grids and Dynamic content. In the HTML code below I am trying to get from my views.py file the values of a dictionary. # From 'views.py' def index(request): values = { 1: 'Value 1', 2: 'Value 2', 3: 'Value 3' } past_values = { 'past_values': experiences } This is part of the HTML I was talking about: <!-- START PORTFOLIO --> <section id="portfolio" class="tm-portfolio"> <div class="container"> <div class="row"> <div class="col-md-12 wow bounce"> <div class="title"> <h2 class="tm-portfolio-title">My <strong>Past Values</strong></h2> </div> <!-- START ISO SECTION --> <div class="iso-section"> <ul class="filter-wrapper clearfix"> <li><a href="#" class="opc-main-bg selected" data-filter="*">All</a></li> <li><a href="#" class="opc-main-bg" data-filter=".html">Cat 1</a></li> <li><a href="#" class="opc-main-bg" data-filter=".photoshop">Cat 2</a></li> <li><a href="#" class="opc-main-bg" data-filter=".wordpress">Cat 3</a></li> <li><a href="#" class="opc-main-bg" data-filter=".mobile">Cat 4</a></li> </ul> <div class="iso-box-section"> {% for key, value in past_values.items %} <div class="iso-box-wrapper col4-iso-box"> <div class="iso-box html photoshop wordpress mobile col-md-3 col-sm-3 col-xs-12"> <div class="portfolio-thumb"> <img src="{% static 'images/portfolio-img1.jpg' %}" class="fluid-img" alt="portfolio img"> <div class="portfolio-overlay"> <h3 class="portfolio-item-title">{{value}}</h3> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonumm.</p> </div> </div> </div> </div> {% endfor %} </div> </div> </div> </div> </div> </section> <!-- END PORTFOLIO --> Here is the related CSS: /* START PORTFOLIO */ .tm-portfolio { … -
Apache webserver with app using GDAL not working on windows
I am trying to deploy a django project using POSTGIS on my windows 11 PC with Apache 2.4. The web page is working as long as I am not using 'django.contrib.gis'. When I add 'django.contrib.gis' to my INSTALLED_APPS and define GDAL_LIBRARY_PATH to point to my gdal installation things stop working. Specifically, trying to access the web app ends up in infinitely loading the page. Weird enough there are no errors in the apache error log. The apache service starts fine. As far as I can see gdal install is correct as the app is working fine on the same machine with the same python environment with the django development server. Actually, I have the same issue with other python libraries that need some dlls, like opencv. So my guess is that it is a security related issue, but I do not find any clues on how to solve it. Any ideas? I tried also to grant rights to the directory where gdal is install in apache conf. But no luck. -
in Django FormView I cant see the form
I have some issues where I can see the form nor the parameter this is my code Here I pass an ID from the previous selection as parameter URL file path('make_payment/<int:jugador_id>', views.Payment_ViewMix.as_view(), name = "make_payment"), view fiel: here I try to catch the parameter and also get the current time and get the form, when I delete the get_context_data function, the form is shown correctly when I add it again nothing sows and the ID is never shown in the HTTP template class Payment_ViewMix(FormView): form_class = PagoJugadorForm template_name = "includes/make_payment.html" context_object_name = 'payment' def get_context_data(self, **kwargs): idjug = self.kwargs idjugador = int(idjug['jugador_id']) print(idjugador) context = { 'idjugador':idjugador, } return context def form_valid(self, form): context = self.get_context_data(context) print(context) fecha_pago = datetime.datetime.now() print(fecha_pago) jugador_id = context['idjugador'] fecha_pago = fecha_pago #jugador_id.instance = self.object monto = form.cleaned_data['monto'] notas = form.cleaned_data['notas'] id_categoriapago = form.cleaned_data['id_categoriapago'] id_group_categoria =form.cleaned_data['id_group_categoria'] JugadorPagos.objects.create( idjugador = jugador_id, fecha_pago = fecha_pago, monto = monto, notas = notas, id_categoriapago = id_categoriapago, id_group_categoria = id_group_categoria, ) return super(Payment_ViewMix, self).form_valid(form) form file : here in the form I do not show the ID because is the one that I want to get from the parameter given and the current date is the one that I would …