Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Expression expected.javascript error. The error is in the if statement and there are some errors in the terminal. Need assistance
//This is the JS Code for the Checkout page in a HTML File <script> document.getElementById('cart').innerHTML = sum; $('#itemsJson').val(JSON.stringify(cart)); //If order is placed then confirm the order with an ID {% if thank %} alert('Thanks for ordering with us. Your order id is {{id}}. Use it to track your order using our order tracker') localStorage.clear(); document.location = "/shop"; {% endif %} </script> -
Django - Can't send Whatsapp message in production mode
I am developing an app that should send msg by WhatsApp using pywhatkit. Running from Django Development Server works fine, but from Xampp it doesn't, I even tried opening whatsapp from the url directly in the project and it doesn't work either. Python 3.10.6 Django 3.2.0 def send_whatsapp(telefono, mensaje): try: pywhatkit.sendwhatmsg_instantly(telefono, mensaje, tab_close=True) print("Mensaje enviado") except Exception: print("Error") -
Order queryset based on condition from fields in different table
I have some resources that a user can subscribe to, for added advantages. My challenge is in sorting them, where the resources with subscriptions come first and the rest follow. Initially, the resources were stored like this. from django.db import models from django.utils import timezone class Entity(models.Model): has_subscription = models.BooleanField() created_at = models.DateTimeField(default=timezone.now) # other fields and I would sort them like this, Entity.objects.all()order_by("-has_subscription", "-created_at") which worked. I decided to move to a different way of storing it that would favor a time bound subscription. I came up with this. from django.db import models from django.utils import timezone class Entity(models.Model): created_at = models.DateTimeField(default=timezone.now) @property def has_active_subscription(self): if ( self.entity_subscriptions.filter( start_date__lte=timezone.now(), end_date__gte=timezone.now() ).count() > 0 ): return True return False class Subscriptions(model.Model): entity = models.ForeignKey( Entity, on_delete=models.CASCADE, related_name="entity_subscriptions", related_query_name="entity_subscription", ) start_date = models.DateTimeField() end_date = models.DateTimeField() How can I sort the queryset in such a manner that the resources with subscriptions come first. -
Django form - the same field multiple times
how can I process a form with a field: order = ModelChoiceField( required=False, queryset=OrderOd.objects.filter(Q(status='DN') | Q(status='DI')), widget=Select( attrs={ "class": "form-select form-select-md form-select-solid", "data-control": "select2", "data-multiple": "true", "multiple": "multiple", "data-placeholder": _("Vyberte objednávku ..."), "id": 'order' } ) ) In front-end, I can select multiple orders (looks like pills/tags) and in the request sent to the server it looks like this: movement: f2b7c234-fbdb-4059-bcb6-8ada46cef72c account: dbabefb7-f053-4edf-a2e3-787bf6bfc371 date: 2022-09-12 order: eb2fc726-3e97-4af2-a8b2-08f20771cfef order: 8398925b-fca6-4b25-8c48-e12940a5b5c3 order: bfa35391-5cf8-4ed8-8c44-a797da875cb4 order: 07be93ac-20b3-459c-8038-c8b023db6d66 When I inspect self.data, I got 'order': ['eb2fc726-3e97-4af2-a8b2-08f20771cfef', '8398925b-fca6-4b25-8c48-e12940a5b5c3', 'bfa35391-5cf8-4ed8-8c44-a797da875cb4', '07be93ac-20b3-459c-8038-c8b023db6d66'], but when I check the output of logger.info(self.data['order']), it gives me only the first UUID. [INFO] form.py 123: 07be93ac-20b3-459c-8038-c8b023db6d66 What I need is to access all UUIDs in the array (order) and process them instance by instance. Any idea, how to do it? Thanks -
Django: How to filter obejects in django?
I simply want to filter the most popular videos based on the views. So in the Model there is a field called views = models.IntegerField(default=0). now videos can have views like 10 42, 65, 2. So what i want to do is simply NOT filter by newest to oldest by highest number of views to the lowest number. What is the best way to achieve this? def Videos: videos = Video.objects.filter(user=channel.user, visibility="public") models.py class Video(models.Model): ... views = models.PositiveIntegerField(default=0) -
Xcode Preview not showing
I was following a YouTube tutorial about how to connect my django backend to Swift and when I finished following along, I just get a blank grey area where the phone preview should be. Anyone know why this would happen? Here's my Model file and my View. import Foundation struct Account: Codable, Hashable { var email: String var username: String var first_name: String var last_name: String var is_venue: Bool var date_joined: Date var last_login: Date var is_active: Bool var is_admin: Bool var is_superuser: Bool } And View import SwiftUI struct AccountView: View { @State var accounts = [Account]() var body: some View { ForEach(accounts, id: \.self) {item in HStack { Text(item.first_name) } }.onAppear(perform: loadAccount) } func loadAccount() { guard let url = URL(string: "http://127.0.0.1:8000/api/account/") // URL is the endpoint of API else { print("API is down") return } var request = URLRequest(url: url) request.httpMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("Basic amZsb3JlbmNlMEBnbWFpbC5jb206QmEka2V0YmExMUZsMEppbW15ITEh", forHTTPHeaderField: "Authorization") URLSession.shared.dataTask(with: request) { data, response, error in if let data = data { if let response = try? JSONDecoder().decode([Account].self, from: data) { DispatchQueue.main.async { self.accounts = response } return } } }.resume() } } struct AccountView_Previews: PreviewProvider { static var previews: some View { AccountView() } } -
How to create a charfield with suggestions in django forms?
I want to create a charfield input in a django form that has suggestions. Essentially I want a choice field that also allows you to write your own value if needed. In other words a hybrid between a charfield and choice field input. Any suggestions on how to achieve this ? class PDFClassificationForm(forms.ModelForm): nature = forms.CharField(required=False) class Meta: model = Documents fields = [, 'nature',] labels = {,, 'nature':'Nature/Concerne:', } widgets = { 'dateenvoi' : DatePickerInput(), } def __init__(self, uuid_pdf, *args, **kwargs): super(PDFClassificationForm, self).__init__(*args, **kwargs) if Documents.objects.get(uuid=uuid_pdf).id_emetteur: nature_choices= Archivagerecurrencelibelle.objects.filter(Q(id_emetteur=Documents.objects.get(uuid=uuid_pdf).id_emetteur) & Q(source="Nature")).values_list('concerne','concerne') self.fields['nature'].choices = nature_choices -
Python requests
Can we consume an API, for example use the POST method to retrieve products. Note that we pass the security key in the body or data. it's possible ?? def api(request): url = 'https://datausa.io/api/data?product' x = requests.post(url,data={'securityKey':'valueKey') contenu=x.text return HttpResponse(contenu) -
how to use the ajax in django and how to avoid this kind of errors?
I am trying to use the ajax in my django application, but its not working. I cannot find that my codes are working or not. python or django did not show any error, but javascript showing some kind of error. I will provide my code and its error here, if my code is wrong, please give me the correct code. html form <form> <input type = "text" name = "user" id = "user"><br> <span id = "mess"></span><br> </form><br> ajax in html {% block javascript %} <script> $(document).ready(function() { $('#user').keyup(function() { let a = $('#user').val(); $.ajax({ url: '{% url "username" %}', type: "POST", data: {a: a}, // on success success: function (response) { if (response == true) { $('#mess').html("username is not available"); alert(response); } else { $('#mess').html("username is available"); alert(response); } } }); }); }); </script> {% endblock javascript %} urls.py path path('username', views.username, name = 'username'), views.py function def username(request): if request.is_ajax(): user = request.POST['a'] response = signup.objects.filter(user = user) # return JsonResponse(response) return HttpResponse(response) error username?a=enteredword:1 Request unavailable in the network panel, try reloading the inspected page Failed to load resource: the server responded with a status of 500 (Internal Server Error) Warning DevTools failed to load source map: … -
How to display the latest modified record first in python
How to display the all records but latest modified one needs to be displayed in first how we can do in python Here is my views.py def getHoto(request): Userdata=hototable.objects.filter(status=open) If request.method=='GET' Ser=addhotoSerializer(userdata,many=True) return jsonResponce (list(Ser.data)[::-1],safe=False) -
How to run custom django-admin commands as a cron job in docker?
I have a django-app sample. In this app I have created a file test.py and wrote my custom commands in it as mentioned in the django official documentation sample/ __init__.py models.py management/ __init__.py commands/ __init__.py test.py views.py test.py: from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): # Sample content print("Hello World") I had run the command python manage.py test and it is working. What I need is that I want to run this command as a cron job in docker. I had tried this, created a cron file hello-cron. hello-cron: * * * * * root python /home/manage.py test >> /home/cron.log 2>&1 # Empty line Dockerfile: FROM python:3.10.6 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /home COPY requirements.txt /home/ RUN pip install -r requirements.txt COPY . /home/ RUN apt-get update && apt-get -y install cron COPY hello-cron /home/hello-cron RUN chmod 0644 /home/hello-cron RUN chmod 0744 /home/sample/management/commands/test.py RUN crontab /home/hello-cron RUN touch /home/cron.log CMD cron && tail -f /home/cron.log docker-compose.yml: version: "3.9" services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: restart: always build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/home ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - … -
Django Model with Oracle Database returns Error: ORA-00904 invalid identifier
i try to connect two database tables with a foreign key and i get the error ORA-00904: "A"."A_NR_ID": invalid identifier for the model: class A(models.Model): id = models.IntegerField(primary_key=True) a_nr = models.ForeignKey(B, models.DO_NOTHING) --> #anr = models.ForeignKey(B, models.DO_NOTHING, db_column="a_nr") f_b = models.CharField(max_length=1) ... class B(models.Model): id = models.IntegerField(primary_key=True) ... If i replace a_nr with the comment-line anr it works. And i have no idea why, since the name only uses single underscore. Also the column f_b seems to work perfectly fine. If i then run "makemigrations" it trys to delete the column a_nr and create anr, which also makes no sense to me, since i thought db_column="a_nr" would keep the actuall name in the oracle database the same. The second error is: ORA-00904: "D"."BEZEICHNUNG_ID": invalid identifier for the model: class C(models.Model): id = models.IntegerField(primary_key=True) bezeichnung = models.CharField() class D(models.Model): id = models.IntegerField(primary_key=True) bezeichnung = models.ForeignKey(C, models.DO_NOTHING) ... And here i can't figure out what's wrong. -
Django,based on model consecutive field value difference update new field value in same row
I'm trying to set stay column field value in TestLocation model table as stay or on_move by calculating difference between lat and longs using for loop to iterate between rows of model table and if condition where to set value of stay field as stay or on_move which depends on difference as shown in views.py. below is my model.py: class TestLocation(models.Model): LOCATOR_YES_NO_CHOICES = ((None, ""), (True, "Yes"), (False, "No")) longitude = models.FloatField() latitude = models.FloatField() processed = models.BooleanField( choices=LOCATOR_YES_NO_CHOICES, max_length=3, blank=True, null=True, default=None, ) stay=models.CharField(max_length=100,null=True) duration=models.FloatField(null=True) and views.py funtion to set value of stay field in above model: def mark_stay_location(): if TestLocation.objects.filter(processed=None): k = TestLocation.objects.filter(processed=None).order_by("timestamp") p = len(k) # list_lat1 = [] # list_lat2 = [] # list_long1 = [] # list_long2 = [] for i in range(p - 1): rowpairs = k[i : i + 2] lat1 = rowpairs[0].latitude # list_lat1.append(lat1) lat2 = rowpairs[1].latitude # list_lat2.append(lat2) long1 = rowpairs[0].longitude # list_long1.append(long1) long2 = rowpairs[1].longitude # list_long2.append(long2) lat = abs(lat2 - lat1) long = abs(long2 - long1) a = sin(lat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(long / 2) ** 2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) for rowpair in rowpairs: row_id = rowpair.id po … -
the "Children" of nested files
I'm doing a project (on Django REST Framework) dedicated to file storage. The project structure assumes that folders can be nested in other folders. And files can be nested in folders. I have prescribed the logic of the file link to the folder in which it is uploaded. However, I need that when I request the service via the API, I am given another field that includes the data of all subfolders and files (the "children") field. My model.py file: FILE='FILE' FOLDER='FOLDER' TYPE_CHOICES = [(FILE,"FILE"),(FOLDER,"FOLDER")] class Folder(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) parent_id = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) type = models.CharField(max_length=255, choices=TYPE_CHOICES, editable=False, default='FOLDER') name = models.CharField(max_length=255) # size = models.IntegerField(blank=True, null=True, default = 0) date = models.DateField(auto_now=True) class File(models.Model): type = models.CharField(max_length=255, choices=TYPE_CHOICES, editable=False, default='FILE') id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) file = models.FileField(null=True, max_length=255) date = models.DateTimeField(auto_now =True) # user = models.ForeignKey(User, on_delete=models.CASCADE) parentId = models.ForeignKey(Folder, on_delete=models.CASCADE) def __str__(self): return str(self.file.name) -
How to filter related objects after a search in django-filter?
I use django-filter on my website to search for books. The filter includes the following fields: book genre, language in which the book is written, publication date, and search field. The search looks for multiple fields in the database, including the book title, authors of the book, etc. The filter works fine, but I don't understand how to make it so that when I search for a book after getting the search result, I will remove the fields that are not related to the result (i.e. genres, language) For example, I want to find books about Harry Potter. After I entered the book title in the search result and associated fields, that is, I see that the site is not related to the book about Harry Potter Chinese (it was removed after the result). The second question - is it possible to make so that after the search I would see how many objects are in each field? That is, if I entered Harry Potter in the search and got a result, I see that there are 5 objects in English. models.py class Book(models.Model): name = models.CharField(max_length=255) author = models.ForeignKey( "Authors", on_delete=models.SET_NULL, null=True, blank=True, ) subject = TreeManyToManyField("Subject") published_date = … -
Django get each item from queryset
I just dont know how to do it. I want to filter my queryset by all dates, and ints and everything else. Everywhere I look is not working for me. @property def mathe2(self): l = [self.lehrertabelle_set.all()] for i in l: l.append(i.Stunden) Stunden is just an int. I want them in a list to comapare with something else. I mean when I can do this in template why not as property -
offset and limit in django rest framework
I've set the offset and limit in the query. like this. queryset = Comments.objects.filter(language_post_id=post_in_lang_id, is_post_comment=True).order_by("-created_on")[offset:offset+limit] # 2 : 2 + 2 It is working fine, but in the pagination response, I'm getting the wrong count of the query. { "response": true, "return_code": "success", "result": [ { "id": 36, "user_id": 3, "language_post_id": 16, "is_post_comment": false, "parent_post_comment_id": 20, "description": "Comment on post in English!!!!", "created_on": "2022-09-12T07:44:33", " ... " }, { "id": 35, "user_id": 4, "language_post_id": 16, "is_post_comment": false, "parent_post_comment_id": 20, "description": "Comment on post in English!!!!", "created_on": "2022-09-12T07:44:32", " ... " } ], "message": "Success", "next": null, "previous": null, "count": 2 } but I got the "count": 2 it should be the number of all rows. and also one more doubt. I'm trying to do like whenever we are getting data query_set every time the database should fire the query according to limit and offset. So I made it possible through costume [offset:limit]. it looks hardcoded. Is there any better way to make it soft? Dose DRF pagination work the same as I'm trying to do? -
I am trying to register new user from Django to PostgreSQL from the app which I created but it is not getting updated in database
I am trying to register new user from Django to PostgreSQL from the app which I created but it is not getting updated in database, but logs are getting generated in PostgreSQL for my each attempts from Django framework and the database table screenshot has been attached here. I also noticed Django.contrib import error but I think it is not problem because rest all codes working fine like I am able to upload photos from admin panel and it is reflecting in my web portal and database as well. .............................................. #accounts\views.py. from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.models import User, auth # Create your views here. def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username,password=password) if user is not None: auth.login(request, user) return redirect("/") else: messages.info(request,'invalid creds') return redirect('login') else: return render(request,'login.html') def register(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] password1 = request.POST['password1'] password2 = request.POST['password2'] email = request.POST['email'] if password1==password2: if User.objects.filter(username=username).exists(): messages.info(request,'Username Taken') return redirect('register') elif User.objects.filter(email=email).exists(): messages.info(request,'Email taken') return redirect('register') else: user = User.objects.create_user(username=username,password=password1,email=email,first_name=first_name,last_name=last_name) user.save() messages.info(request,'User created') return redirect('login') else: messages.info(request,'Password not matching') return redirect('register') return redirect('/') else: return render(request,'register.html') … -
How to annotate integer as a ForeignKey in django?
I have this model: class Order(Model): sale_address = ForeignKey(Address) purchase_address = ForeignKey(Address) and want to conditionally annotate one address or another depending on some condition, as a ForeignKey: order = Order.objects.annotate( address=... # sale_address if current user is seller ).first() assert isinstance(order.address, Address) # True How can I do that? I've tried this: annotate( address_id=Case( When( user_role='SELLER', then=F('sale_address'), ), When( user_role='BUYER', then=F('purchase_address'), ), ), ) but in this case address_id is just an integer and I get N+1 issues when making list of orders with address.region. -
Extract body values from Django request in Django middleware
I want to extract the body part from the request in middleware. The body contains some user-related variables and the second thing file that which the user has uploaded. Code : class DSCheckMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): body_value = request.body resulting_param_value = #some got on values which i am getting from body if "True" in resulting_param_value: return HttpResponse("Please Provide Valid Input!!!") else: response = self.get_response(request) return response I have tried to extract with request.data but it doesn't work in middleware. I have also tried with request.body it works but partially. It gives me values in bytes and the format looks like the below. b'------WebKitFormBoundarym30YxZr7PgRBWRoK\r\nContent-Disposition: form-data; name="user_name"\r\n\r\na\r\n------WebKitFormBoundarym30YxZr7PgRBWRoK\r\nContent-Disposition: form-data; name="dataset_name"\r\n\r\nc\r\n------WebKitFormBoundarym30YxZr7PgRBWRoK\r\nContent-Disposition: form-data; name="project_name"\r\n\r\nc\r\n------WebKitFormBoundarym30YxZr7PgRBWRoK\r\nContent-Disposition: form-data; name="description"\r\n\r\nc\r\n------WebKitFormBoundarym30YxZr7PgRBWRoK\r\nContent-Disposition: form-data; name="dataset_description"\r\n\r\nc\r\n------WebKitFormBoundarym30YxZr7PgRBWRoK\r\nContent-Disposition: form-data; name="model_type"\r\n\r\nRegression\r\n------WebKitFormBoundarym30YxZr7PgRBWRoK\r\nContent-Disposition: form-data; name="visibility"\r\n\r\nprivate\r\n------WebKitFormBoundarym30YxZr7PgRBWRoK\r\nContent-Disposition: form-data; name="inputfile"; filename="CarPrice_Assignment.zip"\r\nContent-Type: application/octet-stream\r\n\r\nPK\x03\x04\n\x00\x08\x00\x08\x00\xbap)U\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x17\x00\x00\x00CarPrice_Assignment.csv\xbd]Ko\xe3\xc6\xb2\xde\x07\xc8\x7f\xe02\x018F\xbf\x1f\xebs6gq\x0ep\x17\xf7\xe2\xee.h\x89\x96\x19\xd3\xa2@R\xf6x~\xfd\xad\xaa\xe6\xab%J$\x95I\x80$\xf0Ll}_WWW\xd7\xb3\xbd\xcb\xea\xff\xfb\xd7?\xd3\xe6\xeb\xfd\xb9*\x8b\xe3!\xfdGV\xff\'{\xcf\xd3\x97s^\xb6_\xa7<\xcd\x9aSQgmQ\x1d\xd3}U\xd5\xc7\xf3\xfbs^\xa7\xbb\xac~\xae\xf6_\xe9\xbe.>\xf2\xcf\xd7</\xd3\xfcx(\x8eyY\xed\xc27\xd3_>gM\x8e\xdf[\xc2\xffl_\xf1\xab\xcfb\x1f\xbex\xcd\x8b\xc3k\x9b\xee\xce\xf5\xf3g\xf82|\x00\x81\xee\xbe\x80\xcc>\xef\xd1\xc2\xffi\x8a\x1f\x81W\xf3\xd5\xb4\xf9{\xfa\\\xd591K\x9b\xb6\xae\xde\xe0\xa7\xaa\xf7S\x9d7\r\xc0\x87\xbf\x7f\xad\xea&?U\x9f\xf0\x11\xa7<{\xabO\xef\xe9\xaeh\xbf\xdeO\x87\xf4\x15 ?3\xfa\xf2T\x17\xbb\xfc\xd7_x*\xd3\xac|\xc9\xbe\xd5\xd5{^W\xc9\xa18\x97E\x96\x1e\xb2\x06>\x7f\x9f\xb6\x9f\x15\x00\x1c?\xf2\xba-\x9e\xcb<\xad?\xf7\xe9K]\x1d\xdb\xd4\xb9\'\x93r\xe3\x9e\\j\xd4\x13O\x15~%\xb4r \xb0\xd7]\xfaR\x9d\xeb\x94K\x96\xbe\x9f^\x8aT>)\x9b\x8a\'\xe3R\x9fr\xceS\xcd\x18K\x05O\x85\x85\xefQ^\xff\xfa\x8b\xb8\xe0\x01k-?' I have also tried to convert it using JSON but it give error like 'utf-8' codec can't decode byte 0xe7 in position 894: invalid continuation byte -
How do I call this function on a button press?
problem here is I want Student to be deleted everytime this delete button is pressed and refresh page/stay on current page, I am stuck with this problem, any solution? <div class="content"> {% for student in students %} <p class= 'my-2 text-center'> {{student.name}} | {{student.bio}} <button type="button" class="btn btn-danger">Delete</button> </p> {% endfor %} </div> -
Setting an option that can only be viewed by users in a certain group
I am quite new to django and am building a project using django and python predominantly. I have two user groups in djangos admin panel created and defined there with user added through this admin panel; Diving_Officers and Club_Members In my webpage, i have an option that i want to only be visible or even clickable to the users in one group, the Diving_Officers group. I cannot find any specific information for how to call a group that exists in django admin and assign it permissions or how to limit a view to it. -
Django/Wagtail Model Admin fields not showing in API
I am using wagtail and I have a ModelAdmin called sorting. I have a PageChooserPanel inside the ModelAdmin. I have exposed these in API but it's showing only id of the table but not showing full details. But in my database, I can view them. API Response Models screenshot Here is my `views.py class FeaturedList(APIView): def get(self, request): featured =Featured.objects.all() serializer= FeaturedSerializer(featured, many = True) return Response(serializer.data) serializers.py class FeaturedSerializer(serializers.ModelSerializer): class Meta: model = Featured fields = ("featured_name","featured_pages",) models.py from django.db import models from wagtail.models import Page, Orderable from modelcluster.fields import ParentalKey from blog.models import * from wagtail.models import Page from wagtail.admin.panels import PageChooserPanel, FieldPanel, InlinePanel from django.utils.translation import gettext_lazy as _ from modelcluster.models import ClusterableModel from modelcluster.fields import ParentalManyToManyField class IDChoice(models.IntegerChoices): Featured1 = 0, _('Featured1') Featured2 = 1, _('Featured2') Featured3 = 2, _('Featured3') Featured4 = 3, _('Featured4') Featured5 = 4, _('Featured5') class Featured(ClusterableModel): featured_name = models.IntegerField(default=IDChoice.Featured1,choices=IDChoice.choices, blank=True, null=False, help_text='Featured ID', unique=True) panels = [ InlinePanel('featured_pages', label="Featured pages"), FieldPanel('featured_name'), ] class FeaturedPages(Orderable, models.Model): """ Orderable helper class, and what amounts to a ForeignKey link to the model we want to add featured pages to (Featured) """ featured_page = models.ForeignKey( 'wagtailcore.Page', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) featured_item = ParentalKey( Featured, related_name='featured_pages', … -
How to properly set up custom User model and multiple databases with Django?
I created a custom application to authenticate users and have hard times to make everything work with multiple databases. Help would be much appreciated. Basically, I create multiple Django projects and want a unique database for authentication and a custom AUTH_USER_MODEL. The databases are declared in settings.py with two routers, one for the auth, contenttypes, and authentication application, and the other router for the rest of the applications. I successfuly migrated the custom User model and created createsuperuser with the option --database=auth_db but then, when I work in the admin section with Celery beat Django throws an error : IntegrityError at /admin/django_celery_beat/crontabschedule/add/ insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_user_id_c564eba6_fk_authentication_user_id" DETAIL: Key (user_id)=(1) is not present in table "authentication_user". As you can see, it says the user with ID 1 isn't created, but I'm logged with it and I'm 100% sure the custom User model was created in the authentication app: root@ec00652b9b9a:/app# python manage.py migrate authentication --database=auth_db Operations to perform: Apply all migrations: authentication Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying authentication.0001_initial... OK root@ec00652b9b9a:/app# python manage.py migrate contenttypes --database=auth_db Operations to perform: Apply all migrations: contenttypes Running migrations: No migrations to apply. root@ec00652b9b9a:/app# python manage.py … -
Django Is the server running on host "localhost" (127.0.0.1) and accepting web | TCP/IP connections on port 5432?
I am trying to dockerize my Django application. My configs are the following: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'DB_NAME', 'USER': 'DB_USER', 'PASSWORD': 'DB_PASSWORD', 'HOST': 'localhost', 'PORT': '5432', } } .env file POSTGRES_USER='DB_USER' POSTGRES_PASSWORD='DB_PASSWORD' POSTGRES_DB='DB_NAME' POSTGRES_HOST='localhost' POSTGRES_PORT='5432' Dockerfile.web FROM python:3.9-bullseye WORKDIR /app ENV PYTHONUNBUFFERED=1 COPY csgo . RUN apt-get update -y \ && apt-get upgrade -y pip \ && pip install --upgrade pip \ && pip install -r requirements.txt CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] docker-compose.yml version: '3' services: web: container_name: web build: context: . dockerfile: Dockerfile.web env_file: - .env volumes: - .:/code ports: - '8000:8000' depends_on: - db db: image: postgres:13 restart: always ports: - '5432:5432' env_file: - .env volumes: postgres_data: Now, when I docker-compose up all appear to be working fine besides connection to the database. I get this error: django.db.utils.OperationalError: could not connect to server: Connection refused web | Is the server running on host "localhost" (127.0.0.1) and accepting web | TCP/IP connections on port 5432? web | could not connect to server: Cannot assign requested address web | Is the server running on host "localhost" (::1) and accepting web | TCP/IP connections on port 5432? Can you please help me solve this problem? Additionally, …