Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django not creating id (pk) on save
I have an old project that I have been asked to maintain and I'm getting some very strange behavior. I have this bit of code where a user's transaction is saved trans = Transaction( # id=str(newest_id), user=request.user, account=userAccount, # balance=balance, date=date, description=description, credit=credit, debit=debit, monthNum=monthNum, monthName=monthName, year=year ) trans.save() # adds record to the database The problem is that the transaction saves but it isn't assigned a id or a primary key (to an sqlite3 database). You can see by the commented code that I've even tried to force it to add an ID number but it didn't like that (and it is a horrible idea as well). I'm pretty sure it is not the code because I'm getting the same behavior from the Admin panel. If I create a new transaction there it saves, but when I try and access the newly created save I get the error "Transaction with ID "None" doesn't exist. Perhaps it was deleted?" I'm thinking this has something to do with the Django version. It was running on local machine which died. I've been asked to get it up and running again, but there was no requirements.txt file so I am guessing which version … -
Refresh django form widgets using htmx
I've successfully used htmx to handle a AJAX call to replace part of an django template form. Please see the question I posted on this here Django and HTMX for dynamically updating dropdown list in form.field . But, the form element being replaced is a multiple drop down list, which uses the django_easy_select2 library to render the drop down list nicely, and the form's widgets are not being refreshed when the partial is loaded (which means only the basic django MultipleChoiceSelect is shown). Grateful if someone could explain how I can solve this using htmx. Many thanks. -
Django Database error(after adding new field to exisiting old table)
I'm getting inconsistentmigration error in django production. Basically I tried doing python manage.py makemigrations and it shows old changes I made a while ago, then trying to migrate that it says inconsistentmigration. I can't delete or drop databases as I have lots of data. How do I solve this error as now I can't even make changes to my database tables. Please help. -
Trying to Redirect User to a Home page (Index.html) when they are signed out
I have been trying to solve one problem regarding redirect to another html page. I am creating a simple Restaurant Booking System (using python Django etc.) that will show the user (once logged in) their bookings to date, to amend or delete bookings and create a new booking. For the Admin, they can view and approve or reject bookings. But once logged out the user will see the main page describing the restaurant etc. The issue I am facing is that every time I log out as both admin and user, I am getting an Anonymous error message which I know the system needs someone to be signed in for a page to appear. So I created a new index.html and created the following: Index.html: enter image description here base.html: enter image description here the apps (booking) model.py: enter image description here the apps (booking) view.py: enter image description here the apps (booking) urls.py: enter image description here After all that I managed to get this error: enter image description here Where am I going wrong? I have tried everything. I tried everything as per the below in the views.py file: `from django.shortcuts import render, redirect from django.views import generic, … -
User is automatically being logout randomly when using session authentication in Django
I am using Django version 4.1 and haven't modified any codes for authentication and have used the defaults/built-ins provided by Django itself. I am facing issue of logging out automatically in random order when user is using my application. I tried to see the request logs during the time of logout, i even replicated it on my local computer, but i couldn't find any bugs or issue (until now) which caused this issue. Issue replication steps (but this doesn't happen always) More than 2 users using the app at same time From this question, i would like to ask What should i be looking for when debugging such scenarios? -
How to make the quantity field fill up automatically depending on the number of objects created in the adminpanel "StackedInLine"
As in the title, I would like the quantity field to fill in automatically. admin.py class ItemInline(admin.StackedInline): model = ProductIndex extra = 0 @admin.register(Book) class BookAdmin(admin.ModelAdmin): list_display = ['title', 'genre', 'price', 'quantity', 'is_available'] list_filter = ['genre', 'is_available'] search_fields = ['title'] exclude = ['popularity'] inlines = [ItemInline] form = BookForm forms.py class BookForm(forms.ModelForm): class Meta: model = Product fields = '__all__' def __init__(self, *args, **kwargs): super(BookForm, self).__init__(*args, **kwargs) self.fields['genre'].choices = [(x.pk, x.name) for x in Genre.objects.filter(category='book')] models.py class Product(PolymorphicModel): title = models.CharField(max_length=100, blank=False, null=False) image = models.ImageField(upload_to='product', default=None) genre = models.ForeignKey(Genre, on_delete=models.CASCADE) quantity = models.IntegerField(null=False) is_available = models.BooleanField(default=True, null=False) price = models.IntegerField(null=False, blank=False, default=15) popularity = models.IntegerField(default=0) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse("ProductDetail", args=[str(self.pk)]) @property def model_name(self): return self._meta.model_name class ProductIndex(models.Model): inventory_number = models.CharField(max_length=255) product = models.ForeignKey(Product, on_delete=models.CASCADE) rental = models.ForeignKey(Rental, on_delete=models.CASCADE) is_available = models.BooleanField(default=True) def __str__(self): return str(self.inventory_number) class Book(Product): author = models.CharField(max_length=100, null=False, blank=False) isbn = models.CharField(max_length=100, null=False, blank=False, unique=True) I tried to do it in the clean() method in forms. But the problem may be that the product is done first and then the productindex. I tried to do a query, len(ProductIndex.objects.filter(product=product) but it didn't work properly. Please help, thank you -
How to prevent django HttpResponseRedirect from overriding URL
In views.py, I use the following to redirect to an HTML page with a parameter: return HttpResponseRedirect("my_page.html?request={"my_request"}") I fetch incoming request in my_page.html as following: <script> var params = new URLSearchParams(document.location.search); var request = params.get("request"); </script> This works as I expect, but of course with overriding URL, from currenturl.com/ to currenturl.com/my_page.html?request=my_request. How can I make the URL intact? -
Django adding current page url to static path
I'm facing an issue with serving my static files. My images are stored in project/static/images When I try to display images on my homepage, no problem, the url is good. But now that I'm trying t o display images on other pages I have the following error : "GET /contact_details/static/images/contact_image.png HTTP/1.1" 404 4212 Django is adding the name of my page 'contact_details' before the image path. Here's my code : settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_URL = '/images/' MEDIA_ROOT =BASE_DIR /'images' urls.py urlpatterns = [ path('', views.home, name="home"), path('contact_details/', views.contactDetails, name="contact_details"), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I found on the forum that for other people the problem came from the STATIC_URL not starting with a slash, but in my case in didn't change nothing. -
Flattening multiple querysets that share the same name in Django
I have multiple querysets that look like: NAME1 | VALUE_FROM_COLUMN_1 NAME1 | VALUE_FROM_COLUMN_2 NAME1 | VALUE_FROM_COLUMN_3 How do I flatten this design other than using list(chain(q1, q2, q3)) function because it shows up like this: NAME1 | VALUE_FROM_COLUMN_1 | | NAME1 | | VALUE_FROM_COLUMN_2 | NAME1 | | | VALUE_FROM_COLUMN_3 And I want this: NAME1 | VALUE_FROM_COLUMN_1 | VALUE_FROM_COLUMN_2 | VALUE_FROM_COLUMN_3 -
Django post_save is not executed on CI/CD
I recently increased the default permissions for all my Django Views. In order for the users to have some default permissions I add new users to a default Group that has mainly viewing permissions. This is done via a post_save signal. MODELS_VIEW = [ "time entry", "time entry version", "project", "client", "user", ] MODELS_CHANGE = ["time entry version", "user"] MODELS_CREATE = ["time entry version"] MODELS_DELETE = ["time entry version"] def _add_permissions_to_group(group, perm_type: str, models: List[str]) -> None: """Add the permission of the `perm_type` to the given models.""" from django.contrib.auth.models import Permission for model in models: perm_name = f"Can {perm_type} {model}" permission = Permission.objects.get(name=perm_name) group.permissions.add(permission) def _add_view_permissions_to_group(group) -> None: _add_permissions_to_group(group, perm_type="view", models=MODELS_VIEW) def _add_create_permissions_to_group(group) -> None: _add_permissions_to_group(group, perm_type="add", models=MODELS_CREATE) def _add_change_permissions_to_group(group) -> None: _add_permissions_to_group(group, perm_type="change", models=MODELS_CHANGE) def _add_delete_permissions_to_group(group) -> None: _add_permissions_to_group(group, perm_type="delete", models=MODELS_DELETE) def _get_default_user_group_with_permissions(): """Get or create the default UserGroup and add all standard permissions.""" from django.contrib.auth.models import Group logger.debug("Getting default group for user") group, _ = Group.objects.get_or_create(name="default") # Add the standard permissions for users _add_view_permissions_to_group(group) _add_create_permissions_to_group(group) _add_change_permissions_to_group(group) _add_delete_permissions_to_group(group) return group class UsersConfig(AppConfig): """Config for Users""" default_auto_field = "django.db.models.BigAutoField" name = "users" def ready(self): """Add the user to the default UserGroup.""" logger.debug("User-config: App ready") def _add_to_default_group(sender, **kwargs): """Add the user … -
getting error when converting html to image using html2image
This is the code I am trying to execute in python shell, but I am getting this error. Please help!! >>> from html2image import Html2Image >>> hti = Html2Image(temp_path="/tmp", output_path="/var/www/html/commonservice/htmltoimage", custom_flags=["--no-sandbox", "--headless", "--hide-scrollbars", "--disable-gpu", "--default-background-color=ffffff"]) >>> html = """<h1> An interesting title </h1> This page will be red""" >>> css = "body {background: red;}" >>> hti.screenshot(html_str=html, css_str=css, save_as='temp_image.png') /snap/chromium/2406/snap/command-chain/desktop-launch: line 369: cannot create temp file for here-document: No such file or directory [0403/090244.518985:WARNING:bluez_dbus_manager.cc(247)] Floss manager not present, cannot set Floss enable/disable. [0403/090244.553724:WARNING:sandbox_linux.cc(393)] InitializeSandbox() called with multiple threads in process gpu-process. [0403/090244.788897:ERROR:headless_command_handler.cc(222)] Failed to write file /var/www/html/commonservice/htmltoimage/temp_image.png: No such file or directory (2) ['/var/www/html/commonservice/htmltoimage/temp_image.png'] -
How to access the names of fields in Django UniqueConstraint : 2?
I have original question here How to access the names of fields in Django UniqueConstraint? but it do not answer my question when *expressions contains different kind of "fields". I left the accepted answer. I want to access the unique constraint field names when declared in Meta class : class Book(models.Model): name = CharField(...) author = ForeignKey(...) description = ... class Meta: constraints = [ UniqueConstraint( Lower("name"), "author", name="unique__book_author", ), ] def do(self): unique_fields = ... # should be ["name", "author"] All fields are not necessarily a function like Lower. In this case, author is a foreign key. See https://docs.djangoproject.com/en/4.1/ref/models/constraints/ -
Django REST + Vue.js Google OAuth2 authorization code flow
I have a Django REST + Vue.js application where I'm using Google OAuth2 to handle authentication. Up to now, I've been using client-side authentication and the drf-social-oauth2 package, where the frontend gets an access_token from Google and sends it to the backend, which exchanges it for an in-house token which is returned to the frontend. I'm adding some integrations with the Google API services, and now I need to store the users' access_token and refresh_token when they log in. Therefore, I'm adding incremental auth using the authorization code flow: the frontend will get an authorization code after granting consent to my app to access the necessary scopes; the backend will exchange it for a pair of access_token and refresh_token and store them in a model. This is the way I've been doing it: when the user clicks the "Authorize" button on my frontend, the app makes a request to an endpoint that returns an auth url generated with a function that looks like this: from google_auth_oauthlib.flow import Flow def get_flow(scope_role: Optional[Union[Literal["teacher"], Literal["student"]]]): from integrations.classroom.views import GoogleClassroomViewSet scopes = get_scopes(scope_role) # returns a list of necessary scopes flow = Flow.from_client_config( GoogleClassroomIntegration().get_client_config(), scopes=scopes, ) # hard-coded url for proof of concept flow.redirect_uri … -
I want to write a template for my views, I am just struggling to make it
{'totals': <QuerySet [ {'trans_mode': 'Cash', 'month': datetime.date(2023, 1, 1), 'tot': Decimal('99.25')}, {'trans_mode': 'Cash', 'month': datetime.date(2023, 2, 1), 'tot': Decimal('161.25')}, {'trans_mode': 'Cash', 'month': datetime.date(2023, 3, 1), 'tot': Decimal('40.5')}, {'trans_mode': 'ENBD', 'month': datetime.date(2023, 1, 1), 'tot': Decimal('2215.72000000000')}, {'trans_mode': 'ENBD', 'month': datetime.date(2023, 2, 1), 'tot': Decimal('1361.66000000000')}, {'trans_mode': 'ENBD', 'month': datetime.date(2023, 3, 1), 'tot': Decimal('-579.130000000000')}, {'trans_mode': 'NoL', 'month': datetime.date(2023, 1, 1), 'tot': Decimal('107')}, {'trans_mode': 'NoL', 'month': datetime.date(2023, 2, 1), 'tot': Decimal('56')}, {'trans_mode': 'NoL', 'month': datetime.date(2023, 3, 1), 'tot': Decimal('-69.5')}, {'trans_mode': 'Pay IT', 'month': datetime.date(2023, 1, 1), 'tot': Decimal('0')}, {'trans_mode': 'SIB', 'month': datetime.date(2023, 1, 1), 'tot': Decimal('208.390000000000')}, {'trans_mode': 'SIB', 'month': datetime.date(2023, 2, 1), 'tot': Decimal('-3.25')} ]>} above is the query set from Django views. I want to achieve the below, please suggest me a good way Trans Mode Jan 2023 Feb 2023 Mar 2023 Cash 99.25 161.25 40.5 ENBD 2215.72 1361.66 -579.13 NoL 107 56 -69.5 Pay IT SIB 208.39 -3.25 -
What would be the best way to handle situations that involves keeping records/history of fields based on the timerange_uuid?
Well, I think, I have run out of ideas and would like someone to help me explain using the example below. I have three tables (Timerange_uuid - should be an enum, and Person, and Organization), I want each time the Person changes an Organization (the Person can change organisations depending on the kind of work he/she is doing) the person's table should keep records of all Organizations that the person has served since the start date to end date - basing on the Timerange_uuid, and I can't figure out what would be the most appropriate solution to handle this situation. Timerange_uuid (enum) class Timerange_uuid(models.Model): start = models.DateTimeField(auto_now_add=True) stop = models.DateTimeField(auto_now=True) u = models.UUIDField(default=uuid.uuid4) class Meta: abstract = True Person class Person(models.Model): group_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) organization = ??? ## timerange_uuid[] -- organization_id Organization class Organization(models.Model): organization_id = models.UUIDField(primary_key=True ,default=uuid.uuid4, editable=False) -
Problem with static files while deploying django with docker-compose
I cannot serve the static files on my Django docker compose deployment. I want it for local deployment, using the built-in web server (runserver) My docker-compose: version: "3" services: app: build: context: ./app dockerfile: Dockerfile command: bash -c "./wait-for-mysql.sh mysqldb" depends_on: - mysqldb ports: - "8000:8000" volumes: - ./app:/app - ./app/static:/static environment: DJANGO_SETTINGS_MODULE: proteas2.settings.production DB_NAME: ${DB_NAME} DB_USER: ${DB_USER} DB_PASS: ${DB_PASS} DB_PORT: ${DB_PORT:-3306} DB_HOST: mysqldb env_file: - .env networks: - proteas mysqldb: image: mysql:latest command: ["--default-authentication-plugin=mysql_native_password"] ports: - "${DB_PORT:-3306}:3306" environment: MYSQL_DATABASE: ${DB_NAME} # MYSQL_USER: ${DB_USER} # MYSQL_PASSWORD: ${DB_PASS} MYSQL_ROOT_PASSWORD: ${DB_PASS} DJANGO_SUPERUSER_USERNAME: ${DJANGO_SUPERUSER_USERNAME} DJANGO_SUPERUSER_EMAIL: ${DJANGO_SUPERUSER_EMAIL} DJANGO_SUPERUSER_PASSWORD: ${DJANGO_SUPERUSER_PASSWORD} volumes: - ./db-data:/var/lib/mysql env_file: - .env networks: - proteas networks: proteas: I have: 'django.contrib.staticfiles' in my INSTALLED_APPS I tried to set: STATIC_URL = os.path.join(BASE_DIR, 'static/') STATIC_ROOT = 'static/' I ran collectstatic but did not make it work. -
How to run channel functions inside shared task function of celery in django?
I am working in a django proejct using celery , redis , rabbitmq , channels all together . I am using two queues Queue A and Queue B for my task assignment and i am using rabbitmq and redis for it. And i am using celery for background task . Now I want to run channels group_send function or in simpler terms i want to use channel functions inside the shared task function of celery so that i can use channels and send messages in real time from the shared task function. I have tried lots of ways but error still persists , every error mainly points towards the event loop that it is closed . Here is my views.py which runs the task function . def myView(request , *args , **kwargs) : try : myTask.delay({}) except Exception as e : print(e) return render(request , "app/htmlFile.html" , context = {} ) This is my tasks.py where i have created tasks and where i am using channel function ( group_send) to send message to the channels group . @shared_task(bind = True , queue = "A") def myTask(self , data): return None Now my various combinations where i used different methods to … -
filter select2 result based on logged in user
I have a select2 input in my django form and i want to filter the select2 options based on the logged in user for example I want user 1 to see options 1 and 3 but for user 2 options 1 snd 3 it's importatnt that my options themeselves are foreign keys from other tables here is my foreign key example: buyer = models.ForeignKey( Contact, on_delete=models.PROTECT, null=True, blank=True,related_name="buyer_contact_buy" ) and here is my ModelForm: class BuyForm(ModelForm): def __init__(self, *args, **kwargs): super(BuyForm, self).__init__(*args, **kwargs) for field_name in self.fields.keys(): self.fields[field_name].widget.attrs['class'] = 'form-control' self.fields['buyer'].widget.attrs['class'] = 'form-control ' + 'select2' class Meta: model = Buy exclude = ('id', 'creator_user',) and this is the js in my HTML: <script type="text/javascript"> $(document).ready(function () { // [ Single Select ] start $(".select2").select2(); }); </script> i had some search but i didnt get any result hope you guys can help me -
Django Channels: Mission Positional Arguments send and receive
Here My Consumer.py currently im developing a live chat system using django channels, but im facing below mentioned issue. please tell me how i can solve below mentioned issue. channels==4.0.0 ` import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.booking_id = None self.booking_group_name = None async def connect(self): self.booking_id = 2 self.booking_group_name = 'chat_%s' % self.booking_id # Join booking group await self.channel_layer.group_add( self.booking_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave booking group await self.channel_layer.group_discard( self.booking_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data=None, bytes_data=None): text_data_json = json.loads(text_data) sender = self.scope['user'] message = text_data_json['message'] # Save chat message to database await self.save_chat_message(sender, message) # Send message to booking group await self.channel_layer.group_send( self.booking_group_name, { 'type': 'chat_message', 'sender': sender.username, 'message': message } ) async def chat_message(self, event): sender = event['sender'] message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'sender': sender, 'message': message })) def save_chat_message(self, sender, message): from booking.models import Booking, CustomerSupportCollection, CustomerSupportChat booking = Booking.objects.get(id=self.booking_id) collection = CustomerSupportCollection.objects.get_or_create( booking=booking, ) chat_message = CustomerSupportChat.objects.create( booking=booking, collection=collection, user=sender, message=message ) return chat_message ` asgi.py """ ASGI config for cleany project. It exposes the ASGI callable as a module-level variable named … -
Remove unnecessary space between lines, flex-wrap tailwind-CSS
{% extends "base.html"%} {% block content %} <div class="place-content-center flex flex-wrap gap-3 mt-2 mb-3 xl:max-w-7xl"> {% for product in products %} <div class="h-fit rounded-md bg-white w-[45%] st:w-[30%] sm:w-[29%] md:w-[22%] lg:w-[18%] xl:w-[15%] shadow-lg"> <a href=""><img src="{{ product.image.url }}" alt="{{ product.name }} image"> <div class="ml-1 mr-1"> <h3 class="text-xs font-mono font-light">{{ product.name }}</h3> <h4> <span class="text-xs">KMF</span> <span class="font-semibold text-lg text-[#EF4444]">{{ product.price }}</span> </h4> </div> </a> <div class="flex place-content-center gap-5 m-2"><!--Shopping cart--> <div class="flex flex-col items-center"> <!--Shopping cart svg icon--> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-5 h-5 sm:w-6 sm:h-6"> <path d="M2.25 2.25a.75.75 0 000 1.5h1.386c.17 0 .318.114.362.278l2.558 9.592a3.752 3.752 0 00-2.806 3.63c0 .414.336.75.75.75h15.75a.75.75 0 000-1.5H5.378A2.25 2.25 0 017.5 15h11.218a.75.75 0 00.674-.421 60.358 60.358 0 002.96-7.228.75.75 0 00-.525-.965A60.864 60.864 0 005.68 4.509l-.232-.867A1.875 1.875 0 003.636 2.25H2.25zM3.75 20.25a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0zM16.5 20.25a1.5 1.5 0 113 0 1.5 1.5 0 01-3 0z" /> </svg> </div> <!--Wish list--> <div class="flex flex-col items-center"> <!--Wish list svg icon--> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-5 h-5 sm:w-6 sm:h-6"> <path stroke-linecap="round" stroke-linejoin="round" d="M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12z" /> </svg> </div> </div> <div class="flex flex-col justify-center font-semibold text-xs gap-2 ml-1 … -
How can I display two testimonial cards in one slide using Django and Bootstrap?
I created a static testimonial section for my website, but I wanted to make it dynamic by adding a django model in my app for testimonials. I was able to fetch the data and show it on the page, but my design has two testimonial cards in one slide, and I'm struggling to implement this feature. Despite my attempts, I'm only able to display one testimonial card in the slide, which is ruining the design. Can anyone guide me on how to implement a solution for this issue? this is my model for testimonials class Testimonial(models.Model): name = models.CharField(max_length=100) content = FroalaField() image = models.ImageField(upload_to='testimonial/') def __str__(self): return self.name I added some data through Django admin and used the following HTML code to display the testimonials this is the staic html <!-- client section --> <section class="client_section py-5"> <div class="container"> <div class="d-flex justify-content-center"> <div class="container" style="text-align: center;"> <h2 class="sub-head">TESTIMONIAL</h2> <div class="small-heading"> <div class="line"></div> <span class="title">Words From Our Clients</span> <div class="line"></div> </div> </div> </div> <div id="carouselExample2Indicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExample2Indicators" data-slide-to="0" class="active"></li> </ol> <div class="carousel-inner"> <div class="carousel-item active"> <div class="client_container"> <div class="row"> <div class="col-md-6"> <div class="client_box"> <div class="detail_box"> <div class="img_box"> <img src="https://randomuser.me/api/portraits/women/28.jpg" /> </div> <h5> Valerie Hayes </h5> … -
Nginx not able to file gunicorn socket file http 502
5 connect() to unix:/var/run/mygunicorn.sock failed (2: No such file or directory) while connecting to upstream my gunicorn.service file [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=abc Group=www-data WorkingDirectory=/home/abc/mywork/xyz ExecStart=/home/abc/shoenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/var/run/mygunicorn.sock xyz.wsgi:application [Install] WantedBy=multi-user.target gunicorn.socket file [Unit] Description=gunicorn socket [Socket] ListenStream=/var/run/mygunicorn.sock [Install] WantedBy=sockets.target nginx server new sites-available server { listen 80;listen [::]:80; server_name <gunicorn server ip>; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/abc/shopcart; } location / { include proxy_params; proxy_pass http://unix:/var/run/mygunicorn.sock; } } I can curl it from gunicorn server curl --unix-socket /var/run/mygunicorn.sock localhost But when I try from nginx directory it cannot find socket file unix:/var/run/mygunicorn.sock failed (2: No such file or directory) while connecting to upstream socket file exists though srw-rw-rw- 1 root root 0 Apr 3 06:18 /var/run/mygunicorn.sock -
Django-graphene and tree structure output
Is it possible to make a tree structure output of the following type with the help of django-graphene? "mainMenu": [ { "pageSlug": "page-slug-01", "pageTitle": "page-title-01", "children": [ { "pageSlug": "sub_page-slug-01", "pageTitle": "sub_page-title-01", "children": [ ... ] }, ... { "pageSlug": "sub_page-slug-N", "pageTitle": "sub_page-title-N", "children": [ ... ] }, ] }, ... { "pageSlug": "page-slug-N", "pageTitle": "page-title-N", "children": [ ... ] }, ] I can't figure out how to describe the classes... -
Django is automatically clear expire sessions?
Django is automatically clear expire sessions? I just want to understand this. i search about this, but nothing -
Where is the parent html file in the Django app?
There is a Django app i am trying to modify. This is the code for it's base.html file: {% extends "base.html" %} {% load i18n %} {% block extra_head %} {{ block.super }} {% endblock %} {% block tabs %} <li><a href="{% url 'app_manager_base_url' %}">{% trans "Apps" %}</a></li> {{block.super}} <li><a href="{% url 'app_manager_base_url' %}">{% trans "Apps" %} asd</a></li> {% endblock %} {% block footer %} {% include 'cartoview/footer.html' %} {% endblock %} now here there are 3 tabs inside block.super. I want to change those tabs. But when i see the parent file then it says above extends base.html. The problem is that this file itself is named base.html and there is no other file of this name in this same directory. I want to locate the parent file so to change those tabs. Kindly help thanks.