Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python manage.py startapp item doesn't work for me
I saw this command work in my django video courses but unfortunately it doesn't work for me when I enter python manage.py startapp item it returns an error which says : File "D:\Django\puddle\manage.py", line 22, in <module> main() File "D:\Django\puddle\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\Django\env\lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "D:\Django\env\lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() File "D:\Django\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\Django\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "D:\Django\env\lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Users\Msk\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'item' I just tried to install this app to learn the rest of the Django course but it says the item module not found! -
How to avoid client caches (Chrome) on django react app?
I have a django-react app that is serving out of Heroku. I use webpack to build static files, which I serve out of a Django app called frontend. Django static files serving adds a hash to the webpack generated files for cache breaking on new releases. To illustrate, here is the index.html that is served for my site: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="/static/favicon.e62ca627caf.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <link rel="stylesheet" type="text/css" href="/static/frontend/css/index.e861872e9ba7b.css"/> <link rel="manifest" href="/static/manifest.a22d2aecab21fe.json" /> </head> <body> <div id="root"></div> <script src="/static/frontend/js/index.a39c981a0accf.js"></script> </body> </html> Cache-Control for index.html is set to max-age=0. I thought this setup would be good enough for breaking client caches when I release a new frontend version of my site (since index.*.js would have a new hash). However, I observed that some of my clients had stale versions up to two weeks ago even with this setup (using Chrome on Windows). How is this possible? Am I missing something to break client caches for new frontend releases? -
Django and tensorflow app deployed with heroku
I am sorta new to django and heroku and but I made a django app which intakes user values, processes them through a tensorflow model which was trained and loaded by doing: enter image description here Locally, my app works just fine but now I am trying to deploy it using heroku and I am finding lots of trouble. My main issue is when I run 'git push heroku main' this is what I get: enter image description here I have tried changing my python versions even using different tensorflow versions as well. I am currently in python-3.11.6 but I have tried running this with python-3.10.13 and python-3.9.18. If anyone can help that would be appreciated. Thank you for your time. -
Django with html chartjs
"I use Django to create a web app with HTML, and I want to change the format of numbers in the graph from 123456.123456 to 123,456.12. I've tried using floatformat:'2g' or .toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","), but the values in each point are separated by commas, like [1123,2212]. The expected result should be like 1,123 and 2,212 as usual, but in the graph, I get: Point 1: 1 Point 2: 123 Point 3: 2 Point 4: 212 Please help." my code : new Chart(chartLineCanvas, { type: 'line', data: { labels: labels, datasets: [ { label: 'Total Sales (Baht)', borderColor: 'rgba(0, 0, 255, 1)', backgroundColor: 'rgba(0, 0, 255, 0.2)', data: data }, { label: 'Average Sales Present (Baht)', borderColor: 'rgba(255, 165, 0, 1)', backgroundColor: 'rgba(255, 0, 0, 0)', data: Array(data.length).fill(data.reduce((a, b) => a + b, 0) / data.length), }, { label: 'Average Sales Before(Baht)', borderColor: 'rgba(255, 0, 0, 1)', backgroundColor: 'rgba(255, 0, 0, 0)', data: Array(averagedata.length).fill(averagedata.reduce((a, b) => a + b, 0) / averagedata.length), }, ], }, options: { mode: 'index', bodyFontSize: 20, locale: 'en-US', tooltips: { callbacks: { label: function (tooltipItem, data) { var datasetLabel = data.datasets[tooltipItem.datasetIndex].label || ''; var value = tooltipItem.yLabel; return datasetLabel + ': ' + value.toLocaleString('en-US', { style: 'decimal', … -
Problems with django testing?
I am developing a django app and currently testing it as well, this is my view: from django.http import JsonResponse, HttpResponseBadRequest from store.models import Product from .basket import Basket # Create your views here. def basket_summary(request): basket = Basket(request) return render(request, "store/basket/summary.html", {"basket": basket}) def basket_add(request): basket = Basket(request) if request.POST.get("action") == "post": product_id = int(request.POST.get("productid")) product_qty = int(request.POST.get("productqty")) product = get_object_or_404(Product, id=product_id) basket.add(product=product, product_qty=product_qty) basket_qty = basket.__len__() response = JsonResponse({"qty": basket_qty}) return response def basket_delete(request): basket = Basket(request) if request.POST.get("action") == "post": product_id = int(request.POST.get("productid")) basket.delete(product_id=product_id) basket_qty = basket.__len__() basket_total = basket.get_total_price() response = JsonResponse({"qty": basket_qty, "subtotal": basket_total}) return response def basket_update(request): basket = Basket(request) if request.POST.get("action") == "post": product_id = int(request.POST.get("productid")) product_qty = int(request.POST.get("productqty")) basket.update(product_id=product_id, product_qty=product_qty) basket_qty = basket.__len__() basket_total = basket.get_total_price() response = JsonResponse({"qty": basket_qty, "subtotal": basket_total}) return response My urls.py file is also below: from .views import basket_summary, basket_add, basket_delete, basket_update app_name = "store_basket" urlpatterns = [ path("", basket_summary, name="basket_summary"), path("add/", basket_add, name="basket_add"), path("delete/", basket_delete, name="basket_delete"), path("update/", basket_update, name="basket_update"), ] Finally my testing file: from django.contrib.auth.models import User from django.test import TestCase from django.urls import reverse from store.models import Category, Product from json import loads class TestBasketView(TestCase): def setUp(self): category = Category.objects.create(name="django", slug="django") user = User.objects.create(username="admin") … -
format datetimeinput in django
I have a booking site and I want the booking to be permanent only by hours (I don't want minutes) an example of John booked from 8 to 10 o'clock And I don't want 8:10 to 10: 30 pm Can I remove the minutes from DateTimeInput format that the user cannot choose them and selects only the hour look at the picture here enter image description here Or any other way to do this -
Docker Compose - could not translate host name "database" to address: Name or service not known
When i run docker-compose up it gives me this error. Im using Django and React to build the application, as listening with gunicorn for server. I know i dont need to create a network because compose do this byself, but i tryed everything i found and nothing solved my problem, any sugestions? django.db.utils.OperationalError: could not translate host name "database" to address: Name or service not known failed to solve: process "/bin/sh -c python manage.py migrate" did not complete successfully: exit code: 1 Dockerfile FROM python:3.9.13 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY . /app WORKDIR /app RUN pip3 install -r requirements.txt RUN python manage.py makemigrations RUN python manage.py migrate CMD gunicorn -b 0.0.0.0:8000 --worker-class=gevent --worker-connections=1000 --workers=5 backend.wsgi docker-compose.yaml version: "3" services: database: container_name: database networks: - djangonetwork image: postgres:12.7-alpine expose: - "5432" volumes: - ./backup_data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=dockerteste - POSTGRES_USER=postgres - POSTGRES_PASSWORD=pw1234 backend: build: ./finapp volumes: - ./finapp:/app depends_on: - database networks: - djangonetwork frontend: build: ./frontend volumes: - ./frontend:/app depends_on: - backend ports: - 80:80 nginx_backend_server: build: ./nginx ports: - 8000:8000 depends_on: - backend networks: djangonetwork: driver: bridge -
How to pass a list of dates from Django ORM to a javascript date list to use as labels in chart.js
I'm trying to plot some charts comparing the close price of pairs of stocks in a timeline. My Django view.py function looks like this: # Access stock pairs for the user settings stock_pairs = StockPair.objects.filter(setting=setting) # Create a context dictionary including, for each stock_pair in stock_pairs, the close prices of the stocks in the pair and pass the dictionary to the template context = {} stocks_and_pair_data_list = [] for stock_pair in stock_pairs: stocks_and_pair_data = {} stocks_and_pair_data['stock1_name'] = stock_pair.stock1.name stocks_and_pair_data['stock2_name'] = stock_pair.stock2.name stocks_and_pair_data['dates'] = [dt for dt in stock_pair.stock_pair_data_set.values_list('date', flat=True)] stocks_and_pair_data['stock1_close_prices'] = [float(close) for close in stock_pair.stock1.stock_data_set.values_list('close', flat=True)] stocks_and_pair_data['stock2_close_prices'] = [float(close) for close in stock_pair.stock2.stock_data_set.values_list('close', flat=True)] stocks_and_pair_data_list.append(stocks_and_pair_data) context['stocks_and_pair_data_list'] = stocks_and_pair_data_list return render(request, 'my_page.html', context) and my_page.html has this script section: <!-- For each stocks_and_pair_data in stocks_and_pair_data_list create, using chart.js, a chart of the close prices of stock1 and stock2 --> {% for stocks_and_pair_data in stocks_and_pair_data_list %} <script> const ctxClose = document.getElementById('ChartOfClosePrices{{ forloop.counter }}'); new Chart(ctxClose, { type: 'line', data: { labels: '{{stocks_and_pair_data.dates}}', datasets: [{ label: '{{ stocks_and_pair_data.stock1_name }}', data: '{{stocks_and_pair_data.stock1_close_prices}}' },{ label: '{{ stocks_and_pair_data.stock2_name }}', data: '{{stocks_and_pair_data.stock2_close_prices}}' }] } }); </script> {% endfor %} I'm having 2 problems. The first problem is that I get the following error on the browser … -
Why is my Django view not automatically downloading a file
My view transcribes a file and outputs the SRT transcript. Then it locates and is supposed to auto download theT transcript but nothing happens after transcription completes(the file was submitted on a previous page that uses the transcribeSubmit view. The view that handles and returns the file is the initiate_transcription view). Here is my views.py: @csrf_protect def transcribeSubmit(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['file'] fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) request.session['uploaded_file_name'] = filename request.session['uploaded_file_path'] = fs.path(filename) #transcribe_file(uploaded_file) #return redirect(reverse('proofreadFile')) return render(request, 'transcribe/transcribe-complete.html', {"form": form}) else: else: form = UploadFileForm() return render(request, 'transcribe/transcribe.html', {"form": form}) @csrf_protect def initiate_transcription(request): if request.method == 'POST': # get the file's name and path from the session file_name = request.session.get('uploaded_file_name') file_path = request.session.get('uploaded_file_path') if file_name and file_path: with open(file_path, 'rb') as f: path_string = f.name transcribe_file(path_string) file_extension = ('.' + (str(file_name).split('.')[-1])) transcript_name = file_name.replace(file_extension, '.srt') transcript_path = file_path.replace((str(file_path).split('\\')[-1]), transcript_name) file_location = transcript_path with open(file_location, 'r') as f: file_data = f.read() response = HttpResponse(file_data, content_type='text/plain') response['Content-Disposition'] = 'attachment; filename="' + transcript_name + '"' return response else: #complete return render(request, 'transcribe/transcribe-complete.html', {"form": form}) def transcribe_file(path): #transcription logic JS: const form = document.querySelector('form'); form.addEventListener('submit', function (event) { event.preventDefault(); const formData = … -
Cannot for the life of me figure out how to get form post to work?
I have an app called search. Here is urls.py from django.urls import path from . import views app_name = "search" urlpatterns = [ path("", views.UsersView.as_view(), name="all_users"), ] Here is models.py from django.db import models class User(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() email = models.EmailField() Here is forms.py from django import forms class UserForm(forms.Form): name = forms.CharField(label="Name", max_length=100) age = forms.IntegerField(label="Age") email = forms.EmailField(label="Email") Here is views.py from django.views import View from search.forms import UserForm from .models import User class UsersView(View): def get(self, request): try: user_list = User.objects.order_by("-name") form = UserForm() except User.DoesNotExist: raise Http404("Users do not exist") return render(request, "search/index.html", {"user_list": user_list, "form": form}) def post(self, request): try: form = UserForm(request.POST) if form.is_valid(): newUser = User(name=request.POST["name"], age=request.POST["age"], email=request.POST["email"]) newUser.save() except: raise Http404("Error when trying to add new user") return redirect('/') And lastly, here is index.html {% if user_list %} <h1>Here are all the users</h1> <ul> {% for user in user_list %} <li><a href="/search/{{ user.id }}/">{{ user.name }}</a></li> {% endfor %} </ul> <h1>Add a user</h1> <form action="/search/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% else %} <p>No users are available.</p> {% endif %} The form displays just fine for me, but when I enter in … -
I can't get my homepage returning httpresponse what could be the issue?
from django.shortcuts import render, HttpResponse Create your views here. def home(request): return HttpResponse('Welcome to Location Intelligence Kenya!') Whenever i run the my server i get the output below i can't seem to locate where the problem is -
Django - inconsistent password hashing
Trying to build the user manager boilerplate of a Django (DRF) project. Facing some really weird issues when registering a user. First problem I encountered was passwords not being hashed. After some investigation I found out that the auth package has make_password function, which generates a hash from a given string. But then I noticed that I cannot authenticate these users. Tried to setup my own authentication logic using the check_password of the same package, when I realized, that the password hash stored in the database is completely different from the hash generated by make_password and passed to the set_password method of the user instance. I know I should provide some code, but the computer running the code doesn't have internet access (my wi-fi adapter has died) , but the structure of the user manager, view and serializer is almost same as here: https://github.com/dotja/authentication_app_react_django_rest/tree/main/backend I do use user.save() after setting up the password. I need to figure out either why the user's password not getting hashed without using the make_password function, or why the stored hash is different when using the make_password function. Thanks. -
Django - data from form (ModelForm) do not save in existing database
Im trying to send via form data to my database as new object of my Task model. When I click submit button it only redirects me to my other page, nothing happens with submitted data and data is not saved to my db. I looked for solution in multiple sources but didn't find one. I am begginer with this topic so every feedback would be great. My questions: Where I made mistake If i have prepopulated slug field in my admin.py (from title field) will it be prepopulated in forms when i exclude my slug field? 3.I would appreciate for useful knowledge sources. model.py class Task(models.Model): is_done = models.BooleanField(default=False) title = models.CharField(max_length=100) add_time = models.DateTimeField(auto_now_add=True) deadline = models.DateTimeField() user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") slug = models.SlugField() description = models.TextField() forms.py from django import forms from .models import Task class TaskForm(forms.ModelForm): class Meta: model = Task exclude = ["add_time", "is_done"] template <form method="post" class="form" action="{% url 'add-task' %}"> {% csrf_token %} <p>Title: {{ form.title }}</p> <p>Deadline: {{ form.deadline }}</p> <p>User: {{ form.user }}</p> <p>Description: {{ form.description }}</p> <button type="submit">Submit</button> </form> views.py def add_task(request): if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect("/todolist") form = TaskForm() return render(request, "todolist/add_task.html", … -
Django generating python file
I am building site in django and I have table with data: <th>name</th> <th>data</th> data is necessary in my client-side python program sender.py. User double click on specific row and using pyinstaller compile it with data which user selected stored as const in python program and then download it. I manage to make JS script witch shows what row you selected, but I cant figure out how to insert data into python program, use run pyinstaller on that file and then download it. Python program have function which takes that data but is not necessary Python: from somelib import func constData = data def clientFunc(constData): if constData != None or len(constData) <= 0: print("Argument constData is valid") else: constData = str(constData) client = func(constData, 9999) client.func2() or from somelib import func constData = data if constData != None or len(constData) <= 0: print("Argument constData is valid") else: constData = str(constData) client = func(constData, 9999) client.func2() JS: const table = document.getElementById('table'); const rows = table.getElementsByTagName('tr'); Array.from(rows).forEach((row, index) => { row.addEventListener('dblclick', () => { const cells = row.getElementsByTagName('td'); console.log(cells[0]); console.log(cells[1]); const content1 = cells[0].innerHTML; alert(content1) }); }); I will be grateful for at least one of these things. Cheers! -
NextJS and Django Project Deploy
Does anyone know how to deploy the django+nextJs app currently, my frontend is running on localhost:3000 and Django at 127.0.1:8000 and its is working perfectly on my local machine I want to deploy it on a live server anyone who knows how to do this I have deployed the next app on Vercel (https://cropsight-dusky.vercel.app/) but it will not move further from login unless Django is also running simultaneously. I have checked it If the nextJs project is running on Vercel and my Django is running locally then the request from front end will come to me -
How can I separate my labels in the x-axis into separate "categories" in my chart?
If my question didn't make sense then let me explain. Basically I am creating a web app for tracking expenses and I want to incorporate a chart to showcase the expenses in a graphical way. I have made for categories which take in separate data, but for some reason when I render the chart it shows all the categories combined as one. (Attachment is provided) Image of the Bar chart. For this reason only the line and bar chart show but the doughnut (which I want) and the pie charts don't work am guessing because of how the labels (categories) are combined into one. Here is the code for my js file: const renderChart = (data, labels) => { const ctx = document.getElementById('myChart').getContext('2d'); new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: 'Current Month Expenses', data: data, }] }, options: { borderWidth: 10, borderRadius: 2, hoverBorderWidth: 0, plugins: { legend: { display: false }, }, }, }); } const getChartData=() => { console.log("fetching") fetch('expense_category_summary') .then((res)=>res.json()) .then((results)=>{ console.log("results", results); const category_data = results.expense_category_data; const [labels, data] = [ Object.keys(category_data), Object.values(category_data), ]; renderChart([data], [labels]); }); }; document.onload = getChartData(); Please help, I am in a tight deadline. If there … -
Django quiz- multiple question- database falsely saves correct answers
I am striving to build a multiquestion quiz option, but I cannot get my postgreSQL save the correct data. The database only saves the first option without it mattering whether it is the correct answer or not and whether there are more correct answers. "GET /multi-form/ HTTP/1.1" 200 7693 <QueryDict: {'csrfmiddlewaretoken': ['ALONiRKNa0QKQe6LQWacVz9vSQZPbFuyfdaLimGg9czBEy46hQAbAGyQatRLpI33'], 'question': ['Question100'], 'language_name': ['5'], 'ans_count': ['5'], 'answer_0': ['99'], 'answer_1': ['98'], 'answer_2': ['97'], 'is_correct_2': ['on'], 'answer_3': ['Qaz'], 'answer_4': ['Dacia'], 'is_correct_4': ['on'], 'Submit': ['Senden']}> 5 True [{'text': '99', 'is_correct': False}] 99 is chosen as the only answer, but it is not correct ans I chose more correct options as you can spot on the screenshot. forms.py class AddMultipleForm(forms.ModelForm): ans_count = forms.IntegerField(min_value=1, label="Number of Answers Anzahl der Antworten") class Meta: model = MultiQuesModel fields = ["question", "language_name"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) ans_count = self.initial.get("ans_count", 1) for i in range(ans_count): self.fields[f"answer_{i}"] = forms.CharField(max_length=200, required=True) self.fields[f"is_correct_{i}"] = forms.BooleanField( required=False, widget=forms.CheckboxInput(attrs={"class": "checkbox"}) ) def clean(self): cleaned_data = super().clean() ans_count = cleaned_data.get("ans_count") print(ans_count) answers = [] for i in range(ans_count): answer_text = cleaned_data.get(f"answer_{i}") is_correct = cleaned_data.get(f"is_correct_{i}") if answer_text: answers.append({"text": answer_text, "is_correct": is_correct}) if not answers: raise forms.ValidationError( "Please fill out at least one answer. Bitte füllen Sie mindestens eine Antwort aus." ) cleaned_data["answers"] … -
React, When i call handleSubmit() function i am sending data in application/json and multiform/data to backend but none data in student_image: null
please see the code that I have to handle application/json and multiform/data type of data along with other fields student_image: fileState, where fileState is e.target.file[0] value which is the image and other field are just application/json i think but this fileState need multiform/data. how to sent data to api as my api accepts list object of all or any other idea to store image along with other field value in models.py in drf const handleSubmit = () => { let dataToSend = {}; if (Array.isArray(formData)) { // Handle array data dataToSend = formData.map((formFields, index) => ({ // // Map the fields accordingly for each object in the array // // Adjust this based on your data structure sn: formFields.sn, student_image: fileState, // Add other fields as needed })); } else if (typeof formData === 'object') { // dataToSend = [formData] // Handle object data dataToSend = [{ // Map the fields accordingly for the object // Adjust this based on your data structure nepali: formData.nepali, international: formData.international, graduate_school_or_campus: formData.Campus, student_image: fileState, first_name: formData.first_name, middle_name: formData.middle_name, last_name: formData.last_name, email: formData.email, contact_no: formData.contact_no, gender: formData.gender, blood_group: formData.blood_group, ethnicity: formData.ethnicity, religion: formData.religion, date_of_birth_bs: formData.date_of_birth_bs, date_of_birth_ad: formData.date_of_birth_ad, batch: formData.batch, disability_status: formData.disability_status, sponsorship_status: formData.sponsorship_status, rural_district: … -
Does user encoding of uploaded files matter and how to configure it?
I'm making a site on Django. The functionality is as follows - users can download pdf files for processing (converting to different formats, extracting text, etc.). This is how I receive a file from a user and process it - def post(self, request, *args, **kwargs): text = services.extract_text_from_pdf(request.FILES.get('file')) I had the following question - what if users will download files in different encodings? Does their encoding matter or do they all end up being utf-8? I read this from the Django documentation. But I didn't quite understand how to configure file encoding. -
How to use django tags in next.js javascript file?
I have a full stack application built in next.js as frontend and django as backend. The frontend is full next.js and react. I want to use django tags in the javascript pages files the code that i want to use is looking like this : {% for item in items %} <div> <a href="{% url 'item:detail' item.name %}"> <div> <img alt="{{ item.name }}" src="{{ item.image.url }}" class="rounded-t-xl"> </div> <div class="p-6 bg-white rounded-b-xl"> <h2 class="text-2xl">{{ item.name }}</h2> <p class="text-gray-500">Price: {{ item.price }}</p> </div> </a> </div> {% endfor %} Those are some information for an item that is stored in the database through django. I checked another post from stackoverflow and said something like this You can't add any Django template code in js file directly. There are 3 ways you can add the first_name in js file. Write a django ajax views and call the api for first_name from your js file as soon as your page is loaded. or render your first name in your html file hidden input fields and than grab the fields value it's name or id from your jsfile or put a utill function on your html js <sccript> tags which are gonna call you driver.js … -
Django CSRF with Angular frontend served from different domains
I have a dockerized Django backend that uses DRF, django cors headers to allow communications over localhost to the Angular app. The docker-compose.yml file looks like this: version: "3.9" services: db: image: postgres volumes: - ./postgres/db:/var/lib/postgresql/data ports: - "5432:5432" environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres backend: container_name: backend-dev-diary build: context: . dockerfile: ./build/backend/dockerfile command: sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - ./backend/dev_diary:/code ports: - "8005:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db frontend: container_name: frontend-dev-diary build: context: . dockerfile: ./build/frontend/dockerfile command: sh -c "npm install && ng serve --poll 2000 --host 0.0.0.0 --disable-host-check" volumes: - ./frontend/dev-diary:/code ports: - "8080:4200" depends_on: - backend I want to use session based auth and csrf protection on angular. In the django settings I've set: CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", ] REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.IsAuthenticated"], "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", ], "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination", } CSRF_COOKIE_SAMESITE = "Lax" SESSION_COOKIE_SAMESITE = "Lax" CSRF_COOKIE_HTTPONLY = True SESSION_COOKIE_HTTPONLY = True CSRF_TRUSTED_ORIGINS = [ "http://localhost:8080", ] if DEBUG == False: CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True Now I created an endpoint that generates a CSRF token and I read the value in Angular. Now when I make a request I include credentials and … -
Django order by pviot table column
I want to order tasks within a bucket based on the 'order' column in the 'bucket_task' table. Tasks and buckets have a many-to-many relationship. How can I achieve this? My models: class Bucket(AbstractModel): user = models.ForeignKey(User, related_name='buckets', on_delete=models.deletion.DO_NOTHING) unique_id = models.CharField(max_length=255, default=uuid.uuid4, unique=True) title = models.CharField(max_length=191, blank=True) order = models.IntegerField(default=1) class Task(AbstractModel): user = models.ForeignKey(User, related_name='tasks', on_delete=models.deletion.DO_NOTHING) unique_id = models.CharField(max_length=255, default=uuid.uuid4, unique=True) title = models.CharField(max_length=191, blank=True) class BucketTask(AbstractModel): bucket = models.ForeignKey(Bucket, on_delete=models.deletion.CASCADE) task = models.ForeignKey(Task, on_delete=models.deletion.CASCADE) order = models.IntegerField(default=1) My view: class BucketsView(generics.ListCreateAPIView): permission_classes = [IsAuthenticated] serializer_class = BucketSerializer model = Bucket def get_queryset(self): queryset = self.model.objects.filter( user=self.request.user, deleted_on__isnull=True ).prefetch_related( 'tasks' ).select_related('user').order_by('order') return queryset My Serializer: class BucketSerializer(ModelSerializer): tasks = TaskSerializer(many=True, read_only=True) class Meta: model = Bucket fields = "__all__" read_only_fields = ['unique_id', 'tasks'] extra_kwargs = {"user": {"required": False}} -
Error while using migrate in Django to postgresql
`I am using postgresql as database for my django project and it is showing me that i don't have permission to even create the data tables when I run migrate command. Error: django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (permission denied for schema public LINE 1: CREATE TABLE "django_migrations" ("id" bigint NOT NULL PRIMA... ^ ) My code: `DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "knapds", "USER": "admin", "PASSWORD": "password", "HOST": "127.0.0.1", "PORT": "5432", } }` `CREATE DATABASE knapds; CREATE USER knapds WITH PASSWORD 'password'; ALTER ROLE system SET client_encoding TO 'utf8'; ALTER ROLE system SET default_transaction_isolation TO 'read committed'; ALTER ROLE system SET timezone TO 'Africa/Johannesburg'; GRANT ALL PRIVILEGES ON DATABASE knapds TO system; \q`` -
How to generate automatically links to picture with spec. size?
I'm a beginner in programming, I've done a small project in Django, but nothing special. I was given a recruitment task with Django RESTframework, but I don't really know how to approach it. I don't want a ready-made solution, but some guidance or advice on how to go about it. Possibly a shared coding :) Task: Using Django REST Framework, write an API that allows any user to upload an image in PNG or JPG format. You are allowed to use any libraries or base projects / cookie cutters you want (but using DRF is a hard requirement). Skip the registration part, assume users are created via the admin panel. Requirements: it should be possible to easily run the project. docker-compose is a plus ## This is no problem. This is main problem. users should be able to upload images via HTTP request users should be able to list their images there are three builtin account tiers: Basic, Premium and Enterprise: users that have "Basic" plan after uploading an image get: a link to a thumbnail that's 200px in height users that have "Premium" plan get: a link to a thumbnail that's 200px in height a link to a thumbnail … -
aws elastic beanstalk deployment error: 502 gateway error
I've been trying to deploy a django application using Django 4.2.6 on the latest platform that AWS EB has to provide: Python 3.9 running on 64bit Amazon Linux 2023/4.0.4 After any try or redeploy I've been getting a 502 Bad gateway issue and I would appreciate some help in debugging this. On the web.stdout.log file I see this log line: web[2059]: ModuleNotFoundError: No module named 'ebdjango.wsgi' which is confusing because I don't see anything I've done different than what's been suggested across the internet via blogposts and so on. All my sourcecode is available here: https://github.com/kolharsam/assignment-practical-swe These are the links I've been looking into: https://medium.com/@justaboutcloud/how-to-deploy-a-django3-application-on-elastic-beanstalk-python3-7-and-amazon-linux-2-bd9b8447b55 https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html https://testdriven.io/blog/django-elastic-beanstalk/