Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get single item in Django Rest Framework
I have a database with cars, and each car has an id. To get all cars I would go at this route api/cars/, now I am trying to implement getting a single car which has id 1 and this is my urls: urlpatterns = [ path('api/cars/', CarsAPI.as_view()), path('api/cars/:id/', CarAPI.as_view()), path('api/tours/ongoing/', CarListOngoingAPI.as_view()) ] And this is my views for first path and second, class CarsAPI(generics.ListCreateAPIView): queryset = Car.objects.all() serializer_class = CarsSerializer # GET single car with id class CarAPI(generics.RetrieveAPIView): queryset = Car.objects.all() serializer_class = CarsSerializer class CarListOngoingAPI(generics.ListAPIView): queryset = Car.objects.all() serializer_class = CarsSerializer And here is my Car model: class Car(models.Model): make = models.CharField(max_length=100, blank=True) description = models.CharField(max_length=500, blank=True) ongoing = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) First class returs a list of all car models. Now I need to find a way to implement two other types, one where an argument is passed in, in my case id api/cars/:id/ and the second api/cars/ongoing/, I should say that these are just hypothethetical cases, just for learning purposes and any help is greatly appreciated. -
SynchronousOnlyOperation from celery task using gevent execution pool
Given celery running with these options: celery -A openwisp2 worker -l info --pool=gevent --concurrency=15 -Ofair Given this celery task from openwisp-monitoring: @shared_task def perform_check(uuid): """ Retrieves check according to the passed UUID and calls ``check.perform_check()`` """ try: check = get_check_model().objects.get(pk=uuid) except ObjectDoesNotExist: logger.warning(f'The check with uuid {uuid} has been deleted') return result = check.perform_check() if settings.DEBUG: # pragma: nocover print(json.dumps(result, indent=4, sort_keys=True)) Most of the time the task works, but some times (usually with bursts), the following exception is generated: SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. Full stack trace: SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. File "celery/app/trace.py", line 412, in trace_task R = retval = fun(*args, **kwargs) File "celery/app/trace.py", line 704, in __protected_call__ return self.run(*args, **kwargs) File "openwisp_monitoring/check/tasks.py", line 44, in perform_check check = get_check_model().objects.get(pk=uuid) File "django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "django/db/models/query.py", line 425, in get num = len(clone) File "django/db/models/query.py", line 269, in __len__ self._fetch_all() File "django/db/models/query.py", line 1308, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "django/db/models/query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "django/db/models/sql/compiler.py", line 1154, in execute_sql cursor = self.connection.cursor() File "django/utils/asyncio.py", line … -
Django - How to get a list of items with the latest element of some ID
For example I have these objects in my DB: [ Item(id: 1, created_at: 01/12/2020), Item(id: 1, created_at: 02/12/2020), Item(id: 2, created_at: 01/12/2020), Item(id: 2, created_at: 02/12/2020), Item(id: 2, created_at: 03/12/2020), ] What I want is latest items from that ID, like these in this example [ Item(id: 1, created_at: 02/12/2020), Item(id: 2, created_at: 03/12/2020), ] How can I filter these out? Thanks and regards -
Django: reference model fields from another model
I have two models. What i need is to reference the name and the email field from the Users model to the Customer model fields. Is the following way correct? class Users(AbstractBaseUser): name = models.CharField(max_length=200) email = models.CharField(max_length=200) from users.models import Users class Customer(models.Model): user = models.OneToOneField( Users, on_delete=models.CASCADE, null=True, blank=True) name = models.OneToOneField( Users.name, on_delete=models.CASCADE, null=True, blank=True) email = models.OneToOneField( Users.email, on_delete=models.CASCADE, null=True, blank=True) -
Creating custom filter for django-groups-manager
I have my own custom account model and installed django-groups-manager for handling members and groups and roles. So in views.py I have: from groups_manager.models import Group, GroupMemberRole, Member def clerks_view(request): accounts = Member.objects.all().reverse() account_filter = AccountFilter(request.GET, queryset=accounts) # I created AccountFilter in forms.py for account in accounts: # Do Something like: accounts_info[account].update({'joined_on': account.django_user.joined_on}) accounts_roles = GroupMemberRole.objects.filter(groupmember__member=account) for role in accounts_roles: roles['roles'].append(role) accounts_info[account].update(roles) context = {'accounts_info': accounts_info, 'account_filter': account_filter} return render(...) And in my template I have to do: <tbody> {% for account, fields in accounts_info.items %} <tr> <td><span class="text-primary">{{forloop.counter}}</td></span> <td class="td-actions"> <li><span class="text-primary">{{fields.joined_on.year}}/{{fields.joined_on.month}}/{{fields.joined_on.day}}</span></li> <li><span class="text-primary">{{fields.joined_on.hour}}:{{fields.joined_on.minute}}:{{fields.joined_on.second}}</span></li> </td> td><span class="text-primary">{{account.django_user.username}}</span></td> <td><span class="text-primary">{{account.django_user.first_name}} {{account.django_user.last_name}}</span></td> <td><span class="text-primary">{{account.django_user.team}}</span></td> <td class="td-actions"> {% for role in fields.roles %} <li><span class="text-primary">{{role.label}}</span></li> {% endfor %} </td> <td><span class="text-primary">{{account.django_user.description}}</span></td> </tr> {% endfor %} </tbody> I want to ask if we have a solution to make a filter.py for searching through these fields in my template. When I use {{account_filter.form}} in my template I can't filter above fields. Finally this is the way I made my filters.py: import django_filters from django_filters import DateFilter, CharFilter from groups_manager.models import Group, GroupMemberRole, Member class AccountFilter(django_filters.FilterSet): start_date = DateFilter(field_name="joined_on_p", lookup_expr="gte") end_date = DateFilter(field_name="joined_on_p", lookup_expr="lte") class Meta: model = Member fields = '__all__' -
Auto display the form's data in other view (django)
I'm using django forms to get some data from the user. It works well with the DB. How can I display that data (in a different page) right after submitting? The flow should be: The user fills the form Clicks submit (creates an object and saves to DB) The user is redirected to another page in which the data he just submitted is presented. Basically I need to pass the object's PK (the one the user just created) from one view to another. It's supposed to be fairly simple yet I couldn't find a decent solution for that issue. Thanks! -
Image is not editing after click on update button
I am going through a Django tutorial and My blog post image is not editing for edit post in my blog app. I use Django==3.1.2. views.py def edit_post(request, post_id): post = BlogPost.objects.get(id=post_id) if request.method != 'POST': form = UpdatePost(request.POST or None, request.FILES or None, instance=post) else: form = UpdatePost(instance=post, data=request.POST) if form.is_valid(): form.save() return redirect('mains:posts') context = {'post':post,'form':form} return render(request, 'mains/edit_post.html', context) forms.py class UpdatePost(forms.ModelForm): class Meta: model = BlogPost fields = ['blog_post_title','blog_description','image'] edit_post.html {% block content %} <div class="container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <table> {{ form.as_table }} </table> <button type="submit">Save Changes</button> </form> </div> {% endblock content %} The Problem I am trying to edit my post in my blog app, Everything is working fine ( Blog title and Blog description is changing ) - when i change image it returns ( redirect ) fine BUT image not changing. I am stuck with this problem and have no idea what is wrong. What have i tried. 1). When i first create the view then i didn't add (request.POST or None, request.FILES or None), BUT when i notice that, this may be effecting from editing then i added and it still not editing the image. 2). I have also … -
Django BinanceSocketManager works on local machine but doesn't work on Nginx server
Recently I’m working on a Django project in which I need to get the price of some cryptocurrencies like BTC, ETH, and … So I used BinanceSocketManager in a class that uses multiprocessing. I used the tutorial from this link: https://livedataframe.com/live-cryptocurrency-data-python-tutorial/ It works fine on my local machine but when I started to deploy it to Centos 7 server, faced some problems. The problem is that the BinanceSocketManager doesn’t call the trade_prices function to pass the received message to it and get the prices. (I’m using Nginx webserver with Python version 3.6.8 and pip and gunicorn and daphne) Here is my code: import multiprocessing from binance.client import Client from binance.websockets import BinanceSocketManager global PRICES PRICES = {} PUBLIC = 'My-Public-key' SECRET = 'My-Private-key' # This method works on development mode but doesn't work on deploy mode! def trade_prices(msg): # I can see these print statements on my local machine terminal but not on the server! print("msg : ", msg) if msg['s'] == 'BTCUSDT': PRICES['BTCUSDT'] = [msg['c'], msg['P']] print("PRICES : ", PRICES) class Process(multiprocessing.Process): __instance = None @staticmethod def getInstance(): if Process.__instance is None: Process() return Process.__instance def __init__(self): super().__init__() if Process.__instance is not None: # raise Exception("This class is a … -
Why my css file is not linking with html files in django
here is all my code why css file is not linked with html file. what is the problem as it dosent shows any error and not any effect on webpage. my setting.py and base.html and base.css Also my static folder outsite my app base.html code below: <!DOCTYPE html> {% load static %} <html> <head> <title>First Project</title> <link href="{% static 'css/base.css' %}" rel="stylesheet" > </head> <body> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <div class="container"> <h1>Parvinder</h1> {% block content %} {% endblock %} </div> </body> </html> base.css code body{ background-color: black; color: blue; } h1{ color: red; } setting.py from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIR = os.path.join(BASE_DIR,"templates") STATIC_DIR = os.path.join(BASE_DIR,"static",'Users/shree/First_Project/static/') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '(1i-@kb057g&x*8ahp1r5f#f(7f99@6uixjl#j*&x%%sp3ily6' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', 'register', 'crispy_forms' ] 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', ] ROOT_URLCONF = 'first_project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', … -
React and Django: How to build and edit functionality with Redux?
I'm working on a CRUD app (blog app basically), i sucessfully created the create, read and delete functionality only update/edit is remaining. Im a beginner with redux i really need your help guys to make my app work. I deployed the frontend part on bitbucket here https://bitbucket.org/Yash-Marmat/frontend-part-of-blog-app/src/master/src/ and the backend looks like this (pic below) -
Django 3 error - NoReverseMatch at /; Reverse for 'car_detail' with no arguments not found. 1 pattern(s) tried: ['cars/(?P<id>[0-9]+)$']
I'm currently taking a tutorial on Django from an ebook. I keep getting this error despite doing what is written in the book. Maybe, I'm having an oversight and must have missed something. Can a kind person kindly help go through my code and tell me what I must have been doing wrong? I've attached my code snippets below. Any help will be greatly appreciated. Thanks NoReverseMatch at / Reverse for 'car_detail' with no arguments not found. 1 pattern(s) tried: ['cars/(?P<id>[0-9]+)$'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'car_detail' with no arguments not found. 1 pattern(s) tried: ['cars/(?P<id>[0-9]+)$'] Exception Location: C:\Python37\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 677 Python Executable: C:\Python37\python.exe Python Version: 3.7.7 Python Path: ['D:\\Django_Tests\\CarZone_Project', 'C:\\Python37\\python37.zip', 'C:\\Python37\\DLLs', 'C:\\Python37\\lib', 'C:\\Python37', 'C:\\Python37\\lib\\site-packages'] Server time: Wed, 16 Dec 2020 14:46:01 +0000 Error during template rendering In template D:\Django_Tests\CarZone_Project\templates\base.html, error at line 0 Reverse for 'car_detail' with no arguments not found. 1 pattern(s) tried: ['cars/(?P<id>[0-9]+)$'] 1 {% load static %} 2 3 <!DOCTYPE html> 4 <html> 5 6 <head> 7 <title></title> 8 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 9 <meta charset="utf-8"> 10 Traceback Switch to copy-and-paste view C:\Python37\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) … ▶ Local vars C:\Python37\lib\site-packages\django\core\handlers\base.py … -
Django/Supervisor: environment variables not set
stack : Django/Nginx/Gunicorn/Sueprvisor I try to work with environment variable but it does not work settings.py SECRET_KEY = os.environ.get('SECRET_KEY', '******************') # if os.environ.get('ENV') == 'PRODUCTION': DEBUG = False ALLOWED_HOSTS = ['192.168.**.*','https://****'] else: DEBUG = True ALLOWED_HOSTS = ['127.0.0.1','localhost', '[::1]'] myapp-gunicorn.conf [program:myapp-gunicorn] ... #environment = ENV="DEV" environment = ENV="PRODUCTION",SECRET_KEY="*****************" When I get url of my web site, DEBUG=True as I can see Django debug toolbar If I run env command, ENV and SECRET_KEY variable are not listed I try to sudo supervisorctl reread and sudo supervisorctl update and restart gunicorn sudo supervisorctl restart myapp-gunicorn but does not change anything I try with tabs without success environment = ENV="PRODUCTION", SECRET_KEY="*****************" -
Create a seconds field in django
I'm trying to create a field that only stores seconds, without the option to enter hours and seconds. Thank you! -
Single template and dynamic menu
I'm new to Django and what I'm trying to do is using a single template for my whole site (which we will call MySite). The page content will dynamically be loaded from a class which returns the page content : content = PageContent().get_content_for("index") My template looks like this : <!DOCTYPE html> <html lang="en-fr"> <head></head> <body> {{ menu | safe }} {{ content | safe}} </body> </html> The menu will be loaded using : def get_menu() -> str: # List of dict menu = [ {"name": "Home", "link": "index"}, {"name": "Products, "link": "products" ] # Generated the HTML formatted menu html_menu = "<ul> for elem in menu: html_menu = f"<li><a href=\"{% url '{elem['link']}' %}\">{elem['name']}</a>" html_menu = "</ul>" return html_menu The output should be : <a href="{% url 'index' %}">Home</a> <a href="{% url 'products' %}>Products</a> The thing is that I am not able to pass a static django url using python string I've tried using {% for elem in menu %} <li><a ...></a> {% endfor %} But I can't use a dict with this Do you guys have any on how I can do it ? If it's not clear enough, don't hesitate to ask me for more details in comment Thank … -
unidentified name errors for mime_types, os and slugify
My IDE is giving me errors for unidentified name for mime_types, os and slugify. To be specific the error lies in the following codes mime_type, _ = mimetypes.guess_type(url) , _, extension = os.path.splitext(url.split('/')[-1]) and slugify(imagefieldinstance.title),. These are my django codes that should list down all images from the D:\testsystem\mysite\images folder and users can choose an image to download into their download folder. image_download.html {% extends "main/header.html" %} {% block content %} <head> </head> <body> <a href="images/" download class="btn btn-dark float-right">Download</a> </body> {% endblock %} views.py def imgdownload(self, request, *args, **kwargs): # first get the instance of your model from the database imagefieldinstance = self.get_object() # Then get the URL of the image to download url = imagefieldinstance.img.url try: # Download the image to the server img = request.get(url) if not 200 <= img.status_code < 400: raise Http404() except Exception as e: raise Http404() from e # Figure out the mimetype of the file mime_type, _ = mimetypes.guess_type(url) # Get the file extension _, extension = os.path.splitext(url.split('/')[-1]) # Create the filename of the download filename = '{}{}'.format( slugify(imagefieldinstance.title), extension ) # Add the content of the (image) file to the response object response = HttpResponse( img.content, content_type=mime_type ) response['Content-Disposition'] = \ … -
Problem loading background image from external css (django)
I'm having trouble loading an image via external CSS on Django. It works fine using inline CSS but I want to understand why it doesn't work using external one. Any help would be appreciated: My tree: ├───migrations │ └───__pycache__ ├───static │ └───website │ ├───css │ ├───img │ └───js ├───templates │ └───website └───__pycache__ CSS: .body { background: url('/static/website/img/Racoon.jpg'); } HTML: {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'website/css/main.css' %}"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Russo+One&display=swap" rel="stylesheet"> {% block title %} <title> Home </title> {% endblock %} {% block content %} <h1> Home </h1> <p> Homepage of the website </p> {% endblock %} settings.py: STATIC_URL = '/static/' P.S I'm using localhost and image does load via URL: http://127.0.0.1:8000/static/website/img/Racoon.jpg -
Django queryset/orm from postgres sql cross join generate_series
Based on my previous stackoverflow question: Handling of generate_series() in queries with date or timestamp with / without time zone, I'd like to get a django queryset/orm on the following sql. (reason is raw() has some limitation problems with array_agg and only returns 3 items instead of returning all items) SELECT * FROM ( -- complete employee/date grid for division in range SELECT g.d::date AS the_date, id AS employee_id, name, division_id FROM ( SELECT generate_series(MIN(created_at) AT TIME ZONE 'Asia/Kuala_Lumpur' , MAX(created_at) AT TIME ZONE 'Asia/Kuala_Lumpur' , interval '1 day') FROM attendance ) g(d) CROSS JOIN employee e WHERE e.division_id = 1 ) de LEFT JOIN ( -- checkins & checkouts per employee/date for division in range SELECT employee_id, ts::date AS the_date , array_agg(id) as rows , min(ts) FILTER (WHERE activity_type = 1) AS min_check_in , max(ts) FILTER (WHERE activity_type = 2) AS max_check_out , array_agg(ts::time) FILTER (WHERE activity_type = 1) AS check_ins , array_agg(ts::time) FILTER (WHERE activity_type = 2) AS check_outs FROM ( SELECT a.id, a.employee_id, a.activity_type, a.created_at AT TIME ZONE 'Asia/Kuala_Lumpur' AS ts -- convert to timestamp FROM employee e JOIN attendance a ON a.employee_id = e.id WHERE a.created_at >= timestamp '2020-11-20' AT TIME ZONE 'Asia/Kuala_Lumpur' -- "sargable" expressions … -
can't adapt type 'SimpleLazyObject' with get_context_data (Class Based View)
I have a Django web app deployed to Heroku. App is deployed and working well, except for the related issue. Some specs : In my local env I use SQLite 3 DB In Heroku env I use Postgress DB When I try to render a class based view this error happens to me: can't adapt type 'SimpleLazyObject' After some checks about this issue I suspect it is related to the get_context_data. but i don't know how to approach it. View Code: class ProfileListView(LoginRequiredMixin, ListView): model = Profile template_name = 'profiles/profile_list.html' context_object_name = 'qs' def get_queryset(self): qs = Profile.objects.get_all_profiles(self.request.user) return qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context URL : urlpatterns = [ path('', ProfileListView.as_view(), name='all-profiles-view'), ] -
How to update model object if it exist or create object if isn't
I need some guidance on how properly use update_or_create method As mentioned in django documentation The update_or_create method tries to fetch an object from database based on the given kwargs. If a match is found, it updates the fields passed in the defaults dictionary. Here is raise my misunderstanding. In order to describe in more understandable way Lets make a deal that by kwargs i mean all kwargs passed to update_or_create method except default dictionary. As i understood when **kwargs passed to update_or_create these kwargs are used to fetch database objects. If objects with the same key values will found update_or_create will update object by key values passed in defaults dictionary. But if object wasnt fetched method will create new object from passed kwargs. If it work like i described than using update_or_create can raise dont expectable behaviour. Lets look by example I have created a model class Testmodel(model.Models): call_datetime=models.DateTimeField() i create objects from it. Than i extended model class Testmodel(models.Model): call_datetime=models.DateTimeField() additional=models.CharField() Lets assume that i need to add value of this additional field to objects which was created before extending Testmodel b=Testmodel.objects.update_or_create(call_datetime=value,additional=another_value,defaults={'additional':another_value}) For db objects which was created before extending Testmodel fetching **kwargs (call_datetime, additional) never fetch old … -
How to save char field line by line using enter keyword into database using django models?
i want to save text field line by line into database using enter keyword. After writing some text if i press enter remainging text should save as next line. How to do this? someone help me. I am using form in django. Form contains charfiled (Text area). -
Sending Email with Image inside the body of the html - Django
I know that there have been questions like this on the site, but none of them have been able to answer my difficulty. So I have the code as following: # custom_methods.py from django.core.mail import EmailMultiAlternatives from django.conf import settings from pathlib import Path from email.mime.image import MIMEImage import threading, random, os class EmailThread(threading.Thread): def __init__(self, subject, body, from_email, recipient_list, fail_silently, html): self.subject = subject self.body = body self.from_email = from_email self.recipient_list = recipient_list self.fail_silently = fail_silently self.html = html threading.Thread.__init__(self) def run(self): msg = EmailMultiAlternatives(self.subject, self.body, self.from_email, self.recipient_list) image_path = os.path.join(settings.BASE_DIR, '/static/images/instagram_icon.png') image_name = Path(image_path).name if self.html: msg.attach_alternative(self.html, "text/html") msg.content_subtype = 'html' msg.mixed_subtype = 'related' with open(image_path, 'rb') as f: image = MIMEImage(f.read()) image.add_header('Content-ID', f"<{image_name}>") msg.attach(image) msg.send(self.fail_silently) def send_mail(subject, recipient_list, body='', from_email=settings.EMAIL_HOST_USER, fail_silently=False, html=None, *args, **kwargs): EmailThread(subject, body, from_email, recipient_list, fail_silently, html).start() # views.py class UserRegisterView(CreateView): model = User form_class = CustomUserCreationForm template_name = 'accounts/register.html' def form_valid(self, form): self.object = form.save(commit=False) self.object.is_active = False self.object.save() send_mail( subject=f'{self.object.code} is your Instagram code', recipient_list=[self.object.email], html=render_to_string('accounts/register_email.html', { 'email':self.object.email, 'code':self.object.code, }) ) return redirect('accounts:login') # register_email.html - This is the html that is connected to the email that will be sent {% load static %} {% load inlinecss %} {% inlinecss "css/email.css" %} … -
Model doesn’t show in admin
I am currently working on a science django blog. I've finished coding it all and I realized that the models items overview and content don't appear in my django.admin. Here's an image so you can see. I know there are other threads related to it. However, I couldn't find the solution in those. Models.py: class Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) content = HTMLField() author = models.ForeignKey(Author, on_delete=models.CASCADE) thumbnail = models.ImageField() categories = models.ManyToManyField(Category) featured = models.BooleanField() previous_post = models.ForeignKey( 'self', related_name='previous', on_delete=models.SET_NULL, blank=True, null=True) next_post = models.ForeignKey( 'self', related_name='next', on_delete=models.SET_NULL, blank=True, null=True) Admin.py: from django.contrib import admin from .models import Author, Category, Post, Comment, PostView # Register your models here. admin.site.register(Author) admin.site.register(Category) admin.site.register(Post) Settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'crispy_forms', 'tinymce', 'marketing', 'posts' ] And urls.py: urlpatterns = [ path('admin/', admin.site.urls), By the way, the models.py is in the app Posts. Just in case somebody needs this information. The other models work perfectly. It’s just the overview and the content -
Nginx config of websockets
I have a problem with my bearle django-private-chat server configuration and websockets. I am getting the following ERR_CONNECTION_TIMED_OUT error: WebSocket connection to 'wss://www.example.me:5002/vzyhorv3hkinr105zh34oab3akgu4685/Chat_with_User failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT Here is my django settings.py: CHAT_WS_SERVER_HOST = 'www.example.me' CHAT_WS_SERVER_PORT = 5002 CHAT_WS_SERVER_PROTOCOL = 'wss' CHAT_WS_CLIENT_HOST = 'www.example.me' CHAT_WS_CLIENT_PORT = 80 CHAT_WS_CLIENT_ROUTE = 'wss/' Here is my nginx (/etc/nginx/sites-available/nginx): server { server_name example.me www.example.me; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/christian/project_mojo/project_mojo; } location /media/ { root /home/christian/project_mojo/project_mojo; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.me/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.me/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.example.me) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = example.me) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name example.me www.example.me; return 404; # managed by Certbot } server { listen [::]:5002; location / { proxy_pass https://example.me; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; } } Nginx -t is okay. However, I am sure that the nginx is not correctly set up. Can anybody … -
django_heroku.settings(locals()) not at the end for collectstatic
I created an webapp with Django, heroku and S3. In production it seems that the upload and urls of my static files are only working when I put in the settings.py the STATIC_URL and STATIC_ROOT after django_heroku.settings(locals()). django_heroku.settings(locals()) STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') So far I understand that django_heroku.settings(locals()) would overwrite my locations with a default value and I was wondering what exaclty happens here and if this is an appropriates solution for production, as django_heroku.settings(locals()) should be actually at then end as far as I know. -
How to retrieve all models data by User id in Django Serializer?
I have following serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id'] class PersonSerializer(serializers.ModelSerializer): user = UserSerializer() comments = CommentSerializer(source='comment_set', many=True) class Meta: model = Person fields = '__all__' And related views class PersonRetrieveView(generics.RetrieveAPIView): queryset = Person.objects.all() serializer_class = PersonSerializer class UserRetrieveView(generics.RetrieveAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (permissions.IsAuthenticated, ) The models are standard, Person related to User by Foreign key. So my url path('persons/<int:pk>/', PersonRetrieveView.as_view()), returns Person object with user field with user id. I want to make kinda reverse logic. By user id I want to query all users with field person with all persons related to this user by user id. I can't just make class UserSerializer(serializers.ModelSerializer): person = PersonSerializer() class Meta: model = User fields = ['id'] because Person serializer defined below the User serializer.