Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
GraphQL request made from React page to Django App blocked in the response
I am currently working on a personnal project which currently creates a GraphQL request in a react application and sends it to a Python django app in order to get the Response. The problem is when I ask for a GraphQL request from a react page, I get this anwser in the console.log : Access to fetch at 'http://localhost:8000/graphql/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. Here are my settings.py files which contains the apps : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'graphene_django', 'myapp', 'corsheaders' ] CORS_ORIGIN_WHITELIST = [ "http://localhost:3000",#React page "http://127.0.0.1:3000" #React page with an IP address ] 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', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] ROOT_URLCONF = 'backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'backend.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': str(BASE_DIR / 'db.sqlite3'), } } … -
Django how to include all columns from one table, but a only subset of columns in a different table, using tbl.only?
I want to join a child table to the parent table, and return all columns from the child table (child.*), but only specific columns from a parent table (parent.foo, parent.bar), using only but not defer. Is there any syntax to issue a SQL similar to the following: select child.*, parent.foo, parent.bar from child join parent on child.parent_id = parent.id I do not want to use defer, because the parent table has even more columns than the child table. I currently have to spell out every column that I want using only: Child.objects.select_related('parent').only( 'id', 'name', 'creation_date', 'parent__foo', 'parent__bar' ).all() But I would like to include all the columns from Child. -
How to make view that uses a web scraper load faster
I have a view that outputs destination city results on a page. As part of the view, a web scraper searches for flight prices from the user's area to the destination city. After adding the web scraper to the view it now takes about 8 seconds to load. I was wondering how I can make the view load quicker, maybe with threading or another alternative. views.py def results(request, result1, result2, result3, result4, result5, result6, broad_variable1, broad_variable2, broad_variable3, specific_variable_dictionary, user_city): result1 = City.objects.filter(city=result1).first() result2 = City.objects.filter(city=result2).first() result3 = City.objects.filter(city=result3).first() result4 = City.objects.filter(city=result4).first() result5 = City.objects.filter(city=result5).first() result6 = City.objects.filter(city=result6).first() # get the first user selected specific variable value for each result result1_value1 = City.objects.filter(city=result1.city).values(broad_variable1)[0][broad_variable1] result2_value1 = City.objects.filter(city=result2.city).values(broad_variable1)[0][broad_variable1] result3_value1 = City.objects.filter(city=result3.city).values(broad_variable1)[0][broad_variable1] result4_value1 = City.objects.filter(city=result4.city).values(broad_variable1)[0][broad_variable1] result5_value1 = City.objects.filter(city=result5.city).values(broad_variable1)[0][broad_variable1] result6_value1 = City.objects.filter(city=result6.city).values(broad_variable1)[0][broad_variable1] # assign variables before referencing them result1_value2 = None result2_value2 = None result3_value2 = None result4_value2 = None result5_value2 = None result6_value2 = None # check if the user chose a second variable # get the second user selected specific variable value for each result if broad_variable2 != "Nothing": result1_value2 = City.objects.filter(city=result1.city).values(broad_variable2)[0][broad_variable2] result2_value2 = City.objects.filter(city=result2.city).values(broad_variable2)[0][broad_variable2] result3_value2 = City.objects.filter(city=result3.city).values(broad_variable2)[0][broad_variable2] result4_value2 = City.objects.filter(city=result4.city).values(broad_variable2)[0][broad_variable2] result5_value2 = City.objects.filter(city=result5.city).values(broad_variable2)[0][broad_variable2] result6_value2 = City.objects.filter(city=result6.city).values(broad_variable2)[0][broad_variable2] # assign variables before referencing them … -
filtering annotated-aggregated columns with django_filters
Assume I have a Customer Model which is related to an Order Model. I want to list customers and the Sum(or Count) of their orders between a date range. if there was no order in the given range for any customer the annotated column would be 0. if I use django_filters FilterSet it changes the main WHERE clause of the query so the row with no order wouldn't be displayed, but I want something like: .annotate( order_count=Count( 'customer_orders', filter=Q( customer_orders__create_time__gte=query_params.get('order_after') ) & Q( customer_orders__create_time__lte=query_params.get('order_before') ) ) ) is there a neat way to achieve this using django_filters FilterSet? -
Django serializer.is_valid() makes a call to different custom serializer method
I have a django test server. i want to POST user data and return Response with 'username' and 'Token' after successfull registration. In the following view, I also check if request.data['email'] already exists in Users model because i want it to behave as unique=True and it gives me unexpected results. I know this code is just a noob implementation all around and it doesnt bother me for now, but the more important thing for me is to understand WHY my code is giving these results. I believe a detailed answer will help me understand python so much better. Here is the View function inside views.py : @api_view(['POST']) @permission_classes((AllowAny,)) def Register(request): r={"username": "JohnDoeyy", "password": "Thisisapassword60!", "email": "test@test.com", "age": "50"} #r = request.data if not (r.get("username") and r.get("password") and r.get("email")): return Response("empty fields") serializer = UserSerializer(data=r) print("debug1") if request.method == 'POST': print("debug2") if serializer.is_valid() and serializer.validate_email(r.get("email")): #User.objects.filter(email=r.get("email")).exists(): print("is_valid:", serializer.is_valid()) try: print("debug3 before .save") serializer.save() #This does NOT work. print("debug3 after .save") token, created = Token.objects.get_or_create(user=serializer.instance) return Response({"user": serializer.validated_data['username'], "token": token.key}, status=status.HTTP_200_OK) except Exception as e: print("debugException" , e) return Response(str(e)) else: print("3") return Response("fail") Here is the serializer.py . Possible culprit the validate_email method. class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) def create(self, validated_data): … -
Django: Can't set up custom django User model
I want to set up my own django User model because I need additional fields, but I am getting the error. I read a lot of posts but I didn't find solution. What is the problem? Code models.py: class User(AbstractBaseUser): username = models.CharField(max_length=30, unique=True), email = models.EmailField(max_length=50, unique=True), city = models.TextField(max_length=30, blank=True), friends = models.ManyToManyField("Account", blank=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['username'] Code admin.py admin.site.register(User) Code admin settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users.apps.UsersConfig' ] AUTH_USER_MODEL = 'users.User' Error: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\options.py", line 608, in get_field return self.fields_map[field_name] KeyError: 'username' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 438, in check all_issues = checks.run_checks( File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\checks.py", line 55, in check_user_model if not cls._meta.get_field(cls.USERNAME_FIELD).unique and not any( File "C:\Users\rogal\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\options.py", line 610, in get_field raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) django.core.exceptions.FieldDoesNotExist: User has no field named 'username' -
skip an iteration of the for loop in python
I need a hand, I don't understand how to fix it. Look at the photo to better understand my speech, where the new field is populated the value of new is subtracted from the total and I don't want it to be subtracted immediately but the next round. How can I do? def UserAndamentoListView(request): giorni = [] mese = [] new_user = [] tot_user = [] tot = User.objects.all().count() for day in range(5): giorni.append(datetime.datetime.now() - datetime.timedelta(days=day)) new = User.objects.filter(date_joined__contains = giorni[day].date()) new_user.append(new) tot -= new.count() tot_user.append(tot) context = {'giorni': giorni, 'new_user':new_user, 'tot_user': tot_user} return render(request, 'andamento.html', context) -
Can't see the address when nginx processes the port and outputs 502 Bad Gateway
I encountered a problem when learning nginx. I have 2 servers on 2 different ports. I want a page with information stored on port 8000 to be returned when accessing "http://localhost/api/v1/clients/". Now I get error 502 Bad Gateway. В консоли: connect() failed (111: Connection refused) while connecting to upstream, client: 111.11.0.1, server: localhost, request: "GET /api/v1/clients/ HTTP/1.1", upstream: "http://111.11.0.2:80/api/v1/clients/", host: "localhost" If I go to the address: "http://localhost:8000/api/v1/clients/", everything is fine. What's my mistake? nginx: upstream backend { server 127.0.0.1:8000; server 127.0.0.1:3000; } server { listen 80; server_name localhost; location /api/v1/clients/ { proxy_pass http://backend_client/api/v1/clients/; } } docker: services: backend_client: build: ./Client volumes: - ./Client/:/app ports: - "8000:8000" restart: always command: "gunicorn --bind=0.0.0.0:8000 django_app.wsgi" nginx: image: nginx:1.17 container_name: ngx ports: - "80:80" volumes: - ./nginx:/etc/nginx/conf.d depends_on: - backend_client -
How to validate and return access and refresh tokens after user.save()
I'm verifying the user OTP to change password and after change password I'm unable to create access and refresh token using JWT , Normally when user get log in I use following method MyTokenObtainPairView which return both access and refresh token with all other stuff to UserSerializerWithToken. class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) serializer = UserSerializerWithToken(self.user).data for k, v in serializer.items(): data[k] = v return data class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer I coppied similar appraoch to return UserSerializerWithToken after set_password and user.save() UserSerializerWithToken is class UserSerializerWithToken(UserSerializer): token = serializers.SerializerMethodField(read_only=True) class Meta: model = CustomUser fields = ['id', 'isAdmin', 'token'] def get_token(self, obj): token = RefreshToken.for_user(obj) return str(token.access_token) and the problematic function is @api_view(['PUT']) def reset_password(request): data = request.data email = data['email'] otp_to_verify = data['otp'] new_password = data['password'] user = CustomUser.objects.get(email=email) serializer = UserSerializerWithToken(user, many=False) if CustomUser.objects.filter(email=email).exists(): otp_to_verify == user.otp if new_password != '': user.set_password(new_password) user.save() # here password gets changed return Response(serializer.data) # else: message = { 'detail': 'Password cant be empty'} return Response(message, status=status.HTTP_400_BAD_REQUEST) else: message = { 'detail': 'Something went wrong'} return Response(message, status=status.HTTP_400_BAD_REQUEST) I receive the toke but not getting access and refresh toke to use it to login next time. I'm assuming user.save() dosnt … -
how to run a loop or any other method for the below mentioned django project
Model.py: ``` from django.db import models class ddlname(models.Model): name=models.CharField(max_length=255) stdate=models.DateField() sttime=models.TimeField() endate=models.DateField() def __str__(self): return self.name``` views.py: ``` from django.shortcuts import render, HttpResponse, redirect from .forms import nameform from .models import ddlname def dashboard(request): if request.method=='GET': form=nameform() return render(request,'home.html',{'form':form}) else: form=nameform(request.POST) if form.is_valid(): form.save() return redirect('/homedetails') def homedetails(request): context={'homedetails':ddlname.objects.all().order_by('stdate','sttime')} return render(request,'homedetails.html',context)``` forms.py: ``` from dataclasses import fields from django import forms from .models import ddlname class nameform(forms.ModelForm): class Meta: model=ddlname fields='__all__'``` I am getting the output from stdate to endate when i input the details in the template, but i am facing difficulty in getting same data for multiple dates. for example(my stdate input is 2022-2-11 and endate input is 2022-2-15, along with name(Test), when i input this details I get a single data as (test,2022-2-11,2022-2-15), where I need my output as (test,2022-2-11,2022-2-11 | test,2022-2-12,2022-2-12 | test,2022-2-13,2022-2-13....finally as per endate test,2022-2-15,2022-2-15). request some one to help me on this. -
NoReverseMatch Django using pk
Reverse for 'update' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['basic_app/update/(?P[0-9]+)/\Z'] 9 <p>Location: {{school_detail.location}} </p> 10 <h3>Students:</h3> 11 {% for student in school_detail.students.all %} 12 <p>{{student.name}} who is {{student.age}} years old</p> 13 {% endfor %} 14 15 16 </div> 17 18 <div class="container"> 19 <p><a class='btn btn-warning' href="{% url 'basic_app:update' pk=school_details.pk %}">Update</a></p> 20 21 </div> 22 {% endblock %} -
Run bash text scripts after docker run
I have django application, a test.sh script and dockerfile. I have built dockerfile and run it by docker run -d -p 80:80 IMAGE_NAME. Dockerfile FROM python:3.8-slim-buster RUN apt-get install -y ca-certificates wget RUN apt install gunicorn3 -y COPY ./ ./ RUN pip3 install -r requirements.txt RUN chmod +x ./test.sh CMD ["sh", "test.sh"] ENTRYPOINT ["gunicorn --bind 0.0.0.0:80 core.wsgi:application"] test.sh #!/bin/bash python manage.py test Gunicorn is running successfully. Now I want to run test.sh script with docker run -it --rm IMAGE_NAME test.sh. When i run that command the server runs but never executes test.sh but gunicorn server runs. How can I run test.sh from docker run -it --rm IMAGE_NAME test.sh? -
How to render Page attributes in a model when displayed in StreamField?
I have the following StructBlock and Page model: class PostGrid(blocks.StructBlock): title = blocks.CharBlock() post_1 = blocks.PageChooserBlock() post_2 = blocks.PageChooserBlock() class Meta: template = 'post-grid.html' class BlogIndex(Page): body = StreamField([('POSTS', PostGrid()),]) class Meta: template = 'base.html' class PostPage(Page): hero_title = models.CharField(max_length=255) I want to render the attributes of post_1 and post_2 in the body StreamField: base.html: {% for block in page.body %} {% include_block block %} {% endfor %} post-grid.html: {{ value.post_1.url }} {{ value.post_1.hero_title }} value.post_1.url renders the URL fine. However, value.post_1.hero_title is blank. How do I render the Page attributes? -
Modern best approach to using Django ORM with async?
The world of async Django is changing rapidly, and it's hard to tell what is current and what is dated. So, what is the current best approach to using the Django ORM (or, possibly, another ORM) for the best/smoothest async capability? What do people use successfully today? Lots of references out there, including: https://forum.djangoproject.com/t/asynchronous-orm/5925/70 https://channels.readthedocs.io/en/latest/topics/databases.html -
Adding id to url route in Async testing with Django
I've built a simple chatroom and now I want to code a test to verify if Its connecting. Following the tutorial in Channels docs i come up with the following test: class ViewTestCase(TestCase): @classmethod def setUp(self): user_moderator = User.objects.create_superuser(first_name='tester', username='test1', password='123', email='testuser@gmail.com') user_player = User.objects.create_user(first_name='player', username='player1', password='1234', email='testplayer@gmail.com') pack1 = Pack.objects.create(deckStyle='Fibonacci',deck=['1','2','3']) self.room = PokerRoom.objects.create(status='Pending',name='planning',styleCards='Fibonacci', user=User.objects.get(username='test1'), deck=Pack.objects.get(deckStyle='Fibonacci'),index=1) user_player = ParticipatingUser.objects.create(name='player',idRoom=PokerRoom.objects.get(name='planning'), status='Pending') self.story = Story.objects.create(storyName='testplanning', idRoom=PokerRoom.objects.get(name='planning'), status='Pending') async def test_consumer(self): application = URLRouter([ url(r'ws/chat/(?P<room_name>[A-Za-z0-9_-]+)/participant/(?P<user>\w+)/$', consumers.ChatConsumer.as_asgi()), ]) communicator = WebsocketCommunicator(application,"/ws/chat/room_id/participant/participant_id)/") connected, subprotocol = await communicator.connect() assert connected await communicator.disconnect() My problem is that I need to substitute room_id and participant_id inside my WebsocketCommunicator. participant_id is just an commom id and my room_id is a UUIDField. I've been using the following method to extract these ids in my others tests: def test_something(self): room_id = PokerRoom.objects.get(name='planning').id user_id = User.objects.get(username='tester').id ... But if I use the same method inside async def like this: async def test_something(self): room_id = PokerRoom.objects.get(name='planning').id user_id = User.objects.get(username='tester').id ... I get this error django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. How can I solve this? -
Django How to Look up querydict in template?
when i look inside querydict it with {{get_copy}} it shows <QueryDict: {'grub_id__in': ['Yelek', 'Tunik', 'Tulum', 'Tshirt']}> as i know that how to look up querydict {%for key,val in get_copy.items%} {{key}}{{val}} {%endfor%} but it shows only one of val value output: grub_id__in Tshirt -
Django relationships between child and parent model
I am busy with a project where I have two models and I'm not sure how to do as I am fairly new to programming. what I would like to do is have a template that renders all the instances of first model and then on the same template I want to have all the sales associated with each of those instances as well as the instances with different states(for example if an instance of first model is linked to 2 sales that has a state of "Confirmed" it should say 2 next to that instance name.) class QAAgent(models.Model): user=models.OneToOneField(User,on_delete=models.SET_NULL,null=True) Qa_name = models.CharField(max_length=15) def __str__(self): return self.user.username States = (('Pending',"Pending"),("Confirmed","Confirmed"),("Requested","Requested),("Cancelled","Cancelled"),("Not interested","Not interested")) class Sale(models.Model): QA = models.ForeignKey(QAAgent,on_delete=models.SET_NULL,blank=True, null=True,related_name="sale") State = models.CharField(choices=States,default="Pending",max_length=15) Date_created = models.DateTimeField(auto_now_add=True) Date_edited = models.DateTimeField(auto_now=True) def__str__(self): return self.client_name + " " + self.client_surname -
Limiting instances in database Django
How can i limit the amount of instances in database based on Entity? So i want to only have 5 photos at most attached to an Entity. Also I want to limit a photo to be max 5mb. Do you have any idea how to do it? class EntityPhoto(models.Model): user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, null=True, related_name='entity_photo') entity = models.ForeignKey(Entity, on_delete=models.CASCADE, null=False) image = models.FileField(upload_to='entities/') created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) -
how to Make an LMS using django?
hi I want to learn about making fast and responsible LMS using Django. is there any course for teaching this? and what can I do to make the website page fast and easy to use and secure just like Udemy? -
Access data across schemas in multi-tenant SaaS system using ORM
In our multi-tenant system (using Postgresql), we want to allow different tenants to "associate" with each other, and share some data. So if Tenant A is associated with Tenant B, when showing the shared data, our queries will need to get data from schema A AND schema B. I've found examples that show how to do so with straight Postgresql code; something like this: select * from S1.table1 UNION ALL select * from S2.table1 ...though ours would be much more complicated than that. But I've not found anything that explains how to do it with Django's ORM. In other words, how would I do the above with the query syntax we actually use in our site: queryset = MyTable.objects.filter(client_id__in=clients, status=Status.ACTIVE) -
Data from django database isnt visible
Data from the database is visible except one. This is the HTML file where the exchange name is not visible. I want the exchange name to be visible but it is not. Rest are visible. {% for balance in balances|dictsortreversed:"amount_fiat" %} <tr class="spacer"> <td class="cell"><div class="btn btncur round">{{ balance.currency }}</div></td> <td >{{ balance.amount|floatformat:-8 }}</td> <td >{{ balance.exchange_name }}</td> <td> {{ balance.amount_fiat|floatformat:-8 }} ({{ balance.amount_fiat_pct|floatformat:-2 }}%) </td> </tr> {% endfor %} Database where exchange_name lies Relevant files: models.py class ManualInput(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now=True) currency = models.CharField(max_length=10, default='BTC') amount = models.FloatField(default=None, blank=True, null=True) exchange_name = models.CharField(max_length=30) def __str__(self): return "%s %s %s %s %s" % (self.user.username, self.timestamp, self.currency, self.amount, self.exchange_name) forms.py class ManualInputForm(forms.ModelForm): currency = forms.ModelChoiceField( queryset=models.Currency.objects.all(), empty_label=None) exchange_name = forms.ModelChoiceField( queryset=models.ManualExchange.objects.all(), empty_label=None) class Meta: model = models.ManualInput fields = ('currency', 'amount', 'exchange_name',) Please tell me where is the error -
How to create custom paginator in django
I'm trying to use django built-in paginator but it's not working cuz I'm not using database storage object I'm creating a website with other api... heres my code: def index(request): response = requests.get("https://www.hetzner.com/a_hz_serverboerse/live_data.json") data = response.json() p = Paginator(data, 3) pn = request.GET.get('page') print(pn, p, data) page_obj = p.get_page(pn) context = { 'data': data, 'page_obj': page_obj } return render(request, 'index.html', context) do i need to create custom paginator if so how should i? or is there solution? -
Django how to create an clone database?
postgresql is my primary data base. If any object create in my original database then I want it will also keep an duplicate object in my secondary database. I read Django documentation for create an clone database but didn't work. here is my code: #replicarouter.py class PrimaryReplicaRouter: def db_for_read(self, model, **hints): """ Reads go to a randomly-chosen replica. """ return 'replica_database' def db_for_write(self, model, **hints): """ Writes always go to primary. """ return 'default' def allow_relation(self, obj1, obj2, **hints): """ Relations between objects are allowed if both objects are in the primary/replica pool. """ db_set = {'default', 'replica_database'} if obj1._state.db in db_set: return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ All non-auth models end up in this pool. """ return True settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '9l2ENsuudW0Kfarhyn', 'USER': 'postgres', 'PASSWORD': 'tusar', 'HOST': 'localhost', 'PORT':5432, }, 'replica_database': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'farhyn_website', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': 3306, } } DATABASE_ROUTERS = ['my_path.replicarouter.PrimaryReplicaRouter'] -
Django deployment on heroku
I have successfully deployed my Django project on Heroku but when I try to load the URL, it's showing a 505 error. I have checked my settings and everything seems to be intact. Please I need an urgent help -
Django 4.0 shows path not found even after configuring all urls and views properly
So my django app looks like this -assaydash --dashboard (app) --members (app) --djangobackend (django project directory) --static --manage.py djangobackend/settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dashboard.apps.DashboardConfig', 'members.apps.MembersConfig', ] djangobackend/urls.py urlpatterns = [ path('admin/', admin.site.urls, name='admin'), path('', include('dashboard.urls')), path('members/', include('django.contrib.auth.urls')), path('members/', include('members.urls')), ] members/urls.py urlpatterns = [ path('login_user', views.login_user, name="login"), path('logout_user', views.logout_user, name='logout'), ] members/views.py def login_user(request): if request.method == "POST": ... else: messages.success(request, ("There Was An Error Logging In, Try Again...")) return redirect('login') else: return render(request, 'authenticate/login.html', {}) def logout_user(request): logout(request) messages.success(request, ("You Were Logged Out!")) return redirect('home') index.html <a href="{% url 'login' %}" > <span class="d-sm-inline d-none">Sign In</span> </a> On the index page when i click on the a tag it shows me a debug page with path not found. Even though the url exists and i have included it in my main urls.py and i have added the app in the settings.py as well. please help and let me know what is wrong here. Notice that the url for name login was detected by the template but the path wasn't found. Also the other urls on the debug page are from my dashboard app which works fine