Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django site not loading using Apache2 and mod_wsgi
Trying to deploy a Django site using Apache and wsgi on an AWS EC2 instance. When running the site using python manage.py runserver 0.0.0.0:8000 everything works perfectly when connecting via the elastic ip. I was under the impression that using Apache and wsgi the site would automatically start and be kept up even after closing the shell. I may be wrong about that though so please correct me if so. I followed the official documentation for setting up the files, and also checked out some other tutorials to try and get it to show but nothing. They all say once the 000-default.conf file is setup and Apache is restarted, to check the site IP, but mine never loads the connection eventually times out. my file structure is: home └── ubuntu/ └── django/ └── portfolio/ ├── portfolio/ │ ├── base │ ├── portfolio/ │ │ ├── settings.py │ │ └── wsgi.py │ ├── static/ │ ├── templates/ │ └── manage.py └── venv/ └── lib/ └── python3.8/ └── site-packages/ my Apache 000-default.conf is <VirtualHost *:80> ServerAdmin YourEmail@yourProvider.com DocumentRoot /home/ubuntu/django/portfolio/portfolio ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/django/portfolio/portfolio/static <Directory /home/ubuntu/django/portfolio/portfolio/static> Require all granted </Directory> <Directory /home/ubuntu/django/portfolio/portfolio/portfolio> <Files wsgi.py> Require all granted </Files> </Directory> … -
Why does Django not find a field added to the AbstractBaseUser
I've inherited from the AbstractBaseUser as follows: class User(AbstractBaseUser): """ Main User model, inherits from AbstractBaseUser """ # Meta email = models.EmailField(verbose_name='email', max_length=60, unique=True) username = models.CharField(max_length=40, unique=True) # equals to email date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) employee_of = models.OneToOneField(Customer, on_delete=models.SET_NULL, null=True) So each User is linked to one and only one Customer. Now within a view I want to access the instance of the current logged in user within the request object and get the employee_of value to get a queryset that contains all users of that customer. def render_employees(request): """ Renders the employees page of the dashboard :param request: :return: """ # Return the value for the current site for css specific classes dashboard_site = 'employees' # Query the employees qs_employees = User.objects.filter(employee_of=request.user.employee_of) # doesn't find field ... However the filter doesn't work because request.user.employ_of doesn't seem to return anything. My IDE even suggests e.g. username, date_joined etc. but not employee_of. Why's that? class Customer(models.Model): """ A table that stores static data about a customer, usually a legal company """ legal_name = models.CharField(max_length=50) street = models.CharField(max_length=30) street_number = models.CharField(max_length=3) def __str__(self): return self.legal_name -
Can't save InMemoryUploadedFile to S3 in Django Admin
I'm using the django-storage package, and trying to upload multiple images at once. So I overwritten the add_view and save_model methods in ModelAdmin, in order to remove the original image field and use a custom one (with a multiple flag in the input tag) given in the template HTML: MODELS.PY class Media(AbstractCreatedUpdatedDateMixin): uuid = models.UUIDField(unique=True, default=uuid4, editable=False, db_index=True) user = models.ForeignKey(User, related_name="uploaded_media", on_delete=models.CASCADE) title = models.CharField(max_length=255) image = models.ImageField(upload_to=uuid_directory_path) ADMIN.PY class MediaModelAdmin(admin.ModelAdmin): def add_view(self, request, form_url='', extra_context=None): self.exclude = ('image', "is_approved") extra_context = extra_context or {} extra_context['show_save_and_add_another'] = False extra_context['show_save_and_continue'] = False return super().add_view(request, form_url, extra_context) def save_model(self, request, obj, form, change): for file in request.FILES.values(): obj.user = User.objects.filter(id=request.POST.get("user")).first() obj.title = request.POST.get("title") obj.image.save(file.name, file.file) obj.save() It uploads correctly to S3, but it doesn't save the instance and throws this error: TypeError at /admin/media/media/add/ expected string or bytes-like object I'm not sure what is wrong here, maybe the fact that the upload is not done yet so the DB transaction is rolled back, but I can't figure out what do to. -
Python / Django Static files not load when debug is False
I have Django project and I deployed this project on Web Host. But I have a problem. Static files do not load when I set the debug variable in the settings file to False. Host control panel: cPanel Web Server: LiteSpeed -
Openpyxl how scroll to cell A1
I have a .xlsx file in a DJANGO project used as a template to the user download insert some data upload and populate some stuffs in the system, so far so good. Sometimes a dev need edit this file, change some description or add a value, anything. Some of then finish the edition, for all sheets set the A3 cell as active scroll to top and for the last select the "initial" sheet, but must of the developers forget this step and i'm trying to create some thing like a set_initial_state. What i have so far: def set_initial_state(workbook: Workbook) -> Workbook: # Set A3 cell as active [working well] for ws in workbook: for selection in worksheet.sheet_view.selection: selection.activeCell = "A3" selection.sqref = "A3" # Set the initial worksheet [working well] workbook.active = workbook["@Instructions"] # set the scroll position to A1 [Not working] for ws in workbook.worksheets: ws.sheet_view.topLeftCell = "A1" OBS: All the worksheets have some column or row frozen. -
splitting all the functions in Django rest framework to separate fils
I am creating an app and it has alot of serializers and views at first I was working in the default way but later I have created a folder name (seriliazers then more folders name (auth,Profile,Payment) and serializers related to each part is inside these folders, I did same with views folder is it a good way to work or not, found out a lot of critics on not using views.py file. -
Accessing result of Django Celery tasks whenever they finish
When a user clicks a button on my webpage 2 celery tasks are started (using RabbitMQ): views.py def btn_clicked(request): task1 = task1.delay() task2 = task2.delay() tasks.py @shared_task def task1: #do something return result1 @shared_task def task2: #do something return result2 I want to use htmx to update the html on my webpage when the results of task1 and task2 are available (as they come in, task1 may be quicker than task2). The tasks will take ~30 seconds. In order to pass the info to the html I need to access the result as soon as it's available but I'm not sure how. From what I've read elsewhere it may be through using AsyncResult but I'm not sure on this - and if it is I'm not sure how I access the id of each task to pass it into AsyncResult (I've tried task.id without success) -
Boostrap.min.css not loading in django app after deploying to Azure Cloud
My Site is running perfectly running on localhost but when i uploaded my code to Azure cloud it doesn't loading boostrap.min.css due to which its theme is not loading on local host: Local host image on Azure site Azure Screenshoy why it is not fetching the boostrap themes on site -
Python/Django Test Framework: Response code was 200 (expected 200)
So I am using Django's test framework, and in this case im testing update_password_view that I ve created on top of the built-in PasswordChangeForm. Could someone please help me with the error from below? After I run tests I get the following error: AssertionError: [] is not true : Response didn't redirect as expected: Response code was 200(expected 200) Here is the code: #views.py class UpdatePassword(PasswordChangeView): form_class = PasswordChangeForm success_url = reverse_lazy('posts:home') template_name = 'accounts/password.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # get the number of unseen messages context['inbox_count'] = Message.objects.filter( ~Q(sender=self.request.user), Q(seen=False), (Q(chat__user1=self.request.user) |\ Q(chat__user2=self.request.user))).count() return context #tests.py def test_update_password_view(self): credentials = { 'old_password': '123secret', 'password1': '321secret', 'password2': '321secret', } response = self.client.post('http://127.0.0.1:8000/users/change-password/', credentials, follow=True) self.assertRedirects(response, '/posts/', status_code=200, target_status_code=200) -
Page not found (404) Request Method: GET
Request Method: GET Request URL: http://127.0.0.1:8000 Using the URLconf defined in DjangoAPI.urls, Django tried these URL patterns, in this order: admin/ ^ ^department$ ^ ^department/([0-9]+)$ ^ ^employee$ ^ ^employee/([0-9]+)$ ^ ^employee/savefile ^ ^Photos/(?P.*)$ The empty path didn't match any of these Yesterday the Django portion of the project was fine and now I'm getting this error message. I've tried adding /home/ at the end of 127.0.0.1:8000 and still getting the same thing. Any help would be greatly appreciated. -
Why does sql skip rows in my own django bulk create?
I have created a method to overwrite bulk_create for certain queries, so that I get an pk returned from my MYSQL database. def dict_fetch_all(cursor): """Return all rows from a cursor as a dict""" columns = [col[0] for col in cursor.description] return [ dict(zip(columns, row)) for row in cursor.fetchall() ] class BulkQueryManager(models.Manager): def bulk_create_return_with_id(self, objs, batch_size=2000): self._for_write = True fields = [f for f in self.model._meta.concrete_fields if not isinstance(f, AutoField)] created_objs = [] with transaction.atomic(using=self.db): with connections[self.db].cursor() as cursor: for item in [objs[i:i + batch_size] for i in range(0, len(objs), batch_size)]: query = sql.InsertQuery(self.model) query.insert_values(fields, item) for raw_sql, params in query.get_compiler(using=self.db).as_sql(): cursor.execute(raw_sql, params) print('last row id: ', cursor.lastrowid, 'count: ', cursor.rowcount) raw = "SELECT * FROM %s WHERE id >= %s ORDER BY id DESC LIMIT %s" % ( self.model._meta.db_table, cursor.lastrowid, cursor.rowcount ) print(raw) cursor.execute(raw) created_objs.extend(dict_fetch_all(cursor)) print(created_objs) post_save.send(item.__class__, instance=item, created=True) return created_objs However, created_objs isn't always the same as my input objs. Very rarely the wrong objects get returned. My cursor.lastrowid is always correct, but it seems like the first few rows sometimes get skipped. For example: print output: last row id: 155407411 count: 22 print output: SELECT * FROM product_research_offer WHERE id >= 155407411 ORDER BY id DESC LIMIT 22 … -
pip not found on virtual environment
I created a virtual environment which called "hekim_venv". But when I try the install django in it, it gives "pip not found error". When I check the pip location there are no pip. When I check pip3 it indicates homebrew location. So there are no pip for venv's. How can I install libraries in virtual env? I can not understand and figure out the configuration. (hekim_venv) cucal@CANER-MacBook-Air dentist_project % pip install django zsh: command not found: pip (hekim_venv) cucal@CANER-MacBook-Air dentist_project % pip3 install django DEPRECATION: Configuring installation scheme with distutils config files is deprecated and will no longer work in the near future. If you are using a Homebrew or Linuxbrew Python, please see discussion at https://github.com/Homebrew/homebrew-core/issues/76621 Requirement already satisfied: django in /opt/homebrew/lib/python3.9/site-packages (4.0.2) Requirement already satisfied: asgiref<4,>=3.4.1 in /opt/homebrew/lib/python3.9/site-packages (from django) (3.5.0) Requirement already satisfied: sqlparse>=0.2.2 in /opt/homebrew/lib/python3.9/site-packages (from django) (0.4.2) DEPRECATION: Configuring installation scheme with distutils config files is deprecated and will no longer work in the near future. If you are using a Homebrew or Linuxbrew Python, please see discussion at https://github.com/Homebrew/homebrew-core/issues/76621 (hekim_venv) cucal@CANER-MacBook-Air dentist_project % which pip pip not found (hekim_venv) cucal@CANER-MacBook-Air dentist_project % which pip3 /opt/homebrew/bin/pip3 -
permission() for permission in self.permission_classes -> TypeError: 'str' object is not callable
does anybody know why do I get this error? I set default permission to IsAuthenticated. Only register has AllowAny, to allow users to register. Not Found: / [21/Feb/2022 21:43:06] "GET / HTTP/1.1" 404 2278 Not Found: /account [21/Feb/2022 21:43:11] "GET /account HTTP/1.1" 404 2317 Internal Server Error: /account/register Traceback (most recent call last): \venv\lib\site-packages\rest_framework\views.py", line 278, in <listcomp> return [permission() for permission in self.permission_classes] TypeError: 'str' object is not callable [21/Feb/2022 21:43:14] "GET /account/register HTTP/1.1" 500 106055 My views.py class: @api_view(['POST']) @permission_classes(['AllowAny']) def registration_view(request): serializer = RegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): account = serializer.save() data['response'] = "successfully registered a new user." data['email'] = account.email data['username'] = account.username else: data = serializer.errors return Response(data) I am using SessionAuthentication and IsAuthenticated as default authentication and permission in my settings.py file. CustomUser model just inherits from AbstractUser. No addition. -
Django channels remote user auth
Is it possible to pass remote user over reverse proxy (like in Apache server) to Django channels and use the user? -
How can i make this on django? (Listings main objects and subjects)
Firstly i wanna give good title for my question but i dont know how to describe and sorry for bad question title... So... First picture In vertical picture i wrote 3 symptoms and four remedy for each symptoms. And each remedy has a point for every different symptoms. Forexample, silica get 2 points for cough but when symptom is headache silica gets 3 points. Second Picture I wanna make a webpage like this second image. On the left frame i wanna listing the symptoms. And on the other side i wanna list all remedies. Remedies must be listed for the higher points. Forexample, Silica gets 6 points and silica is the remedy for all symptoms so therefore i wrote 3/3. Natmur gets 5 points and natmur is remedy for 2/3 symptoms. I wonder how can i make this. I think i must make a model but this subject is a little bit complicated for me. I need a vision. -
How can I fix this issue on my social app? [duplicate]
I deployed my django app on Heroku using sqlite as database, I migrated. And still haven't seen my old data content on the site, I even had to create a new superuser to login. Now I said let's forget about the old db and posted some new content to make the site look alive, posted a couple of pics but after some time they disappear, just a white thumbnail on the post. The users I created are still there, just the pics they look broken or something.. Anyway I could fix this or even better find a way to use the old existent database. I still see it on my heroku console but not on the site even though I migrated. Link of the site: https://network50web.herokuapp.com/ Settings: """ Django settings for project4 project. Generated by 'django-admin startproject' using Django 3.0.2. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os import django_heroku from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used … -
Pythonanywhere ModuleNotFoundError No module named mysite
Hi I've been continuing to get this error on Pythonanywhere trying to run a Django project. Error is with the WSGI file but not sure what I'm doing wrong. Here is my WSGI file currently: import os import sys ## assuming your django settings file is at '/home/cole3237/mysite/mysite/settings.py' ## and your manage.py is is at '/home/cole3237/mysite/manage.py' path = '/home/cole3237/wintergarden_django' if path not in sys.path: sys.path.append(path) # os.environ['DJANGO_SETTINGS_MODULE'] = 'wintergarden_django.settings' # ## then: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() The name of the root folder is correct (which seemed to be the problem for anyone whose had a similar problem) so not sure what the issue could be? Thank you for any help -
How to display Json format on Django?
I am building an application with Django. I want to display only the field without the number and data type as shown in the picture. I use data from CSV. Maybe I think this needs to be converted into Json. But I don't understand. This is my code: views.py def get_rbook(request, bookid): df_book = pd.read_csv(book_path) book_details = df_book[df_book['book_id'] == bookid] context = { 'book': book_details, } return render(request, "resources/read.html", context) HTML <div class="container-fluid"> <div class="container-fluid"> <div class="row"> <div class="col-sm-12"> <div class="row"> <div class="col-sm-2"> <div class="grid-item"> <div class="view-details" style="cursor:pointer"> <img id="product_image" class="lookInsideImg" src="{{ book.image_url }}"> </div> </div> </div> <div class="col-sm-10"> <div class="product-information"> <h4>{{ book.original_title }}</h4> <p style="margin: 0px">by <a style="font-weight:bold" href="#">{{ book.authors }}</a></p> <div class='rating'> </div> <article class="text-justify" style="margin-top:10px;"> {{ book.desc }} </article> </div> </div> </div> </div> </div> </div> </div> Thank you before! -
Django: how to include CSS once within an "included" template
With Django templates, once can either {% extend %} or {% include %} a template. I have a template that already extends another template, and then there are various optional bits of code in templates which get included to the extended template. Thing of these included files as "components" which get added to various templates. Now one of these inlcuded templates requires an external CSS file. Although one could add the included file to all the templates which include it, I think logically it makes more sense that code snippet injects its own dependencies automatically, or else soft dependencies in far away files tends to get broken. i.e. the included template should declate its needs for the CSS file. If I write a custom template tag to achieve this, as far as I understand, by the time its gets to this template tag in the included template, it can't go back to the document head and add a line to the rendering of the head to add a <style> tag. So how can one achieve this? One could add the style tag in the component, but then the style tag is duplicated everytime there's an instance of the component, which … -
Powershell - How to get output from Python script program that's being run in Powershell and write it in a log file?
I'm looking to write the output that appears on the Powershell console of my Python script to the log file. How am I able to read it and write it to my log file? My powershell script: $LogFileTime = Get-Date -Format "yyyyMMdd_HHmmss" $LogFile = "D:\Project\_LOG\START_WEBSERVER_"+$LogFileTime+".log" $CurrDatetime = Get-Date -Format "yyyy-MM-dd HH:mm:ss" $CurrDatetime+" | START WEBSERVER" | Add-Content -Path $LogFile D:\Project\Venv\Scripts\python.exe D:\Project\PowerShellScripts\manage.py runserver 0.0.0.0:80 > $LogFile 2>&1 $CurrDatetime = Get-Date -Format "yyyy-MM-dd HH:mm:ss" $CurrDatetime+" | STOP WEBSERVER" | Add-Content -Path $LogFile My Python script: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Project.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise 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?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() -
Getting user`s UUID from django server
I have a django server with an admin panel. Different users make changes there and this is saved via auditlog in the database and displayed in the "history". But there are situations when a user enters under the account of another user and makes changes on his behalf. In order to identify from which device this or that change was made, it was a nice decision to also record data about the IP of the user from whom the change was made, and his unique device number. By overloading several methods in the "AuditlogMiddleware" class, I got the desired result via "uuid.UUID(int=uuid.getnode())". (Tested locally, because the prod server is heavily loaded and there is no way to do test committees) from __future__ import unicode_literals import threading import time from auditlog.middleware import AuditlogMiddleware threadlocal = threading.local() class ExtendedAuditlogMiddleware(AuditlogMiddleware): def process_request(self, request): threadlocal.auditlog = { 'signal_duid': (self.__class__, time.time()), 'remote_addr': request.META.get('REMOTE_ADDR'), } super(ExtendedAuditlogMiddleware, self).process_request(request) **#changes here import uuid threadlocal.auditlog['additional_data'] = str(uuid.UUID(int=uuid.getnode()))+" | "+request.META["USERNAME"]** # @staticmethod def set_actor(self, user, sender, instance, signal_duid, **kwargs): super(ExtendedAuditlogMiddleware, self).set_actor(user, sender, instance, signal_duid, **kwargs) **#changes here instance.additional_data = threadlocal.auditlog['additional_data']** But the problem is that I think I get the UUID not of the user, but of the server, because … -
UUIDs with django and mssql
I have a mssql schema with the django ORM / pymssql extension. I have some classes build via the inspectdb function. A lot of the Primarykeys in the tables are UUID fields / mssql uniqueidentifier, which the ORM inspected as CharFields with length 36. I am concerned now with possible duplicates for the primary keys since the tables are growing very fast. The tables have a default constraint for any new primary key on the database site. So basically I have two (different) sources of UUID generation (the database server and the application server) How is it possible to insert via the ORM from django performantly? Am I save with generating the UUIDs via pythons uuid module or do I have to ask the database everytime for a new UUID before creating a object with django? -
How to have a choice depending on the instance of a model in Django admin
I am stuck since quiet a few days now. I have a level 1 model, which is in 0 to Many relation with a level 2 model, which is in a 0 to Many relation with a level 3 model: class Level1(models.Model): title = models.CharField(max_length=30) # some fields class Level2(models.Model) title = models.CharField(max_length=30) # some Fields level1 = models.ForeignKey(Level1, on_delete=models.CASCADE) class Level3(models.Model) title = models.CharField(max_length=30) # some Fields level2 = models.ForeignKey(Level2, on_delete=models.CASCADE) choices = # I get stuck here # The field 'choices' must point to one level2 instance proposed through a kind of Choices form field, but maybe I am wrong. By pointing, I think it can be as well a relation or just storing the id of the Model instance. The choices must be limited. Here an example would be the simplier way to explain : Level 1 : objects : A, B Level 2 : objects : A1, A2, A3 : (Parent A); B1, B2 : (Parent B) Level 3 : object A10 : (parent A1) For A10 choices must be limited to A1, A2, A3. And that's it. Thank you in advance for your help. -
Get field from cursor select (mssql) in my template
I have this VIEW below: from django.shortcuts import render from django.db import connections def IndexView(request): con_totvs = connections['totvs'].cursor() with con_totvs as cursor: cursor.execute("SELECT A1_NOME, A1_CGC FROM SA1010 WHERE D_E_L_E_T_ <> '*' ORDER BY A1_NOME") select = cursor.fetchall() # bla bla bla context = {} cursor.close () con_totvs.close () return render(request, "home.html", context) Just like I use when creating models, in my template id like to do something like: {% for i in SELECT %} {{ i.A1_NOME }} {% endfor %} Is this possible? Ive been searching but i failed it -
Convert template html in django to pdf and download it
How I can create a button on my web page using Django to convert the page to PDF and download it ?