Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku can't find styles.css
Trying to deploy a Django app to Heroku for the first time. When I view the app using Django, everything shows up correctly, but when I run it on Heroku, pieces of the UI are missing. I'm not too familiar with the frontend - this was a group project and I was working on backend - and my team isn't willing to help with deployment, so I'm unable to diagnose any frontend issues. Looking at the Heroku logs, I get this error "Not Found: /static/styles.css" - but there is a styles.css file under static. Does anyone know where the root problem might lie? Under settings.py I have specified this STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'staticfiles')] All functionalities work as expected, I think it has something to do with the base.html file - but this is just a stab in the dark. An example of what it's meant to look like, compared to what it looks like on Heroku. -
Django path not matching with urlpatterns in urls.py
Guys I am not a web developer, I have been learning django for a couple of hours now for my father's small business website and I am hitting a silly error for hours now. the name of the project is mysite and mysite urls.py looks like this from django.contrib import admin from django.urls import include, path urlpatterns = [ path("", include("index.urls")), path("about/", include("about_page.urls")), path("polls/", include("polls.urls")), path("admin/", admin.site.urls), ] mysite's settings.py also includes the correct AppConfig for the app. about_page included. INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'index.apps.IndexConfig', 'about_page.apps.AboutPageConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] about_page's views.py is attached_below from django.shortcuts import render from django.http import HttpResponse from django.template import loader from django.http import Http404 # Create your views here. # return HttpResponse("website under construction !!!") def about_func(request): template = loader.get_template("about/about_page.html") context = { "about":"about_us", } return HttpResponse(template.render(context, request)) about_page's urls.py: from django.urls import path from . import views urlpatterns = [ path("about/", views.about_func, name="about_page"), ] polls and index apps have exact same pattern, i simply don't know why i cannot display about page. -
deploy project on my local machine with Apache
I built a website with Django, installed Apache and made all the adjustments. In addition, I bought a domain from GoDaddy for the site. I want to deploy the site on my computer. The problem is when I try to access the site via the internet I get to a page from GoDaddy with my domain. The steps I did: Add A record with my local IP DNS on GoDaddy Installing wsgi Updating the settings.py page with the new addresses. Update httpd-vhosts Update httpd.conf Resetting the Apache server open the ports in my firewall *I bought the domain two days ago. httpd.conf: ServerName DomainName LoadFile path LoadModule wsgi_module path WSGIPythonHome path httpd-vhosts: ServerName DomainName <VirtualHost *:80> ServerName DomainName ServerAlias www.DomainName WSGIScriptAlias / "path" ErrorLog "logs/DomainName-error.log" CustomLog "logs/DomainName-access.log" common <Directory "path"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "path" <Directory "path"> Require all granted </Directory> -
Please i want to generate username from user email in django that can be used in the url
I'm encountering an issue with populating the display_username field in my custom Django user model. Which i want to use as the username handle. My Model: class User(AbstractUser): # First and last name do not cover name patterns around the globe name = CharField(_("Name of User"), blank=True, max_length=255) first_name = None # type: ignore last_name = None # type: ignore display_username = CharField(_("Display Username"), blank=True, max_length=255) email = EmailField(_("email address"), unique=True) username = None # type: ignore USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self) -> str: """Get URL for user's detail view. Returns: str: URL for user detail. """ return reverse("users:detail", kwargs={"pk": self.id}) My Manager: class UserManager(DjangoUserManager): """Custom manager for the User model.""" # def _create_user(self, email: str, password: str | None, **extra_fields): # """ # Create and save a user with the given email and password. # """ # if not email: # raise ValueError("The given email must be set") # email = self.normalize_email(email) # user = self.model(email=email, **extra_fields) # user.password = make_password(password) # user.save(using=self._db) # return user # def _create_user(self, email, password=None, **extra_fields): # if not email: # raise ValueError("The given email must be set") # email = self.normalize_email(email) # base_username = email.split('@')[0] # … -
What would be a better solution for storing data in a Django model?
Could you please give me a piece of advice? Context: I have a Django project in which each user stores many different variables linked to his profile. I created a model called Snapshot, that has a foreign key of user. Single user can have multiple Snapshots linked to his User instance, but only the latest one (by its ID, pk) is editable. Any other ones might be used to revert to past setup only. Typical use case: User modifies his setup stored in his latest Snapshot using API endpoints. Each function that an endpoint call has to query the latest Snapshot owned by user that called the function. Then it modifies some of the variables in the Snapshot and saves it. Once everything's done user approves the setup and the Snapshot is being duplicated. Now the new instance becomes the latest. Question: Is it a good idea to query the latest Snapshot this many times in each function? Wouldn't it be a good idea to link the latest Snapshot one-to-one with User, so that it's always available as User.latest_snapshot? This latest_snapshot would be automatically re-linked to User once user approves setup, thus creating a new Snapshot. -
Django tenants can't delete record from a shared model that has FK in tenant from public schema
I Have a custom user model shared between tenants and public HAS_MULTI_TYPE_TENANTS = True MULTI_TYPE_DATABASE_FIELD = 'type' TENANT_TYPES = { "public": { "APPS": [ 'django_tenants', 'clients', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'djoser', "corsheaders", 'accounts', ], "URLCONF": "server.urls_public", }, "menu": { "APPS": [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework.authtoken', 'accounts', 'products', ], "URLCONF": "server.urls_menu", }, "full-version": { "APPS": [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework.authtoken', 'accounts', 'products', 'order', ], "URLCONF": "server.urls_full", } } INSTALLED_APPS = [] for schema in TENANT_TYPES: INSTALLED_APPS += [app for app in TENANT_TYPES[schema] ["APPS"] if app not in INSTALLED_APPS] from the full-version order app, there is an FK to the user model that restrict me to delete any user from the public schema class Address(models.Model): user = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True) also, the issue appears in the menu type cuz the order models do not exist yet django.db.utils.ProgrammingError: relation "order_address" does not exist LINE 1: ...."user_type", "accounts_user"."phone_number" FROM "order_add... Is any work around or do I have to create an empty model for each type? -
How to clone github repository to azure blob
I'm trying to clone a github repository in my django application and write it to my server machine. And I have to serve that repository files to end users. I did it using below code "my implementation code"but "shutil.rmtree(repo_dir)" is taking very long time to remove existing repository files from my server machines. "Here is my implementation code" Please help and guide if there is any better way to do this. Thanks in Advance -
ploty theme change issue
I am using ploty py and django have two themes in my webapp dark and light. on light theme select graph is shown light theme and on dark theme select graphs are shown dark theme. the issue i am getting when one user change the theme it affect the other user graph theme when other user refresh or callback change. dark theme template import plotly.io as pio from plotly.graph_objs import Layout import plotly.graph_objects as go dark_template_layout = Layout( images=[ dict( source="/static/img/images/watermark/Anahit-SVG-LOGO-GreyScale-4.svg", name="Anahit", xref="paper", yref="paper", x=0.5, y=0.5, sizex=0.5, sizey=0.4, xanchor="center", yanchor="middle", layer="below", opacity=0.1, ) ], annotationdefaults={ "arrowcolor": "#f2f5fa", "arrowhead": 0, "arrowwidth": 1, }, autotypenumbers="strict", coloraxis={"colorbar": {"outlinewidth": 0, "ticks": ""}}, colorway=[ "#636efa", "#EF553B", "#00cc96", "#ab63fa", "#FFA15A", "#19d3f3", "#FF6692", "#B6E880", "#FF97FF", "#FECB52", ], font={ "family": "Mulish, sans-serif", "size": 16, "color": "#a9afc3", }, ### title ### title={ "font": { "family": "Poppins, sans-serif", "size": 15, "color": "white", }, ### control position of title # "y": 0.5, "x": 0.5, # "xanchor": "right", # "yanchor": "middle", }, hoverlabel={"align": "left"}, # Keep adding others as needed below hovermode="closest", mapbox={"style": "dark"}, **paper_bgcolor="#080a12",** **plot_bgcolor="#080a12",** shapedefaults={"line": {"color": "#a9afc3"}}, sliderdefaults={ "bgcolor": "#C8D4E3", "bordercolor": "rgb(17,17,17)", "borderwidth": 1, "tickwidth": 0, }, updatemenudefaults={"bgcolor": "#506784", "borderwidth": 0}, xaxis=dict( automargin=True, gridcolor="#283442", linecolor="#506784", title={"standoff": 15}, zerolinecolor="#283442", zerolinewidth=2, rangeselector={"activecolor": … -
Django: Make variable of child model depend on number of siblings associated with the same parent model
Assume I have two models, one modelling a Patient and another one modelling a tissue sample. To avoid confusing among lab members, instead of refering to the samples and the patients by a PK we transform the PK into a hashed string named displyed_id below. In the ideal case we would have a patient referred to as 'H6F4A' and the samples to be 'H6F4A-1', 'H6F4A-2', etc. (be labelled by a suffix of the sample number belonging to that patient). As a requirement we would need that if a sample is deleted that the sample numbering doesn't change for the suceeding samples (as the samples have physical barcodes printed onto them). As this is kind of hard to do (probably one would need a counter for every patient counting how many samples there are) we have opted to use the tissuesample pk as the suffix which is not really what we want as this is global and not per patient. Even if this new counter would not be a pk, combined with the hashed id of its parent e.g. sample 1 of patient 1 being 'H6F4A-1' it would need to be an injective mapping as staff will always refer to this … -
How to make on update record pass the signal in Django Model?
Hello I'm trying to make on update trigger in Django Model. Model.py class Item(models.Model): status_type = ( ('a','Active'), ('d','Deactive') ) code = models.CharField(max_length=100, null=True, blank=True, unique=True) name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) gsts = models.ForeignKey(Gst, on_delete=models.CASCADE) sgst = models.DecimalField(max_digits=10, decimal_places=2,null=True,blank=True) cgst = models.DecimalField(max_digits=10, decimal_places=2,null=True,blank=True) net_amount = models.DecimalField(max_digits=10, decimal_places=2,null=True,blank=True) status = models.CharField(max_length=1, choices=status_type, default = 'a') create_at = models.DateField(auto_now_add=True) update_at = models.DateField(auto_now=True) create_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name def ItemGenerator(sender, instance, created, *args, **kwargs): if created: id = instance query = Item.objects.get(id = int(id.id)) #gst calculation gst_cal = query.price * query.gsts.gst/100 #net amount calculation net_amounts = query.price + gst_cal #item number generate temp_count = Item.objects.all().count() no = str('ITEM') + '/' +str(temp_count) query = Item.objects.filter(id = id.id).update(code = str(no), cgst = round(gst_cal/2), sgst=round(gst_cal/2), net_amount = round(net_amounts)) When I'm insert to the data post_save signal is call and my price and gst calculation save into data base but problem is that when I'm update the record post_save signal is not working -
product.models.Products.DoesNotExist: Products matching query does not exist
product.models.Products.DoesNotExist: Products matching query does not exist. i have this problem in my site when i ran this url it show me this error please help in django and this is my views.py: class GetListProduct(APIView): def get(self, request): products = Products.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) class Getproduct(APIView): def get_object(self, brand): comment = Products.objects.get(brand=brand) serializer = ProductSerializer(comment) return Response(serializer.data) class Topsellsviews(APIView): def get(self, request): topsellsproduct = TopSells.objects.all() serializer = Topsellsserializer(topsellsproduct, many=True) return Response(serializer.data) class Getdetailproduct(APIView): def get(self, request, productid): detail = Products.objects.get(productid=productid) serializer = ProductSerializer(detail) return Response(serializer.data) and this is my url: from django.urls import path from.views import GetListProduct, Topsellsviews, Getdetailproduct, Getproduct urlpatterns = [ path('product/', GetListProduct.as_view()), path('topsells/', Topsellsviews.as_view()), path('product/<str:productid>/', Getdetailproduct.as_view()), path('product/<str:brand>/', Getproduct.as_view()), when i run /product/productid it worked but when i run /product/brand it not worked -
Using field in Trunc's kind property
I use PostgreSQL in my project and have three related models: class Timer(models.Model): start = models.DateTimeField() end = models.DateTimeField() task = models.ForeignKey( Task, models.CASCADE, related_name="timers", ) class Task(models.Model): name = models.CharField(max_length=64) wanted_duration = models.DurationField() frequency = models.ForeignKey( Frequency, models.CASCADE, related_name="tasks", ) class Frequency(models.Model): class TimeUnitChoices(models.TextChoices): DAY = "day", "day" WEEK = "week", "week" MONTH = "month", "month" QUARTER = "quarter", "quarter" YEAR = "year", "year" events_number = models.PositiveIntegerField() time_unit = models.CharField(max_length=32, choices=TimeUnitChoices.choices ) I want to get a start of timespan (day, week - a value of Frequency's time_unit) according to start date (field of Timer). I tried execute next code: task.timers.annotate(start_of=Trunc('start', kind='task__frequency__time_unit')) But Django doesn't accept field in kind argument of Trunc class. Error: psycopg.ProgrammingError: cannot adapt type 'F' using placeholder '%t' (format: TEXT) If I execute a following query in raw SQL: SELECT DATE_TRUNC(schedules_frequency.time_unit, timers_timer.start)::date as start_of FROM public.tasks_task INNER JOIN public.schedules_frequency ON tasks_task.frequency_id = schedules_frequency.id INNER JOIN public.timers_timer ON timers_timer.task_id = tasks_task.id; Everything works as wanted. Is there workaround without using raw SQL directly in the Django project? -
I/O Operation on closed file while using boto3 library for S3 file upload
Here is the traceback Internal Server Error: /api/v1/vehicle/ss-image-upload/ Traceback (most recent call last): File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\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\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\views\decorators\csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\vehicle_management\views.py", line 462, in patch i.save() File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\db\models\base.py", line 814, in save self.save_base( File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\db\models\base.py", line 877, in save_base updated = self._save_table( ^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\db\models\base.py", line 981, in _save_table values = [ ^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\db\models\base.py", line 985, in <listcomp> (getattr(self, f.attname) if raw else f.pre_save(self, False)), ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\db\models\fields\files.py", line 317, in pre_save file.save(file.name, file.file, save=False) File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\db\models\fields\files.py", line 93, in save self.name = self.storage.save(name, content, max_length=self.field.max_length) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\django\core\files\storage\base.py", line 38, in save name = self._save(name, content) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Guest Window\Desktop\vwfs-main-test-env-03082023\VWFS\venv\Lib\site-packages\storages\backends\s3boto3.py", line 446, in _save content.seek(0, os.SEEK_SET) ValueError: I/O … -
Error after removing slug from Page.promote_panels [Django Wagtail]
I am getting the following error after removing the 'slug' field from Page.promote_panels. I am using wagtail 5.1. KeyError at /admin/pages/add/blog/blogdetailpage/10/ "Key 'slug' not found in 'BlogDetailPageForm'. Choices are: category, classes, comment_notifications, container_size, containerized, content, expire_at, go_live_at, publish_at, search_description, seo_title, site, title." I am autogenerating the slug with the following piece of code, so I do not see a need for keeping it around. def save(self, request=None, *args, **kwargs): ... slug = slugify(f"{self.title}-{self.created_at}") if not self.slug or self.slug != slug: self.slug = slug if not self.publish_at: self.publish_at = datetime.now() super().save(*args, **kwargs) Is anyone familiar with doing something along the lines of this? -
Connect a Reddit app to Django and get permission to make a post
As a developer, I'd like to create a Reddit app and use it in Django. I'd like to get authorization to get the posts that the user has authorized. Imagine: A user clicks a button on my website and goes directly to the authorization screen and then he will be able to see his Reddit posts on my website -
How reset the user password in django
I have make canteen invoice making app and also admin can create user, update user and change the user's password But admin can't change user password form.py class PasswordChange_Form(UserCreationForm): class Meta: model = User fields = ["username","password1","password2"] widgets = { "username":forms.TextInput(attrs={'class':'form-control','placeholder':'Username', 'readonly':'readonly'}), "password1":forms.TextInput(attrs={'class':'form-control',"placeholder":"Password"}), "password2":forms.TextInput(attrs={'class':'form-control','placeholder':'Confirm Password'}), } View.py @login_required(login_url='/') def UserChangePassword(request,pk): id = User.objects.get(id = pk) user_id =request.user heading_name = "user" rights, main_heading, page_menu, form_btn_data = RightLoader(user_id, heading_name) try: auth_check = rights.form_btn.get(heading_name = heading_name, btn_type = "Password")# fetch form btn right if request.method == 'POST': form = PasswordChange_Form(request.POST, instance=id) try: if form.is_valid(): form.save() form = PasswordChange_Form(instance=id) #update_session_auth_hash(request, ) # Important! messages.success(request, 'Your password was successfully updated!') except: messages.error(request,str(form.errors)) else: form = PasswordChange_Form(instance=id) context = { 'form':form, 'page_menu':page_menu, 'main_heading':main_heading, 'btn_type':'fa fa-regular fa-plus', 'title':'iCateen | User', 'page_title':'Password Change', 'tree_title_1':'User', 'tree_url':'user', 'tree_title_2':'Add Form', 'view':'yes', } return render(request, 'base/user/change_password.html',context) except: return HttpResponseRedirect("/") Admin user can change user's password ? -
PyCharm does not accept my Python interpreter
I'm working with Python framework Django. I used Pycharm's terminal created virtual environment. {.\venv\Scripts\activate} It was created, and i run the server with this python manage.py runserver But the system responds: No Python at "C:\Users\User\AppData\Local\Programs\Python\Python38\python.exe But i installed and using Python 3.11.2 And i have file manage.py in project1 folder What should i do? The code PS D:\binkw32.dll\djangomorning> .\venv1\Scripts\activate (venv1) PS D:\binkw32.dll\djangomorning> cd project1 (venv1) PS D:\binkw32.dll\djangomorning\project1> python manage.py runserver No Python at 'C:\Users\User\AppData\Local\Programs\Python\Python38\python.exe' (venv1) PS D:\binkw32.dll\djangomorning\project1> -
Web and Daphne always restarting and not working properly
I've checked all I've seen, yet nothing is working. Please, I'm trying to make use of docker and all for the first time. This is my docker-compose.yml services: cache: image: redis:7.0.4 restart: always volumes: - ./data/cache:/data db: image: postgres:15.0 restart: always volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=samuel - POSTGRES_USER=samuel - POSTGRES_PASSWORD=*** web: build: . command: ["./wait-for-it.sh", "db:5432", "--", "uwsgi", "--ini", "/code/config/uwsgi/uwsgi.ini"] restart: always volumes: - .:/code environment: - DJANGO_SETTINGS_MODULE=chollosite.settings.prod - POSTGRES_DB=samuel - POSTGRES_USER=samuel - POSTGRES_PASSWORD=samuel101 depends_on: - db - cache daphne: build: . working_dir: /code/chollosite/ command: ["../wait-for-it.sh", "db:5432", "--", "daphne", "-u", "/code/chollosite/daphne.sock", "chollosite.asgi:application"] restart: always volumes: - .:/code environment: - DJANGO_SETTINGS_MODULE=chollosite.settings.prod - POSTGRES_DB=samuel - POSTGRES_USER=samuel - POSTGRES_PASSWORD=samuel101 depends_on: - db - cache nginx: image: nginx:1.23.1 restart: always volumes: - ./config/nginx:/etc/nginx/templates - .:/code ports: - "80:80" - "443:443" this is my base.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'pex0v$*b!kjl-bk2p%1y8rf!&jh+bqa!9t5e4@xnac-(nbi2wc' # Application definition INSTALLED_APPS = [ 'chollo_main.apps.CholloMainConfig', 'chollo_cart.apps.CholloCartConfig', 'orders.apps.OrderConfig', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.postgres', 'channels', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', … -
Possible security risks for the following form submission in Django
I am trying to create the page for a livetime chat app using Django and some Ajax. I have always used django forms, since it is more secure and clean if you are not very familiar with javascript. The below html and views.py don't use django forms, but instead go with the traditional method of using javascript. However, I am concerned that there might be security leaks with this following form, which I copied from another website. I believe I added the csrf token correctly, but is there anything else I need to consider? Thank you, and please leave any comments. <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script> </head> <body> <h2>{{room}} - DjChat</h2> <div id="display"> </div> <script> $(document).ready(function(){ setInterval(function(){ $.ajax({ type: 'GET', url : "/getMessages/{{room}}/", success: function(response){ console.log(response); $("#display").empty(); for (var key in response.messages) { var temp="<div class='container darker'><b>"+response.messages[key].user+"</b><p>"+response.messages[key].value+"</p><span class='time-left'>"+response.messages[key].date+"</span></div>"; $("#display").append(temp); } }, error: function(response){ alert('An error occured') } }); },1000); }) </script> <div class="container"> <form id="post-form"> {% csrf_token %} <input type="hidden" name="username" id="username" value="{{username}}"/> <input type="hidden" name="room_id" id="room_id" value="{{room_details.id}}"/> <input type="text" name="message" id="message" width="100px" /> <input type="submit" value="Send"> </form> </div> </body> <script type="text/javascript"> $(document).on('submit','#post-form',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/send', data:{ username:$('#username').val(), room_id:$('#room_id').val(), message:$('#message').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, … -
Django daphne service service is not working while deploying on aws ec2 an error Requested setting INSTALLED_APPS, but settings are not configured
Aug 06 11:11:00 ip-172-31-12-99 python[92893]: File "/home/ubuntu/nextshelters/env/lib/python3.10/site-packages/django/conf/init.py", line 72, in _setup Aug 06 11:11:00 ip-172-31-12-99 python[92893]: raise ImproperlyConfigured( Aug 06 11:11:00 ip-172-31-12-99 python[92893]: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJ> Aug 06 11:11:00 ip-172-31-12-99 systemd[1]: daphne.service: Main process exited, code=exited, status=1/FAILURE Aug 06 11:11:00 ip-172-31-12-99 systemd[1]: daphne.service: Failed with result 'exit-code'. Aug 06 11:11:00 ip-172-31-12-99 systemd[1]: daphne.service: Scheduled restart job, restart counter is at 1. Aug 06 11:11:00 ip-172-31-12-99 systemd[1]: Stopped WebSocket Daphne Service. this is the error coming when i am trying to do this sudo journalctl -u daphne.service here is m asgi.py file import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Renter.settings') django.setup() from django.conf import settings settings.configure() from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter, get_default_application from django.core.asgi import get_asgi_application from django.urls import path from home.consumers import ChatConsumer, NotificationsConsumer, TenantsConsumer application = get_asgi_application() application = ProtocolTypeRouter( { "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( [ path("chat/<room_code>", ChatConsumer.as_asgi()), path("view_messages", NotificationsConsumer.as_asgi()), path("dashboard/tenant_details/<tenant_uid>", TenantsConsumer.as_asgi()) ] ) ), } ) -
Having problems with message tags
*trying to create dynamic responses depending on user input but no alert button even appears. but when i get rid of {% for message in messages%} an empty alert button appears. ** here are sections of the code views.py file from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib import messages from django.contrib.auth import authenticate, login, logout def signup(request): if request.method == "POST": username = request.POST.get('username') email = request.POST.get('email') pass1 = request.POST.get('pass1') pass2 = request.POST.get('pass2') if pass1 != pass2: messages.info(request, "Password is not matching") return redirect('/authapp/signup/') try: if User.odjects.get(username=get_email): messages.warning(request, 'User with email already exist') return redirect('/authapp/signup/') except Exception as identifier: pass myuser = User.objects.create_user(username, email, pass1) myuser.save() messages.success(request, "Your Account has been successfully created, Login") return redirect('/authapp/signin/') return render(request, 'authapp/signup.html') signup.html {% for message in messages %} <div class="alert alert-{{message.tags}} alert-dismissible fade show" role="alert"> <strong> {{message}} </strong> <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endfor %} settings.py MESSAGE_TAGS = { messages.ERROR:'alert-info' } -
how to access MsSql Database from Cpanel
i am using python django project hosted in c panel. Database used is MsSql but not Supporting. try to add MsSql databse in CPanel but got error- MsSql is not supported.how to add mssql databasein cpanel with free of cost -
How to get full history executed function inside parrent function in Python / Django
I have function like this def test_func_1(angka): angka = angka + 3 result = test_func_2(angka) return result def test_func_2(angka): angka = angka + 5 return test_func_3(angka) def test_func_3(angka): angka = angka * 2 return angka def wrapper_func(): return test_func_1(3) When I call wrapper_func() I want to have history function that executed like this : wrapper_func() test_func_1(3) test_func_2(angka) test_func_3(angka) is that possible ? I know it's possible if we put trace_back.print_stack() like this Getting a python traceback without an exception But what if I don't have access to change that code ? It's very useful when I run django shell in the production server, and debug intermittent issue. So I can just call that function and I input specific parameter, then I can know what actually that function did -
Django session id cookie not as expected when requesting from swift
When I use Postman to log a user in I get my csrftoken and sessionid cookies in the response as expected. When I make the same exact request but on my iOS app on the simulator, I get the csrftoken cookie from my response just fine as expected. But I do not get the same sessionid cookie. The cookie I'm getting is named "__cf_bm" with a much longer than expected value. The domain of the sessionid cookie on iOS is also now "cloudflare-ipfs.com", whereas on both Postman and iOS the csrftoken domain is just 127.0.0.1. On Postman the sessionid cookie's domain is also just local host. I never did anything with cloudflare. What could be causing this? -
asgi config in Django
I implemented a chat environment with Django chat channel and it works with asgi, messages are exchanged on my computer without any problem, but when I upload my project on host, it does not exchange messages, I am wondering should I config my passenger_wsgi or some configuration from my host? My asgi config: import os import chat.routing from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.core.asgi import get_asgi_application from chat.routing import websocket_urlpatterns os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") django_asgi_app = get_asgi_application() application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(websocket_urlpatterns)) ), } ) My wsgi import os from django.core.wsgi import get_wsgi_application from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'zgalaxy.settings') aplication = get_wsgi_application() ` My passenger_wsgi from zgalaxy.asgi import application ` My settings.py ASGI_APPLICATION = 'zgalaxy.asgi.application' `