Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Execute Multiple Cursor in Single Function
I want to execute multiple cursor in single function, here's the function in my views.py def index(request): cursor = connection.cursor() cursor.execute('''select count(name) from report sr where is_active=0 group by is_active ''') abcd = cursor.fetchall() connection.close() return render (request, 'index.html',{'abcd':abcd}) I've tried on my own like this but it doesn't seem to work, so please help me out on how to implement this def index(request): cursor = connection.cursor() cursor.execute('''select count(name) from report sr where is_active=0 group by is_active ''') abcd = cursor.fetchall() connection.close() cur = connection.cursor() cur.execute('''select count(name) from report sr where is_active=1 group by is_active ''') abcd = cur.fetchall() connection.close() return render (request, 'index.html',{'abcd':abcd},{'cur':cur}) -
Slug size too large
I tried to deploy my app on heroku, but have following error. Compiled slug size: 869M is too large (max is 500M). I am wondering if i can increase the slug size by chancing Dyno types (ex. change free to standard)? -
Sending header for authentication in the mutation causes error
Using Graphene-Django and Django-Graphql-Jwt, the mutation causes errors with the authentication header. But it works well without the authentication header. class HelloMutation(graphene.Mutation): """Mutation that says hello""" hello = graphene.String() class Arguments: pass @login_required def mutate(self, info): return f'Hello, { info.context.user.username }' -
Django search fields under Createviews
I have datalist like Search field created in django template using ajax autofill with function views. Now I want to work the datalist in Classbased views, It's possible to do in createviews with autofill?? Or can someone give me an idea on how to do?? Thanks I tried using Foregnkey but not totally like a Search field... Datalist in frontend autofill <div class="col-sm-4"> <label>Employee Id</label> <input name="emp_id" id="emp_id" class="form-control" list="emp_list" required> <datalist id="emp_list"> {% for emp_id in elist %} <option data-value="{{ emp_id.Employee_Id }}" | "{{ emp_id.Group }}" value="{{ emp_id.Employee_Id }}"> </option> {% endfor %} </datalist> </div> <div class="col-sm-4"> <label>Group</label> <input type="text" name="group" id="group" class="form-control"> </div> AJAX <script> $('#emp_id').on('change', function () { var value = $('#emp_id').val(); var val = ($('#emp_list [value="' + value + '"]').data('value')); var parts = val.split(" | "); $('#emp_id').val(parts[0]); $('#group').val(parts[1]); }); </script> -
How to raise multiple ValidationError in Django
I saw this post: How to raise multiple ValidationError on Django? However I have some questions. In the accepted answer, andilabs writes: raise ValidationError({ 'field_name_1': ["Field not allowed to change"], 'field_name_2': ["Field not allowed to change"], }) Do the values have to be in a List even though it is just one string? If so, anyone know why? Or where in the documentation it says so? I have not found it in https://docs.djangoproject.com/en/3.0/ref/forms/validation/#raising-multiple-errors. The below code works for me and in my html template I can do {{ form.user.errors }} to have it show up in a div on submission. For who wants to know what context I am using it in, I am using it in a Form view, and inside it I have a def clean(self) method, where I override the parent clean(). Some code for reference: class RegisterForm(forms.Form): user = forms.CharField() **the fields and stuff** def clean(self): error = {} cleaned = super().clean() if 'user' not in cleaned_data: error['user'] = ['Username is empty'] **check if other fields are not there, check password length minimum, etc.** if len(error) != 0: raise ValidationError(error) return cleaned -
django choices in usercreationform
I tried a lot of ways to add a choice field on the registration field, but only the forms.ChoiceField is not showing up. class NewUserForm(UserCreationForm): Choices = (('I', "International"), ('K', "Korean")) EXAMPLE = forms.CharField(max_length=30) you_are = forms.ChoiceField(choices=Choices) class Meta: model = Student fields = ("username", "password1", "password2", "you_are") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) if commit: if user.you_are == "K": user.lang = "KR" user.save() return user Then the EXAMPLE part shows up, but not the you_are part. Are there any problems with my code? Or do I have to use a different way to include forms.ChoiceField? -
Modifying request body according to inputs read from a csv file
I have to read CSV file from AWS S3 bucket say it has 5 columns. Column 1,Column 2,...,Column 5. I have fetched the column names using below code. column_names=[] client = boto3.client('s3', aws_access_key_id = access_key, aws_secret_access_key = secret_access_key) csv_from_aws_s3 = path df = pd.read_csv(path) for col in df.columns: column_names.append(col) print(column_names) Some column details are static and some dynamic. Say (eg Designation)Column1= static & (eg Salary)column2 dynamic. Specified by user input, taken by any UI Text Editor. Now I have to make api-calls to GET and POST static & dynamic part from the csv files and store it in an SQL database. I am using django-rest-api. With some research I came across Requests lib that is suitable for this problem. If I'm missing some information required for this question please mention in comment. -
Having problem in displaying Django messages on HTML template
base.html <body data-spy="scroll" data-target=".navbar"> {% include "navbar.html" %} {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}" role="alert"> {{ message }} </div> {% endfor %} {% endif %} {% block content %} {% endblock %} <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script> </body> settings.py MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage' views.py def login_view(request): form = AuthenticationForm() if request.method == 'POST': form = AuthenticationForm(request, data=request.POST) if form.is_valid(): login(request, form.get_user()) messages.info(request,'登入成功!') return redirect('index') else: messages.error(request,'帳戶無效或密碼錯誤! 請重試!') context = {'form':form} return render(request,'customer/login.html',context) For the login view, I may want to display the error message '帳戶無效或密碼錯誤! 請重試!' if the user entered the incorrect username or password. When I try to enter the incorrect username or password, the error message could not be shown on the template even though I had added {% if messages %} in the base.html. However when I check the code of the template it has been included but do not know why could not be shown with the alert tag so can anyone help me find out what I am missing? -
Connecting ElasticSearch to Django using "django-elasticsearch-dsl" results in ConnectionError when attempting to create/rebuild index
I am trying to call a local ES instance running on docker. I used the following instructions to setup my ES instance: https://www.elastic.co/guide/en/elasticsearch/reference/current/getting-started.html https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html#docker-cli-run-dev-mode I am able to play around with my instance on Kibana at http://0.0.0.0:5601/app/dev_tools#/console. Everything works upto here. Now I am trying to define some sample documents using django models and index them through the library; I am following the instructions here: https://django-elasticsearch-dsl.readthedocs.io/en/latest/quickstart.html#install-and-configure First, I add pip installed and added django_elasticsearch_dsl to INSTALLED_APPS Next, I added in settings.py: ELASTICSEARCH_DSL = { 'default': { 'hosts': 'localhost:9200' }, } Then I create a sample model and document that looks like this: # models.py from django.db import models class Car(models.Model): name = models.CharField(max_length=30) color = models.CharField(max_length=30) description = models.TextField() type = models.IntegerField(choices=[ (1, "Sedan"), (2, "Truck"), (4, "SUV"), ]) # documents.py from django_elasticsearch_dsl import Document from django_elasticsearch_dsl.registries import registry from .models import Car @registry.register_document class CarDocument(Document): class Index: # Name of the Elasticsearch index name = 'cars' # See Elasticsearch Indices API reference for available settings settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Car # The model associated with this Document # The fields of the model you want to be indexed in Elasticsearch fields = [ … -
Docker python:3.9.10-slim-buster image can not install backports.zoneinfo using pip
I have tried Containerising an django project. I was using python:alpine image. The app needed backports.zoneinfo to be installed as requirement. While running pip install -r requirements.txt its showing error when it try to install the backports.zoneinfo. requirements.txt asgiref==3.5.0 backports.zoneinfo==0.2.1 Django==4.0.2 sqlparse==0.4.2 Then I have opened docker container in interactive mode and tried pip install backports.zoneinfo. There also its showing same error. I have tried the same commands in python:3.9.10 image. It was working fine and the package got installed. This error can be reproduced using any of slim, alpine images. I have went through couple of fixes. But it wasn't working. Few of the fixes that I have tried are given below. I have tried these inside the container. pip upgrade pip upgrade wheel apt/apk install gcc apt/apk install gzdata pip install python-dev-tools apt/apk install gcc-c++ To reproduce the error Command docker pull python:alpine docker run -it python:alpine sh pip install backports.zoneinfo Error Collecting backports.zoneinfo Downloading backports.zoneinfo-0.2.1.tar.gz (74 kB) |████████████████████████████████| 74 kB 692 kB/s Installing build dependencies ... done Getting requirements to build wheel ... done Preparing wheel metadata ... done Building wheels for collected packages: backports.zoneinfo Building wheel for backports.zoneinfo (PEP 517) ... error ERROR: Command errored out … -
Associate user by email
I want to override the pipeline to associate user's with their email for accounts that are only active. But I need the backend for a regular login. settings.py AUTHENTICATION_BACKENDS = ['social_core.backends.google.GoogleOAuth2','django.contrib.auth.backends.AllowAllUsersModelBackend',] # Extends default user with additional fields AUTH_USER_MODEL = 'pages.Profile' SOCIAL_AUTH_USER_MODEL = 'pages.Profile' # social auth configs for google SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = config('GOOGLE_OAUTH2_KEY') SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = config('GOOGLE_OAUTH2_SECRET') SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['https://www.googleapis.com/auth/calendar'] SOCIAL_AUTH_JSONFIELD_ENABLED = True SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = {'access_type': 'offline','approval_prompt':'force'} SESSION_COOKIE_SAMESITE = None SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', # <--- enable this one 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'pages.pipeline.save_token' ) views.py def login(request): if request.method == 'POST': form = AuthenticationForm(request.POST) username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user: if user.is_active: auth_login(request, user) return redirect('home') else: messages.error(request,'User blocked',extra_tags='login') return redirect('login') else: messages.error(request,'username or password not correct',extra_tags='login') return redirect('login') else: form = AuthenticationForm() return render(request, 'registration/login.html',{'form':form}) -
Display different data based on name (Django)
I'm making an online food delivery website using Django. I have this table showing each restaurant's name and business hours. If the user clicks the restaurant's name, I want the new page to display the menu of the restaurant. How do I do this? Below is my code for models.py class Restaurant(models.Model): photo = models.ImageField(upload_to="images/") name = models.CharField(max_length=50, primary_key=True) phone = models.CharField(max_length=15) hours = models.CharField(max_length=100) website = models.TextField() category = models.CharField(max_length=20) def __str__(self): return self.name class Menu(models.Model): restaurant_name = models.CharField(max_length=50) item = models.CharField(max_length=20, default='item') price = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.item Below is my code for menu.html <div class="container"> <table class="table text-center"> <thead> <tr> <th scope="col">Item</th> <th scope="col">Price</th> <th scope="col">Add to Cart</th> </tr> </tr> </thead> <tbody> <tr> <td> {{ }} </td> <td>$ {{ }}</td> <td><button class="btn">Add</button></td> </tr> </tbody> </table> </div> -
How to save user preferences without logging user in flutter app
I am working on a flutter app that requires some user data to be saved on server side. But I don't want user to log in using username/password or any social account. Is there a way in flutter to identify the user/device without explicit login ? There seems to be a anonymous login using Firebase but I am looking for a generic solution without any specific backend. I am using Django as my backend. -
Django i18n using a translation from django.contrib module instead of LOCALE_PATHS file
My Django 3.2.9 project displays a translation of both _('Active') and {% translate 'Active' %} that comes from one of Django's modules instead of my application registration. However, other translations from registrations are properly used. By temporarily moving the locale directory outside of the application directory, I confirmed that not only LOCALE_PATHS is correctly set, but also used. Reordering my INSTALLED_APPS also does not change anything. Django seems to insist to use a translation from one of its modules instead from the one in LOCALE_PATHS. The translation in the file looks standard: #: .\registration\templates\users.html:109 #: .\registration\templates\list.html:34 .\registration\views.py:687 msgid "Active" msgstr "XXX" My settings look as follows: BASE_DIR = Path(__file__).resolve().parent.parent LOCALE_PATHS = [ BASE_DIR / 'registration' / 'locale', BASE_DIR / 'administration' / 'locale', ] I confirmed that the path is correct and contains django.po and django.mo in LC_MESSAGES under the language's code directory. As noted above, other translations work correctly. Why does Django use its own version, even though mine is in LOCALE_PATHS and, after changing settings, at the front of INSTALLED_APPS? How can I ensure that Django uses my version? -
Cant login in django when RLS is enabled in the user model?
I have a multi-tenant django application where I've enable Row Level Security using Postgres. Each table has a tenant_id column. I am able to do RLS on the tables using the following postgres policy CREATE POLICY {policy_name} ON "{table_name}" USING (tenant_id::TEXT = current_setting('rls.tenant_id'));" and a middleware from django.utils.deprecation import MiddlewareMixin from django.db import connection class RLSMiddleware(MiddlewareMixin): def process_view(self, request, **kwargs): with connection.cursor() as cur: cur.execute("""select set_config('rls.tenant_id', %(value)s, false)""", dict(value=request.user.pk)) Now when I enable this to the django user model, I'm can't login since the tenant in the current_setting isn't set. But I need to login to set the current_setting. Any work around for this? Can I maybe disable the RLS when in the login page? -
SQL raw to Django query
Can someone help me to change the following query to Django a query so that I use it in my views.py? select onhold_hour, onhold_date, clinic_id, hospital_id, region_id hospital_name, clinic, (select string_agg(clinic, ', ') as other_clinics from hospitals_core_clinic inner join hospitals_core_schedule on hospitals_core_clinic.id = hospitals_core_schedule.clinic_id where hospital_id = 263 and onhold_date = '2022-02-27') from hospitals_core_schedule inner join hospitals_core_clinic on hospitals_core_schedule.clinic_id = hospitals_core_clinic.id inner join hospitals_core_hospital on hospitals_core_schedule.hospital_id = hospitals_core_hospital.id and hospital_id = 263 and onhold_date = '2022-02-27' The onhold_date and the hospital_id will be custom variables My models.py are the following: class Region(models.Model): region = models.CharField(max_length=100, unique=True) region_display = models.CharField(max_length=100, unique=True, null=True) slug = models.SlugField(max_length=255, unique=False, null=True) def __str__(self): return self.region def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(unidecode(self.region)) super(Region, self).save(*args, **kwargs) class Hospital(models.Model): hospital_name = models.CharField(max_length=100, unique=True, blank=True, null=True) actual_name = models.CharField(max_length=100, unique=True, blank=True, null=True) #hospital_address = models.CharField(max_length=100, unique=False, blank=True, null=True) #hospital_phone = slug = models.SlugField(max_length=255, unique=False, null=True) def __str__(self): return self.hospital_name def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(unidecode(self.hospital_name)) super(Hospital, self).save(*args, **kwargs) class Clinic(models.Model): clinic = models.CharField(max_length=100, unique=True, blank=True, null=True) clinic_display = models.CharField(max_length=100, unique=True, blank=True, null=True) slug = models.SlugField(max_length=255, unique=False, null=True) def __str__(self): return self.clinic def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(unidecode(self.clinic)) … -
how to retrieve in a sql many to many relationships query all the instances a user is involved with
How can I retrieve all the instances a user is part of in a Many to Many relationship in SQL. (PostgreSQL) I have the following table using django: models.py ... from django.contrib.auth import get_user_model ... User = get_user_model() class Member(models.Model): ... member = models.ManyToManyField(User, related_name="membership") status = models.CharField(max_length=20, choices=STATUS) created = models.DateTimeField(auto_now_add=True) query user = User.objects.get(id=1) user.membership.all() # result => give me all instances where user 1 is associated in Member table What would be the equivalent in sql of the above django query? Any help would be much appreciated -
How to get rid of "%20Profile" in URL Pattern
First, I will search up the user, and then it takes me to a page of a list of users to click onto. After that, when I choose a user I want to click on to check out their profile, it should take me to users page I want to see, but that is where I have a problem. The URL pattern should be, for example /user/MatthewRond/, but instead, I get /user/MatthewRond%20Profile/, which prevents me from seeing Matthew's page because %20Profile was never intended to be in the URL. If I can figure out how to get rid of the %20Profile, my problem should be solved. I read up on what %20 was and what I got from it: it has to do with using and dealing with alphanumeric characters. Regardless none of it helped me figure out how to remove it. As for the code part of it, I am grabbing the default username from the database then grabbing the custom profile I made from that default user. After that, I set the username to the custom profile model I made. I don't believe it is an error with my views, maybe my templates or URLs. views.py def profile_view(request, … -
graphene.Field() with filter() and graphene.List() with get() return errors (Graphene Django)
<Case 1> I used "graphene.Field()" with "get()" and "graphene.List()" with "filter()" to get one specific object. "graphene.Field()" with "get()" in schema.py: import graphene from graphene_django import DjangoObjectType from .models import Category class CategoryType(DjangoObjectType): class Meta: model = Category fields = ("id","name") all_categories = graphene.Field(CategoryType, id=graphene.Int()) # graphene.Field() def resolve_all_categories(root, info, id): return Category.objects.get(pk=id) # get() schema = graphene.Schema(query=Query) "graphene.List()" with "filter()" in schema.py: import graphene from graphene_django import DjangoObjectType from .models import Category class CategoryType(DjangoObjectType): class Meta: model = Category fields = ("id","name") all_categories = graphene.List(CategoryType, id=graphene.Int()) # graphene.List() def resolve_all_categories(root, info, id): return Category.objects.filter(pk=id) # filter() schema = graphene.Schema(query=Query) Then, I queried "allCategories" for both code in schema.py above one by one: query { allCategories(id:1) { id name } } Finally, I got this result without error for "graphene.Field()" with "get()" in schema.py: { "data": { "allCategories": { "id": "1", "name": "category1" } } } And this result without error for "graphene.List()" with "filter()" in schema.py: { "data": { "allCategories": [ { "id": "1", "name": "category1" } ] } } <Case 2> Next, I used "graphene.Field()" with "filter()" and "graphene.List()" with "get()" to get one specific object. "graphene.Field()" with "filter()" in schema.py: import graphene from graphene_django import DjangoObjectType from … -
Django serializer how to serialize a foreign key field
This is my models.py class AuthorModel(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) host = models.CharField(max_length=200, default=settings.HOST_URL) displayName = models.CharField(max_length=200) github = models.CharField(max_length=200) profileImage = models.CharField(max_length=200) class PostModel(models.Model): title = models.CharField(max_length=200) id = models.CharField(max_length=200, primary_key=True) source = models.CharField(max_length=200, blank=True) origin = models.CharField(max_length=200, blank=True) description = models.CharField(max_length=200) contentType = models.CharField(max_length=200) content = models.CharField(max_length=2000) author = models.ForeignKey(AuthorModel, related_name=("post"), on_delete=models.CASCADE, null=True) categories = models.CharField(max_length=200) count = models.IntegerField(blank=True, null=True) comments = models.CharField(max_length=200, blank=True) published = models.DateTimeField(auto_now=True) visibility = models.CharField(max_length=200) unlisted = models.BooleanField() This is my views.py @api_view(['POST']) def create_post(request): """ Create a new Post """ if request.method == 'POST': serializer = PostSerializer(data=request.data) print("api received request data: ",request.data) if serializer.is_valid(raise_exception=True): author_object = AuthorModel.objects.get(id=request.data['author']) serializer.author = author_object serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is my serializers.py class AuthorSerializer(serializers.ModelSerializer): class Meta: model = AuthorModel fields = ['id', 'host', 'displayName', 'github', 'profileImage'] class PostSerializer(serializers.ModelSerializer): author = AuthorSerializer(many=True, read_only=True) class Meta: # TODO commentsSrc model = PostModel fields = ['title', 'id', 'source', 'origin', 'description', 'contentType','content','author','categories','count','comments','published','visibility','unlisted'] and finally my html {% extends 'base.html' %} {% block title %} Create Post {% endblock %} {% block content %} <div class="card" style="margin:10px"> <h2 style="margin: 10px 10px 0">Create A New Post</h2> <form action="{% url 'createpost' %}" method="post" id="post_form"> {% … -
Why does my Django query from Postgres database return the query set in reverse order
I have a model called "Step" that is connected to a learning guide through a foreign key. In my views.py file I am simply querying the steps using this learning_guides_steps = learning_guide.step_set.all() and in the templates I am just looping through the steps using a for loop and displaying the title of the steps like this {%for step in learning_guides_steps%} <div class="entire_step"> <!-- Displaying the title of the step with an angle down button beside the title --> <div class = "btn-group step" > <a href = "#" class = "btn stepname" role = "button" style = "font-size: 18px;"> {{forloop.counter}}. {{step.title}}</a> </div> </div> However when I display it in website its printing in reversed order. Can anyone explain why this is happening and how I can fix this? I am new to Django and Postgres, so any help would be appreciate it. Thank you. My Step model and the views is given below class Step(models.Model): title = models.CharField(max_length=200, null=False) step_description = models.TextField(max_length=1000, null=False) # enforces one-to-many relationship between LearningGuide and Step. # Deleting a LearningGuide deletes all the associated steps (CASCADE delete) learning_guide = models.ForeignKey(LearningGuide, on_delete=models.CASCADE) My views.py file: learning_guide = LearningGuide.objects.get(pk=learning_guide_id) learning_guides_indicators = learning_guide.indicators.all() indicators = Indicator.objects.all() learning_guides_steps = … -
Foreign key columns and parent model
I have a model like this class Order(models.Model): product = models.ForeignKey(Product, on_delete=models.DO_NOTHING) In the product model, I save the price of that product, but from time to time the price may change. I want when the order is completed and I want to change the product price of that sold product not update the price of the product that is sold in that order. So, the price change should be affected only new orders. Thanks in advance! -
nginx deployment issues on aws alb host not found
error am getting in my web server container 2022-02-26 23:02:312022/02/26 22:02:31 [notice] 22#22: exiting 2022-02-26 23:00:432022/02/26 22:00:43 [error] 23#23: *13 django_web could not be resolved (3: Host not found), client: 10.0.1.89, server: enum-ops-staging.enum.africa, request: "GET / HTTP/1.1", host: "10.0.1.68" 2022-02-26 23:00:4310.0.1.89 - - [26/Feb/2022:22:00:43 +0000] "GET / HTTP/1.1" 502 157 "-" "ELB-HealthChecker/2.0" "-" 2022-02-26 23:00:432022/02/26 22:00:43 [error] 23#23: *12 django_web could not be resolved (3: Host not found), client: 10.0.0.59, server: enum-ops-staging.enum.africa, request: "GET / HTTP/1.1", host: "10.0.1.68" 2022-02-26 23:00:4310.0.0.59 - - [26/Feb/2022:22:00:43 +0000] "GET / HTTP/1.1" 502 157 "-" "ELB-HealthChecker/2.0" "-" my nginx.conf file server { listen 80; server_name enum-ops-staging.enum.africa; location / { resolver 10.0.0.2 valid=300s; set $backend http://django_web:8000; proxy_pass $backend; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static { alias /usr/src/app/enumops/static; } location /media { alias /usr/src/app/enumops/media; } } tried a lot of suggestions but none seems to be working. Please any suggestions or help, thanks in advance?? -
How to access an object's fields and manipulate them when using pre_delete?
I have a foreign key in the model and I want to change a field's value in that object when pre_delete is called. I'm new to this concept and just found out that you use a pre delete signal like this: @receiver(pre_delete, sender=MyModel) def bid_deletion(sender, instance, using, **kwargs): pass What should I write to use the foreign key object's field? -
Django annotate() is not adding up the number of entries but is instead repeating them
Background: The Amazon Kindle PaperWhite stores the words we lookup while reading into a sqlite3 database called vocab.db. I am working on a small kindle companion app that takes this db file and imports it into a django table for various processing. I have done this step already. What I would like to do: I would like to query my table KindleLookups for my most difficult words (ex: how many times have I looked up a specific word). I would ultimately like to present this data in a table ordered by highest count. Desired Result: Word Lookup Count Reverberated 3 Troubadour 1 Corrugated 1 My result (undesired): Here Reverberated is being repeated three times each with a lookup count of one, instead of one time with three lookup count. Word Lookup Count Reverberated 1 Reverberated 1 Reverberated 1 Troubadour 1 Corrugated 1 Model: class KindleLookups(TimeStampedModel): book = models.ForeignKey(KindleBookInfo, on_delete=models.CASCADE) word = models.ForeignKey(KindleWords, on_delete=models.CASCADE) ... class KindleWords(TimeStampedModel): word_key = models.CharField(max_length=255, unique=True) word = models.CharField(max_length=255) ... I am trying to accomplish this using annotate(), but this is repeating the rows instead of adding them up for some reason. context['lookup_counts'] = KindleLookups.objects.annotate(word_count=Count("word")) I then thought that I needed to annotate on the actual …