Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to render template with context in a django backend api call?
I have a frontend react app... Now on clicking a button in frontend it will go through a server side rendering and the middleware will take the authorization token and fetch user info from api/me endpoint...then using that user info i will render user specific form... here is my front end-> <a href="apply-form/31">Apply Job</a> here is my middleware-> access_token = request.COOKIES.get("AccessToken") headers = { "Authorization":f"Bearer {access_token}", "Content-Type":"application/json" } r = requests.get(url='https://im/api/v1/me',headers=headers) json = r.json() request.META["user"] = json my view file is simple , just getting the request meta user data ...querying the user specific information from the database and rendering the template with context def index(request): user = request.META["user"] data = models.Post.objects.filter(user_id = user["id"]) return(request, "index.html", {"data": data}) the problem is that i dont want to fetch the authorization token from the cookies rather i want it from an api call in headers-> fetch("https://apply-form/31",{ headers: { "Content-type": "application/json", "Authorizaton" : "Bearer Token" } }) then the middleware will not have to fetch the token from the cookies but rather from the request.header["Authorization"] headers = { "Authorization":request.headers.get('Authorization'), "Content-Type":"application/json" } r = requests.get(url='https://im/api/v1/me',headers=headers) json = r.json() request.META["user"] = json but the problem is that if the view function turns in to a … -
How to identify generic relationship after model is passed to React
I've built a Django app with a React frontend. Now, I want to use generic relationships and not sure of a reliable way for my React app to identify which model the relationship is. I've considered : adding a new field to my model to keep track of the model type but this seems counter to the idea of generic relationships Looking at the fields of the object once it reaches my react app to determine what the model is. But this seems difficult to maintain as things grow. I use 100% Typescript in my React, so perhaps there is some way to leverage Typescript to help. What is a good way to identify different models in generic relationships once they reach the React app? -
How to pass percentage of two django db field as a template tag
I have two fields in my django db which called like and dislike. I want to pass I need to pass the average of these two values to the template to be used as the width of <div style="width:x%">. in views.py: def PostListView(request): posts = Post.objects.all() context['posts'] = posts return render(request, 'app/mytemplate.html', context) and in template: {% for post in posts %} <div class="ratings-css-top" style="width: {% widthratio post.like post.dislike 100 %}"> </div> {% endfor %} how to pass this average value of fields as a width? like % (like + dislike ) * 100 -
trying to make a carousel slider in django and trying to take picture from database then render on frontend
I am trying to make a carousel slider. Picture comes from the database and then render it on the frontend slider. But the picture is rendering but it is creating new slider and when i change to next slide then it shows the same picture. What to do?? My code is here... `{% for post in object_list %} <h2>{{ post.title }}</h2> </ul> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> </ol> <div class="carousel-inner"> <div class="carousel-item active"> <img src="{{ post.image.url}}" class="d-block w-100" alt="{{ post.title }}"> </div> <div class="carousel-item"> <img src="{{ post.image.url }}" class="d-block w-100" alt="{{ post.title }}"> </div> <div class="carousel-item"> <img src="{{ post.image.url }}" class="d-block w-100" alt="{{ post.title }}"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> {% endfor %} {% endblock %} ` -
Javascript incorrect output of datetime from rest API
I'm not getting the right time from my datetime field data when trying to fetch the data using fetch API. So here's the data from my database. See image: Now, my problem is when I'm trying to print the data using console.log it is giving me a wrong time. See image: Here's the field in my model: date_created = models.DateTimeField(auto_now=True, auto_created=True) Here's my serializer: class Meta: model = Message fields = [ 'date_created',] Here's also the settings: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Manila' USE_I18N = True USE_L10N = True USE_TZ = True I'm not sure where is the problem if it is with the timezone settings? Anyone had an experience of this? -
How to restrict user who can make a blog post
I am working on blog site and making it with django also came across https://www.youtube.com/watch?v=TAH01Iy5AuE this tutorial from codemy. In this tutorial he told a hacky way to do the restrict thing can anyone tell me the recommended way to do so -
How to set fields/model to readonly if one attribute is set to true in Django?
So, I got three classes: class User(...): #... other fields name = models.CharField() class Equipment(...): #... other fields inUse = models.Boolean(default=False) class Ticket(...): #... Other fields user = models.ForeignKey(...) equipment = models.ForeignKey(...) ended = models.Boolean(default=False) Now, when I create a new Ticket, the equipment "inUse" attribute changes to True, so I cannot give the same Equipment to more than one User. The thing is that when I set the Ticket to "ended" I'll still be able to change it to not "ended". I want not to be able to change that once I set the "ended" attribute of the Ticket to True. PS: I'm overriding the method save to make changes in the Equipment when setting up a new Ticket or changing it to "ended". -
What is the correct way to bring only the relationship on a Queryset (django)?
I have this models: class Thing(models.Model): thing_name = models.CharField(max_length=200) thing_stuff = models.SlugField(max_length=200, unique=True) class AllowedThing(models.Model): thing = models.ForeignKey( 'Thing', on_delete=models.PROTECT) foo = models.ForeignKey('Foo', on_delete=models.PROTECT) bar = models.ForeignKey(Bar, on_delete=models.PROTECT) class Meta: unique_together = (('thing', 'foo'),) and I would like to access "thing_name" and "thing_stuff" directly in the queryset objects, as in obj.thing_name instead of obj.thing.thing_name without having to do this qs = AllowedStuff.objects.all().annotate( thing_name=F('thing__thing_name') ).annotate( thing_stuff=db.F('thing_thing_stuff') ) -
Image not loading in apache web server
I made a django project with a raspberry pi and I tried loading it into apache2. I'm trying to stream images from the raspberry pi cam into the website but the images dont seem to be loading. The CSS and everything else looks like it working fine but the images arent loading. Heres what I get on my error log: [Tue Oct 13 13:22:48.910217 2020] [wsgi:error] [pid 520:tid 1964999728] [remote 192.168.0.156:60677] mod_wsgi (pid=520): Exception occurred processing WSGI script '/home/pi/dev/Rover/src/Rover/wsgi.py'. [Tue Oct 13 13:22:48.911093 2020] [wsgi:error] [pid 520:tid 1964999728] [remote 192.168.0.156:60677] Traceback (most recent call last): [Tue Oct 13 13:22:48.911339 2020] [wsgi:error] [pid 520:tid 1964999728] [remote 192.168.0.156:60677] File "/home/pi/dev/Rover/src/roverBase/views.py", line 27, in gen [Tue Oct 13 13:22:48.911388 2020] [wsgi:error] [pid 520:tid 1964999728] [remote 192.168.0.156:60677] frame = camera.get_frame() [Tue Oct 13 13:22:48.911481 2020] [wsgi:error] [pid 520:tid 1964999728] [remote 192.168.0.156:60677] File "/home/pi/dev/Rover/src/RoverLibs/CamWebInterface.py", line 24, in get_frame [Tue Oct 13 13:22:48.911528 2020] [wsgi:error] [pid 520:tid 1964999728] [remote 192.168.0.156:60677] ret, jpeg = cv2.imencode('.jpg', frame_flip) [Tue Oct 13 13:22:48.911688 2020] [wsgi:error] [pid 520:tid 1964999728] [remote 192.168.0.156:60677] cv2.error: OpenCV(4.4.0) /tmp/pip-wheel-p4wkaqpf/opencv-python/opencv/modules/imgcodecs/src/loadsave.cpp:919: error: (-215:Assertion failed) !image.empty() in function 'imencode' [Tue Oct 13 13:22:48.911737 2020] [wsgi:error] [pid 520:tid 1964999728] [remote 192.168.0.156:60677] This is what my wsgi.py looks like: import os … -
multiple images upload working but how to return all images related to that instance in Django rest framework
I have successfully implemented the multiple images upload , but how to return all images related to that instance in response. class ContactTransactionsViewSet(ViewSet, ListAPIView): permission_classes = [IsAuthenticated] serializer_class = ContactTransactionsSerializer filter_backends = (DjangoFilterBackend,) filter_class = ContactTransactionsFilter parser_classes = (MultiPartParser,FormParser) def get_queryset(self): user = self.request.user return ContactTransactions.objects.filter(contact__user=user, cashbook__user=user).order_by('-txn_date') def create(self, request): flag=1 data = request.data.copy() data["user"] = request.user.id if 'transaction_images' in data: images = dict((request.data).lists())['transaction_images'] else: flag=2 serializer = self.get_serializer(data=data) if not serializer.is_valid(): response_json = { "Status": "Failure", "Response": { "data": { "message": "" } }, "Error": { "code": 400, "message": "invalid request", "error_message": {} } } return Response(response_json) else: obj= serializer.save() print(obj.id) arr=[] if flag==1 and flag != 2: for img_name in images: modified_data = modify_input_for_multiple_files(obj.id, img_name) file_serializer = ContactTransactionsImagesSerializer(data=modified_data, context={"request": request}) if file_serializer.is_valid(): file_serializer.save() arr.append(file_serializer.data) else: flag = 0 if flag==0: response_json={ "Status": "Failure", "Response": { "data": { "message": "" } }, "Error": { "code": 400, "message": "invalid request", "error_message": {} } } else: dict1={"transaction_images": arr, "view_type": "body", "receive_amount": ""} dict1.update(serializer.data) response_json={ "Status": "Success", "Response": { "data": dict1 }, "Error": { "code": 201, "message": "" } } return Response(response_json) serializer.py class ContactTransactionsImagesSerializer(serializers.ModelSerializer): imagePath = serializers.SerializerMethodField() def get_imagePath(self, obj): request = self.context.get("request") return str(request.build_absolute_uri(obj.image.url)) class Meta: model = ContactTransactionsImages fields … -
get field value from form and make an object from that value django
I want to get a field value from form when submitted(object a created) and use that value to make another object(object b, which is OneToOneRelationship), if it's possible. I tried something like this, but didn't work. # models.py class Employee(models.Model): ... number = models.CharField(max_length=10, unique=True) ... class Person(models.Model): ... employee = models.OneToOneField(Employee, on_delete=models.CASCADE) ... views.py def create(request, number): if request.method == "POST": emp_form = EmployeeForm(request.POST, request.FILES) p, _ = Person.objects.get_or_create( employee=Employee.objects.get_or_create(number=emp_form.data['number'])[0] ) person_form = PersonForm(request.POST, instance=p) if emp_form.is_valid() and person_form.is_valid(): e=emp_form.save(commit=False) number=e.number e.profile = request.FILES['profile'] if 'profile' in request.FILES else None e.save() person_form.save() return redirect('employee:detail', number=number) else: emp_form = EmployeeForm() person_form = PersonForm() context = { 'emp_form': emp_form, 'person_form': person_form, } return render(request, 'employee/member_create_or_update.html', context) I know I can create Employee object first, and then add Person object later, still I'd like to know if I can create both objects in one go in one submit. Thanks for your help in advance. -
How to change a field of model prior saving the model based on another field in django 3.1
I need to be able to set the KeyIndex field of the Settings model to a value that is equal to lastExtension - firstExtension How can i do that this is the content of my model models.py class Settings(models.Model): KeyIndex = models.CharField(max_length=150, blank=True, name='Key_Index') firstExtension = models.CharField(max_length=15, blank=False, null=False, default='1000') lastExtension = models.CharField(max_length=15, blank=False, null=False, default='1010') def save(self, *args, **kwargs): f = int(self.firstExtension) l = int(self.lastExtension) a = [0] * (l - f) self.KeyIndex = str(a) return super(Settings, self).save() class KeyFiles(models.Model): setting = models.ForeignKey(Settings, on_delete=models.CASCADE) keyFile = models.FileField(upload_to='key File', null=True, blank=True, storage=CleanFileNameStorage, validators=[FileExtensionValidator(allowed_extensions=['bin']), ]) this is the content of my form forms.py class ShowAdminForm(forms.ModelForm): class Meta: model = Settings fields = '__all__' files = forms.FileField( widget=forms.ClearableFileInput(attrs={"multiple": True}), label=_("Add key Files"), required=False,validators=[FileExtensionValidator(allowed_extensions=['bin'])] ) def save_keyFile(self, setting): file = KeyFiles(setting=setting, keyFile=upload) file.save() and t admin.py class KeyFilesAdmin(admin.TabularInline): model = KeyFiles @admin.register(IPPhone_Settings) class IPPhoneSettingsAdmin(admin.ModelAdmin): form = ShowAdminForm inlines = [KeyFilesAdmin] def save_related(self, request, form, formsets, change): super(IPPhoneSettingsAdmin, self).save_related(request, form, formsets, change) -
Export Django logs to Azure AppInsights with OpenCensus
I'm following this guidance for Django and Azure. I'm able to get dependancies and requests, but not traces. I added this to middleware: 'opencensus.ext.django.middleware.OpencensusMiddleware' Here is the LOGGING and OPENCENSUS portions of settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '%(asctime)s - %(levelname)s - %(processName)s - %(name)s\n%(message)s', }, }, "handlers": { "azure": { "level": "DEBUG", "class": "opencensus.ext.azure.log_exporter.AzureLogHandler", "instrumentation_key": assert_env('APPINSIGHTS_INSTRUMENTATIONKEY'), }, "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "default", }, }, "loggers": { "logger_name": {"handlers": ["azure", "console"]}, }, # For some reason, this is needed or logging doesn't show up in the # celery log file. 'skyforge.tasks': { 'handlers': ['azure','console'], 'level': assert_env('DJANGO_LOG_LEVEL'), }, } OPENCENSUS = { 'TRACE': { 'SAMPLER': 'opencensus.trace.samplers.ProbabilitySampler(rate=1)', 'EXPORTER': '''opencensus.ext.azure.trace_exporter.AzureExporter( service_name='skyforge' )''' #Assumes Environmental Variable 'APPINSIGHTS_INSTRUMENTATIONKEY' } } Any guidance on where to look for why no trace logs. The django-critical and django-tasks are still going to the console. -
SyntaxError: 'return' outside function (HELP me To add Try , Except block in my Code.) [closed]
please help to to add try and except block to my following code.As i am interacting with DB. Views.py class FacilityView(viewsets.ModelViewSet): queryset = Facility.objects.all() serializer_class = FacilitySerializer I AM add in this way but not working giving me an error SyntaxError: 'return' outside function class FacilityView(viewsets.ModelViewSet): try: queryset = Facility.objects.all() serializer_class = FacilitySerializer return JsonResponse(serializer_class.data, safe=False) except: return JsonResponse({'message':'Failed'}, status=400) -
django model forms does'nt save the data
i want to create a todolist app with django. i created a form for list model but when the user click on submit to submit a list, the form is'nt saved, why? this is views.py i have created an instance of the form and set the user field to it and then save the instance but fact it does'nt Create your views here. def index(request): if request.user.is_authenticated: user_ = User.objects.get(username=request.user.username) lists = user_.user.all() form = listForm() if request.method == "POST": form = listForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return HttpResponseRedirect(reverse("index")) context = {'lists':lists, 'form':form} return render(request, 'todolists/index.html', context) else: return render(request, 'todolists/login.html') this is index template {% extends "todolists/layout.html" %} {% block body %} {% if user.is_authenticated %} <div class="center-column"> <form method="POST" action="{% url 'index' %}"> {% csrf_token %} {{form.title}} <input type="submit" class="btn btn-info"> </form> <div class="todo-list"> {% for list in lists %} <div class="item-row"> <a class="btn btn-sm btn-info" href="{% url 'update' list.id %}">update</a> <a class="btn btn-sm btn-danger" href="{% url 'update' list.id %}">delete</a> <span>{{list}}</span> </div> {% endfor %} </div> </div> {% endif %} {% endblock %} this is urls.py from django.urls import path from .import views urlpatterns = [ path('', views.index, name='index'), path('update/<str:id>/', views.update, name='update'), path("login", … -
Generating random string (for unique code) keeps returning the same random string
I have a Test model where each test can be identified by a unique randomly-generated string: from django.utils.crypto import get_random_string class Test(models.Model): code_length = 7 code = models.CharField(max_length=code_length, editable=False, default=generate_id(code_length)) name = models.CharField(max_length=100, default=None) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return "Code: {} | Username: {} | Test: {}".format(self.code, self.user.username, self.name) def generate_id(length): return get_random_string(length) Tbh, it was working good before. It started to "bugged-out" after I updated my Django from Django 1.x to Django 3.x and I also cleared all the records of the Test model in django-admin (I want to have a fresh and clean database for testing). Right now, whenever I try and create a new Test, it's code is literally the same with all other new Tests that I create: I think I haven't done anything to it other than those two changes I made. Any ideas? Thanks a lot! -
Run Selenium tests in Gitlab CI (Django project)
I'm trying to have GitLab CI run (with a shared runner) Selenium tests on my Django project every time commits are pushed to the repo on Gitlab.com. gitlab-ci.yml: image: python:3.8.5 services: - selenium/standalone-chrome:latest cache: paths: - ~/.cache/pip/ before_script: - python -V - python -m pip install --force-reinstall pip==18.1 - pip install -r requirements.txt test: script: - python manage.py test tests.py: from django.test import TestCase from django.test import LiveServerTestCase from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities @override_settings(DEBUG=True) class CreateNewProjectTestCase(LiveServerTestCase): def setUp(self): selenium_url = 'http://selenium__standalone-chrome:4444/wd/hub' self.selenium = webdriver.Remote( command_executor=selenium_url, desired_capabilities=DesiredCapabilities.CHROME) super(CreateNewProjectTestCase, self).setUp() However, when the pipeline job executes, I get the following error, resulting in a job's failure: selenium.common.exceptions.WebDriverException: Message: unknown error: net::ERR_CONNECTION_REFUSED Is there something I am missing? I think the URL is correct and I saw answers quite similar to this. -
Show all user articles from another view in profile [django]
I have Article model in news_app class Article(Created, HitCountMixin): title = models.CharField(max_length=120) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) snippet = models.TextField(null=False) with view: class AllArticlesListView(ListView): template_name = 'news/articles_list.html' model = Article paginate_by = 5 def get_queryset(self): return self.model.objects.all().order_by('-pk') in another app (user_app) I have Profile model: class Profile(AbstractUser): bio = models.TextField(blank=True, null=True, default='Brak') with view class ProfileView(HitCountDetailView): model = Profile template_name = 'profile/profile.html' In project url I have: path("<slug:slug>", ProfileView.as_view(), name='profile'), and in news_app url I have: path('all/', AllArticlesListView.as_view(), name='all_articles_list'), How can i show all user articles IN HIS USER PROFILE? class ProfileView(DetailView): model = Profile template_name = 'profile/profile.html' count_hit = True -
Error The current path, didn't match any of these
I'm trying to save the data submitted on a form, and redirect the user to a results.html. ------- Front template ------------------- Welcome to readability test V1 <form action="/addtext" method="POST">{% csrf_token %} <input type="text" name="title"/> <input type="text" name="content"/> <input type="submit" value="Add"/> </form> ---------- URLS.PY ----------------- from django.contrib import admin from django.urls import path from readtest.views import readtest, addtext urlpatterns = [ path('admin/', admin.site.urls), path('readability-test/', readtest), path('results/', addtext), enter code here ------------ VIEWS.PY ------------------------ from django.shortcuts import render from django.http import HttpResponseRedirect from .models import TestedText # Create your views here. def readtest(request): return render(request, 'test.html') def addtext(request): a = TestedText(title=request.POST['title'], content=request.POST['content']) a.save() return HttpResponseRedirect('/results/') ------ ERROR IM GETTING ------------------ Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/addtext Using the URLconf defined in redability.urls, Django tried these URL patterns, in this order: admin/ readability-test/ results/ The current path, addtext, didn't match any of these. -
How to place text & Image side by side using CSS & HTML
For my Django Project, I want to align Text & Image side by side. But not able to achieve it. The Image is crossing the parent div box. Can someone please help me to achieve below structure as shown in image below. Below is my piece of HTML & CSS code. <!DOCTYPE html> <html> <head> <title>AKS NAGG</title> <style> body { padding: 0; margin: 0; } .container{ background: aqua; height: 100vh; display: flex; } .box{ position: relative; margin:20px; margin-top: 40px; float: left; background: yellow; height:400px; width: 400px; border-radius: 10px; flex: 1; overflow-y: auto; } .items{ position: relative; margin: 10px; padding: 10px; border: solid; border-width: 2px; height: 100px; width: 400px; } .title{ position: relative; width: 50%; border: dotted; float: left; flex: 50%; } .image{ position: relative; float: right; clear: both; border-width: 2px; border: solid; } /* Clearfix (clear floats) */ .row::after { content: ""; clear: both; display: table; } </style> </head> <body> <div class='container'> <div class='box'> {% for t,l,i in data %} <div class='items'> <div class='title'> <a href="{{l}}">{{t}}<a/> </div> <div class='image'> <a href="{{l}}"><img src="{{i}}"></a> </div> </div> {% endfor %} </div> <div class='box'> Box2 </div> <div class='box'> Box3 </div> </div> </body> </html> Output as per my current code. The image is overlapping between … -
How To Filter foreign key in seralizers django rest framework?
Hope You Are Good! my question is how can filter foreign key in serializer? first, let's look at my code then I will explain you everything in detail! models.py class Project(models.Model): id = models.UUIDField(default=uuid4, primary_key=True, editable=False) user = models.BigIntegerField() program = models.ForeignKey(Program, on_delete=models.CASCADE) class Meta: ordering = ['-id'] def __str__(self): return self.name class Sprint(models.Model): id = models.UUIDField(default=uuid4, primary_key=True, editable=False) user = models.BigIntegerField() project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return f"{self.name}" class Backlog(models.Model): id = models.UUIDField(default=uuid4, primary_key=True, editable=False) ...... as_a = models.ForeignKey(Persona, on_delete=models.CASCADE) sprint = models.ForeignKey(Sprint, on_delete=models.CASCADE) def __str__(self): return f"{self.name}" serializers.py class ProjectSerializer(serializers.ModelSerializer): date_created = serializers.SerializerMethodField() class Meta: model = Project fields = "__all__" read_only_fields = ("id", "user", "program", "date_created",) def get_date_created(self, instance): return timesince(instance.date_created) class SprintSerializer(serializers.ModelSerializer): date_created = serializers.SerializerMethodField() class Meta: model = Sprint fields = "__all__" read_only_fields = ("id", "user", "date_created", "project",) def get_date_created(self, instance): return timesince(instance.date_created) class BacklogSerializer(serializers.ModelSerializer): date_created = serializers.SerializerMethodField() project = ProjectSerializer(read_only=True) class Meta: model = Backlog fields = "__all__" read_only_fields = ("id", "user", "date_created", "project",) def get_date_created(self, instance): return timesince(instance.date_created) views.py class BacklogAPIView(ListCreateAPIView): serializer_class = BacklogSerializer def get_project_or_404(self): return get_object_or_404(Project, pk=self.kwargs.get("uuid")) def perform_create(self, serializer): serializer.save(user=self.request.user.id, project=self.get_project_or_404()) def get_queryset(self): query_set = Backlog.objects.filter(user=self.request.user.id, project=self.get_project_or_404()) return query_set now my page looks like this: but … -
How to store image in database using django models
I have few questions please guide on these I am try to stroe images in database but they are getting store in media directory 2.The corresponding url is stored in the db column but I need actual image to be stored in the db please advice -
Why when I try to start my docker container it doesn't connect to the ports?
I have a Django app with postgresql as a database and 2 containers inside my docker compose that look like this: version: '3.7' services: web: build: ../DevelopsTest command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app/ ports: - "8000:8000" env_file: - ./.env.dev depends_on: - db db: image: postgres ports: - 5432 volumes: - postgres_data:/var/lib/postgres/data environment: - POSTGRES_USER=dbuser - POSTGRES_PASSWORD=dbpassword - POSTGRES_DB=db volumes: postgres_data: my Dockerfile looks like this: # pull official base image FROM python:3.8-alpine # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # copy project COPY . . when I run docker-compose up it gives me the next error: web_1 | django.db.utils.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "localhost" (127.0.0.1) and accepting web_1 | TCP/IP connections on port 5432? web_1 | could not connect to server: Address not available web_1 | Is the server running on host "localhost" (::1) and accepting web_1 | TCP/IP connections on port 5432? looks like Django can't connect to my db Here are … -
Why do I get CORS error when I have the header installed in Django and React?
So I'm running both React and Django application, in port 3000 and 8000 respectively. I'm aware of the CORS policy, so installed django-cors-headers and did as written in the documentation. Like below in my settings.py: INSTALLED_APPS = [ ... 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] I don't see anything wrong, but whenever I try to fetch the api in my React, I get error saying "Access to fetch at 'http://127.0.0.1:8000/main' from origin 'http://localhost:3000' has been blocked by CORS policy: 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." What do you think went wrong? Thank you very much in advance. *I've tried adding slash(/) at the end of "~~:3000", but still got the error. -
Django cannot find my base template, but it's there
I am "trying" to develop a Django project with Bootstrap. Because each page requires the exact same Bootstrap code, it looks more logical to me to have one base template at project level. Learning from this guide and this guide, here's the content of my project files: settings.py 'DIRS': [(os.path.join(BASE_DIR, 'templates')),], urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.homepage, name='homepage'), ] views.py def homepage(request): return render(request, 'homepage/index.html') index.html {% extends 'base.html' %} {% block title %}Hello from index.html{% endblock %} {% block content %} This is from the index.html {% endblock %} Now when I browse the homepage of site (localhost:8000) I get TemplateDoesNotExist error. When I look at the error details I see this: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: D:\Django Projects\omidshojaee.com\omidshojaee_com\templates\base.html (Source does not exist) So Django is looking into the correct folder, and base.html is there (I can see it with my own eyes), so why Django cannot load it?