Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error running Django and Ghost in Docker Compose: 'manage.py' file not found and database access denied
I'm trying to set up a Docker Compose configuration to run Django and Ghost together, but I'm encountering some issues. Here are the relevant files: dockerfile: FROM python:3.12-rc-bullseye WORKDIR /django_dir COPY requirements.txt . RUN pip install -r requirements.txt COPY . /django_dir docker-compose.yml: version: '3.1' services: db: image: mysql:8.0 restart: always environment: MYSQL_USER: example MYSQL_PASSWORD: example MYSQL_ROOT_PASSWORD: example volumes: - ./mysql_dir:/var/lib/mysql networks: - nginx ghost: image: ghost:latest restart: always ports: - 2368:2368 environment: database__client: mysql database__connection__host: db database__connection__user: example database__connection__password: example database__connection__database: ghost url: https://example.com.br volumes: - ./ghost_dir:/var/lib/ghost/content networks: - nginx depends_on: - db django: build: context: . dockerfile: dockerfile restart: always ports: - 8000:8000 environment: - DEBUG=1 command: python /django_dir/manage.py runserver 0.0.0.0:8000 networks: - nginx volumes: - ./django_dir:/django_dir networks: nginx: name: nginx-proxy external: true When I run docker-compose up, I'm getting the following errors: For the Django service: python: can't open file '/django_dir/manage.py': [Errno 2] No such file or directory For the Ghost service: Access denied for user 'example'@'172.18.0.4' (using password: YES) I have checked the file paths and database credentials, but I can't seem to find a solution. What could be causing these errors? How can I fix them? Any help or suggestions would be greatly appreciated. Thank you! -
Retrieving data from an Excel file in Django using Pandas: How can I include duplicates that are being overwritten by Python?
I am creating a django application which retrieves data from an excel file. The excel file I access the excel file through the scrape.py file: import pandas as pd import os from pathlib import Path BASE_DIR = Path(file).resolve().parent DATA_DIR = os.path.join(BASE_DIR, "Data") database_path = os.path.join(DATA_DIR, "Data.xlsx") Database = pd.read_excel(database_path) Then I have this class: class skimask: def init(self, name, GradesWDates, motive, avgGrade, highestgrade, pfp, nexttest, recentgrades, tens): self.name = name self.GradesWDates = GradesWDates self.motive = motive self.avgGrade = avgGrade self.highestgrade = highestgrade self.pfp = pfp self.nexttest = nexttest self.recentgrades = recentgrades self.tens = tens self.subjects = {} Evan = skimask('Evan', dict(zip(Database.Evan, Database.Date)), "B", 0, 0, "./static/media/evan1.png", list(Database.EvanNext), [], 0) Felix = skimask('Felix', dict(zip(Database.Felix, Database.Date)), "B+", 0, 0, "./static/media/felix.png", list(Database.FelixNext), [], 0) Hessel = skimask('Hessel', dict(zip(Database.Hessel, Database.Date)), "A+", 0, 0, "./static/media/hessel2.png", list(Database.HesselNext), [], 0) Niels = skimask('Niels', dict(zip(Database.Niels, Database.Date)), "B", 0, 0, "./static/media/niels.png", list(Database.NielsNext), [], 0) Sem = skimask('Sem', dict(zip(Database.Sem, Database.Date)), "A", 0, 0, "./static/media/sem1.png", list(Database.SemNext), [], 0) Students = [Evan, Felix, Hessel, Niels, Sem] This excel file is a file of all our grades of this year, and coincidentally there are duplicates, ofcourse. But python, for some reason, overwrites duplicates and skips over them. But I want to include those … -
How To Get Nginx Client Ip Using Revese Proxy (Django, Nginx)
I'm facing an issue with retrieving the client IP addresses from the X-Forwarded-For header when using Nginx as a reverse proxy server in front of my Django application. Currently, I'm only able to obtain the IP address of the Nginx proxy server instead of the actual client's IP. I have configured Nginx to set the necessary headers using the following directives: server { server_name example.domain.com; set_real_ip_from 0.0.0.0/0; real_ip_header X-Forwarded-For; real_ip_recursive on; location /static/ { root /home/user/example.domain.com/djangoapp; } location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto https; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://10.0.0.122:8000; } } I have tried it all, even using the map from this artlcle and alot more: link but the X-Forwarded-For and X-Real-IP are still the proxy server's IP and not the client IP! can't even get it to return a list and not just the last IP... In my Django view, I'm trying to access the client IP using request.META.get('HTTP_X_REAL_IP') and request.META.get('REMOTE_ADDR'). The headers are showing, but not the client's IP. { 'Content-Length': '', 'Content-Type': 'text/plain', 'X-Real-Ip': '10.0.0.101', 'X-Forwarded-Proto': 'https', 'X-Forwarded-For': '10.0.0.101', 'User-Agent': 'Mozilla/5.0 ...', even the user agenst is correct. but the IPs are not. I have also checked that the X-Forwarded-For header is … -
testdriven.io The Definitive Guide to Celery and Django getting error while tring submitting the form
The Definitive Guide to Celery and Django web sockets not working Hi, I've followed Django Channels and Celery chapter in The definitive guide to Celery and Django chapter and got the following error when I'm filling the form and press submit buttom: WebSocket connection to 'ws://localhost:8010/ws/task_status/d4e6e4e5-4000-4341-9e6d-15d1ded308e2/' failed: updateProgress @ (index):59 (anonymous) @ (index):111 I've reviewed the web app docker container logs and found the following: [29/May/2023 19:45:21] "GET /ws/task_status/e96dcec6-35f6-47f3-b55c-7379779fdeb9/ HTTP/1.1" 404 3122 [29/May/2023 19:49:44] "GET /form_ws/ HTTP/1.1" 200 4351 [29/May/2023 19:49:52] "POST /form_ws/ HTTP/1.1" 200 51 Not Found: /ws/task_status/d4e6e4e5-4000-4341-9e6d-15d1ded308e2/ But I still can't understand what's gone wrong. -
instance.save() method not updating the instance in the database
I have written this code for product checkout. I wanted to create a Order model and then update the transaction ID. But it's not getting updated, doesn't even providing any error. Whats's the issue ? @csrf_exempt @user_passes_test(lambda u: u.is_authenticated and not u.is_analyst) def processOrder(request): data = json.loads(request.body) transaction_id = datetime.now().timestamp() print(int(transaction_id)) if request.user.is_authenticated: customer = Customer.objects.get(user=request.user) order, created = Order.objects.get_or_create( customer=customer, complete=False) total = int(data['form']['total']) try: order.transaction_id = int(transaction_id) except Exception as e: print(e) order.complete = True print(order.transaction_id) try: order.save() except Exception as e: print(e) Here is my Order model that I've used. class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) date_ordered = models.DateField(default="2014-02-20") complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) @property def shipping(self): shipping = False order_items = self.orderitem_set.all() for i in order_items: shipping = True return shipping @property def get_cart_total(self): order_items = self.orderitem_set.all() total = sum([item.get_total for item in order_items]) return total @property def get_cart_items(self): order_items = self.orderitem_set.all() total = sum([item.quantity for item in order_items]) return total def __str__(self) -> str: return str(self.id) -
What is going on with my Django site, it's health check, and admin page? [closed]
I'm following a Django tutorial located here: https://dev.to/daiquiri_team/deploying-django-application-on-aws-with-terraform-minimal-working-setup-587g I successfully made it to step 4 located here: https://dev.to/daiquiri_team/deploying-django-application-on-aws-with-terraform-namecheap-domain-ssl-19a5 During Step 4, the author writes the following: I was able to receive Healthy! from the 127.0.0.1:8000/health url. Also, at one point I was able to get Bad Request from my equivalent Load Balancer domain, however I destoryed and rebuilt the underlying infrastructure, and now I get Not Found from both the AWS Load Balancer domain and the /health/ check, however the /admin/ page successfully loads and allows me to login (although I did not attempt to login). Could someone help explain what is going on? I'd like the AWS Load Balancer page to load Bad Request, same with the /admin page I presume...but the Health check should show Healthy. Lastly, my custom domain isn't working any longer either. I'm assuming that is because of my infrastructure tear down and rebuild...it updates the name servers for DNS and I think they take a days to correct. -
TypeError in Django: "float () argument must be a string or a number, not 'tuple.'"
Description: When attempting to access a specific page that relate to a cryptocurrency, in this case Dogecoin, I receive a TypeError in my Django application. "Field 'bought_price' expected a number but got (0.07314770668745041,)" reads the error notice. The traceback also states that the problem is with the float() function and that a tuple was used as the argument. The passed value, however, is not a 'tuple'. It is a numpyfloat64 type, therefore I tried passing the same value after converting it to a float type in Python. Even if I provide the form a static value, the problem still occurs. form.instance.bought_at = 45.66 results in the same issue. Could anyone help me understand why this error is occurring and how I can resolve it? Here's the relevant code: Model Code: class Order(models.Model): coin = models.CharField(max_length=100) symbol = models.CharField(max_length=50) bought_price = models.FloatField() quantity = models.IntegerField(default=1) bought_at = models.DateTimeField(default=datetime.now) user = models.ForeignKey(User, on_delete=models.CASCADE) View Code: ticker = yf.Ticker(symbols[pk]) price_arr = ticker.history(period='1d')['Close'] price = np.array(price_arr)[0] if request.method == 'POST': form = BuyForm(request.POST) if form.is_valid(): form.instance.coin = ticker.info['name'], form.instance.symbol = ticker.info['symbol'], form.instance.bought_price = price, form.instance.user = request.user form.save() return redirect('portfolio') else: form = BuyForm() I appreciate any assistance or insights you can provide. Thank … -
How can I fix the error of not being able to establish a connection to a Django Channels server with WebSockets using Python and ASGI?
Django channels & websockets : can’t establish a connection to the server. I am trying to do a real-time drawing app using django channels, websockets & p5. The only problem I've got is : Firefox can’t establish a connection to the server at ws://XXX.XXX.XXX.XXX:8090/ws/room/1/. What I've done : settings.py : INSTALLED_APPS = [ ... 'channels', ] ASGI_APPLICATION = 'DrawMatch.asgi.application' CHANNEL_LAYERS = { 'default': { "BACKEND": "channels.layers.InMemoryChannelLayer" } } asgi.py : os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DrawMatch.settings') django_asgi_app = get_asgi_application() application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( drawmatch_app.routing.websocket_urlpatterns ) ) ), }) consumers.py : class DrawConsumer(AsyncJsonWebsocketConsumer): room_code: str = None room_group_name: str = None async def connect(self): self.room_code = self.scope['url_route']['kwargs']['room_code'] self.room_group_name = f'room_{self.room_code}' print(f"room_code: {self.room_code}") print(f"room_group_name: {self.room_group_name}") await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data: str = None, _: Any = None) -> None: data = json.loads(text_data) await self.channel_layer.group_send( self.room_group_name, { 'type': 'draw', 'data': data } ) async def send_message(self, res): await self.send(text_data=json.dumps({ "payload": res })) routing.py : websocket_urlpatterns = [ url(r'^ws/room/(?P<room_code>\w+)/$', DrawConsumer.as_asgi()), ] views.py : def room(request, room_code): context = { 'room_code': room_code } return render(request, 'room.html', context) urls.py : urlpatterns = [ path('', views.home), ... path('room/<room_code>/', views.room), path('predict', draw_guess.main), … -
Celery task queue not blocking to single thread - what am I doing wrong?
I'm trying to reproduce example from Celery official Task Cookbook (link: Ensuring a task is only executed one at a time) and I can't figure out why my Celery task queue is not blocked to single thread. So here is my code snippet (it is almost exactly the same as in the official doc): from celery import shared_task from celery.utils.log import get_task_logger from django.core.cache import cache logger = get_task_logger(__name__) LOCK_EXPIRE = 60 * 10 @contextmanager def memcache_lock(lock_id, oid): timeout_at = time.monotonic() + LOCK_EXPIRE - 3 status = cache.add(lock_id, oid, LOCK_EXPIRE) try: yield status finally: if time.monotonic() < timeout_at and status: cache.delete(lock_id) @shared_task(bind=True, name="print_text") def print_text(self, text): text_hexdigest = md5(text.encode("utf-8")).hexdigest() lock_id = "{0}-lock-{1}".format(self.name, text_hexdigest) logger.debug("Printing text: %s", text) with memcache_lock(lock_id, self.app.oid) as acquired: if acquired: import time time.sleep(5) return logger.debug("Print_text %s is already being imported by another worker", text) When I call the print_text function several times, the first call should block the second (and all subsequent) calls - this is expected behavior: # ./manage.py shell from django_celery_example.celery import print_text task = print_text.delay('John') task = print_text.delay('John') But when I check the Celery output, both tasks run in parallel, without thread blocking (look at the time difference between the first and the … -
How can I allocate chat memory to the openai model
I'm working in django, I have a view where I call the openai api, and in the frontend I work with react, where I have a chatbot, I want the model to have a record of the data, like the chatgpt page does. class chatbot(APIView): def post(self, request): chatbot_response = None if api_key is not None and request.method == 'POST': openai.api_key = api_key user_input = request.data.get('user_input') prompt = user_input response = openai.Completion.create( model = 'text-davinci-003', prompt = prompt, max_tokens=250, temperature=0.5 ) chatbot_response = response["choices"][0]["text"] if chatbot_response is not None: return Response({"response": chatbot_response}, status=status.HTTP_200_OK) else: return Response({'errors': {'error_de_campo': ['Promt vacio']}}, status=status.HTTP_404_NOT_FOUND) I was planning to create a model and save the questions in the database, but I don't know how to integrate that information into the view, I'm worried about the token spending, I don't really know how it works. I hope someone can clarify these doubts for me. thank you so much. -
How can I properly interact with many-to-many relationship in Django+GraphQL when working with Project and User models?
How do I properly interact with many-to-many relationship in Django+GraphQL? I have a Project model which has a many to many relationship to User model. class Project(models.Model): title = models.CharField(max_length=256, blank=True) users = models.ManyToManyField(to=User, blank=True, related_name='projects') class User(AbstractUser): email = models.EmailField(max_length=128, verbose_name='email address', blank=False) EMAIL_FIELD = 'email' USERNAME_FIELD = 'username' I need to connect it to GraphQL so I can read and modify that fields via mutations. I already have a schema to work with Project without users but now I need to add users as well { projects { edges { node { id title } } } } But it doesn't work when I add users because the Project table in db doesn't have a users field. It has the projects_project_users table that describes their relationship. How can I modify my code to be able to work with project.users field? -
Display post Data in a Bootstrap Modal in Django
I'm trying to Display data in a Modal from a Post Request to my Django backend. $(function (e) { $(".form-select").change(function (event) { let $vid = this.value; let $hostname =$(this).closest('tr').find('td.hostname').text(); for(var i = 0; i < this.options.length; i++){ //deselect the option this.options[i].selected = false; } $.ajax({ type: "POST", url: '/api/vulinfo', data: { 'client': $hostname, 'vid' : $vid, 'csrfmiddlewaretoken': '{{ csrf_token }}' }, success: function(response) { $('#vulmodal').modal("show"); } }); }); The correct hostname and vid is send to my Django View. def vulInfo(request): qs = clientvul.objects.all().filter(client=request.POST['client']).filter(VID=request.POST['vid']) return render(request,'browseDB.html', {'vuldata':qs}, status=200) I try to access the Data in the Modal, but it´s always empty <div class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true" id="vulmodal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <h1>Path:{{vuldata.Path}} </h1> text text text </div> </div> </div> Models.py from django.db import models from django.contrib import admin class client(models.Model): client= models.CharField(max_length=50,primary_key=True) user= models.CharField(max_length=100) vuls = models.ManyToManyField( 'vul', through='clientvul', related_name='client' ) class vul(models.Model): vid=models.IntegerField(primary_key=True) cvelist=models.CharField(max_length=50) cvsscore=models.FloatField(max_length=5) serverity=models.CharField(max_length=25) title=models.CharField(max_length=1000) summary=models.CharField(max_length=1000) class clientvul(models.Model): client= models.ForeignKey(client, on_delete=models.CASCADE) vid=models.ForeignKey(vul, on_delete=models.CASCADE) path=models.CharField(max_length=1000) isActive=models.BooleanField(default=True) class Meta: constraints = [ models.UniqueConstraint( fields=['client', 'VID'], name='unique_migration_host_combination' # legt client und VID als Primarykey fest ) ] admin.site.register(client) admin.site.register(vul) admin.site.register(clientvul) -
django makemigrations --check with output?
I'm trying to combine two behaviours of the makemigrations command in my CI: makemigrations --check will return non-zero when a migration file needs to be generated makemigrations --dry-run will print details about the ungenerated migration makemigrations --check --dry-run behaves as makemigrations --check (since Django 4.2). My CI script needs to fail if there are ungenerated migrations and it would be helpful if it also described the missing migrations. Is there a cleaner way to do this besides some bash tricks involving both options? -
Why is my Django CreateView not adding new recipes to the database?
My Django CreateView doesn't submit data to the database. I am an absolute beginner when it comes to Django and creating websites and I feel like there's something that i haven't quite understood yet. I tried following tutorials and ended up with a draft of a recipe sharing website for a uni project, but, even thought the other CRUD views can access the database, it looks like the one that's supposed to create a new recipe can not. It does not display any errors, nor show something not working, when I press "Confirm" it justs refreshes the page and doesn't add anything to my database (I'm using Django's default db). This is my code, sorry for the poor quality but I'm doing my best to learn: Models: class Category(models.Model): CATEGORY_CHOICES = [ ('Easy', 'Easy'), ('Medium', 'Medium'), ('Hard', 'Hard'), ] name = models.CharField(max_length=100, choices=CATEGORY_CHOICES) def __str__(self): return self.name class Meta: app_label = 'recipes' class Ingredient(models.Model): name = models.CharField(max_length=125) amount = models.CharField(max_length=250, blank=True, null=True) def __str__(self): return self.name class Meta: app_label = 'recipes' class Recipe(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) description = models.TextField() ingredients = models.ManyToManyField(Ingredient, related_name='recipes') instructions = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) … -
Supervisorctl refused connection
I am running Django-huey as a background task using a supervisor. Once the supervisor is started, I get a ConnectionRefusedError: [Errno 111] Connection refused task.conf [program:encryption] command=/home/user/apps/venv/bin/python /home/user/apps/project-dir/manage.py djangohuey --queue encryption user=user autostart=true autorestart=true redirect_stderr = true stdout_logfile = /etc/supervisor/realtime.log supervisord.conf [unix_http_server] file=/var/run/supervisor.sock chmod=0700 [supervisord] logfile=/var/log/supervisor/supervisord.log pidfile=/var/run/supervisord.pid childlogdir=/var/log/supervisor [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [supervisorctl] serverurl=unix:///var/run/supervisor.sock [include] files = /etc/supervisor/conf.d/*.conf [inet_http_server] port=127.0.0.1:9001 [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface -
ValueError: Cannot assign "(<SimpleLazyObject: <User: bhavna>>,)": "cart.user" must be a "User" instance
i am just learning to add ForeignKey instance in table ValueError: Cannot assign "(<SimpleLazyObject: <User: bhavna>>,)": "cart.user" must be a "User" instance. this is model file from django.conf import settings User = settings.AUTH_USER_MODEL class cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) stock = models.ForeignKey(Stock,on_delete=models.CASCADE) qty = models.IntegerField() class Stock(models.Model): product_id = models.ForeignKey(Product, null=True,on_delete=models.CASCADE) size_id = models.ForeignKey(Size, null=True,on_delete=models.CASCADE) colour_id = models.ForeignKey(Colour,null=True,on_delete=models.CASCADE) qty = models.IntegerField() views.py @login_required def add_cart(request): if request.method == 'POST': p_id = request.POST.get('product_id') s_id = request.POST.get('size_name') c_id = request.POST.get('col_name') qs = Product.objects.get(id=p_id) qtty = 0 print(p_id) print(s_id) print(c_id) object_stock = Stock.objects.filter(product_id=p_id,size_id=s_id,colour_id=c_id, qty__gte=1).values() object_stock1 = Stock.objects.get(product_id=p_id,size_id=s_id,colour_id=c_id, qty__gte=1) print(object_stock1) for ob in object_stock: qtty += ob['qty'] if qtty >= 1: b = cart(qty=1) b.stock = object_stock1 b.user=request.user, b.save() return HttpResponse("Inserted") else: return HttpResponse("Not inserted") i am trying add to cart functionality for study purpose but it is giving me error -
Django many-to-many formset for books and authors: only books added to database
My aim is to have a form where users can enter a book and its authors into the database using an 'Add Author' button if there's more than one author. I use a many-to-many relationship so all of these authors can be added (or in most cases, just 1 author). Currently the book is getting added to the table but not the author. I think it has to do with the multiple forms aspect. Originally I tried CreateView until I realised that doesn't work with more than one model at a time. I am new to programming and to Django and only have a few CRUD apps under my belt at this point. models.py: class Book(models.Model): title = models.CharField(max_length=200) authors = models.ManyToManyField('Author', through='Authored') def __str__(self): return self.title class Author(models.Model): name = models.CharField(max_length=200) books = models.ManyToManyField('Book', through='Authored') def __str__(self): return self.name class Authored(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) author = models.ForeignKey(Author, on_delete=models.CASCADE) views.py: class BookCreate(View): template_name = 'bookmany/book_form.html' form_class = BookForm formset_class = AuthorFormSet def get(self, request, *args, **kwargs): form = self.form_class() formset = self.formset_class() return render(request, self.template_name, {'form': form, 'formset': formset}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) formset = self.formset_class(request.POST) success_url = reverse_lazy('bookmany:book_list') if form.is_valid(): book = form.save() if … -
Keep getting a CORS error for put requests in Django from browser
I keep getting a CORS error when I make a put request to my Django server from my frontend application (Fetch API) but not from Postman. Here is the error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://q72y0iroi2.execute-api.us-west-2.amazonaws.com/weightsheets/636. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 503. Somehow GET, POST and DELETE requests are working fine. I have tried all the settings suggested in the documentation for django-cors-headers but to no avail! Any advice would be highly appreciated Here is my settings.py: BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key()) DEBUG = os.getenv("DEBUG", "False") ALLOWED_HOSTS = ['*'] DEVELOPMENT_MODE = os.getenv("DEVELOPMENT_MODE", "False") # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'weighttrackingapi', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } # List of allowed origins CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_METHODS = ( "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ) CORS_ALLOW_HEADERS = ( "accept", "authorization", "content-type", "user-agent", "x-csrftoken", "x-requested-with", ) CORS_ALLOW_CREDENTIALS = True MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'weighttracking.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', ], }, … -
Python Django and React: CSRF Authtification failing, HTTP 403
I have the following Django-Setup to ensure CORS between my React Frontend and my Django Backend: views.py: import json from django.http import JsonResponse, HttpResponseBadRequest from django.middleware.csrf import get_token from django.views.decorators.http import require_http_methods from .models import FavouriteLocation from .utils import get_and_save_forecast def get_forecast(request, latitude, longitude): forecast = get_and_save_forecast(latitude, longitude) data = { 'latitude': str(forecast.latitude), 'longitude': str(forecast.longitude), 'generation_time_ms': str(forecast.generation_time_ms), 'utc_offset_seconds': forecast.utc_offset_seconds, 'timezone': forecast.timezone, 'timezone_abbreviation': forecast.timezone_abbreviation, 'elevation': str(forecast.elevation), 'temperature': str(forecast.temperature), 'windspeed': str(forecast.windspeed), 'winddirection': str(forecast.winddirection), 'weathercode': forecast.weathercode, 'is_day': forecast.is_day, 'time': forecast.time.isoformat(), # convert datetime to string 'hourly_time': forecast.hourly_time, 'temperature_2m': forecast.temperature_2m, 'relativehumidity_2m': forecast.relativehumidity_2m, 'windspeed_10m': forecast.windspeed_10m, } return JsonResponse(data) def get_favourites(request): favourites = FavouriteLocation.objects.all() data = [{'id': fav.id, 'name': fav.name, 'latitude': fav.latitude, 'longitude': fav.longitude} for fav in favourites] return JsonResponse(data, safe=False) @require_http_methods(["POST"]) def add_favourite(request): try: data = json.loads(request.body) name = data['name'] latitude = data['latitude'] longitude = data['longitude'] FavouriteLocation.objects.create(name=name, latitude=latitude, longitude=longitude) return JsonResponse({'status': 'success'}) except (KeyError, ValueError): return HttpResponseBadRequest() @require_http_methods(["DELETE"]) def delete_favourite(request, favourite_id): try: fav = FavouriteLocation.objects.get(id=favourite_id) fav.delete() return JsonResponse({'status': 'success'}) except FavouriteLocation.DoesNotExist: return HttpResponseBadRequest() def csrf(request): token = get_token(request) return JsonResponse({'csrfToken': token}) settings.py: from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'secret' # SECURITY WARNING: don't run with debug turned on in production! DEBUG … -
The class name with or without quotes in a Django model field to have foreign key relationship
I can set Category with or without quotes to ForeignKey() as shown below: class Category(models.Model): name = models.CharField(max_length=50) class Product(models.Model): # Here category = models.ForeignKey("Category", on_delete=models.CASCADE) name = models.CharField(max_length=50) Or: class Category(models.Model): name = models.CharField(max_length=50) class Product(models.Model): # Here category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=50) And, I know that I can set Category with quotes to ForeignKey() before Category class is defined as shown below: class Product(models.Model): # Here category = models.ForeignKey("Category", on_delete=models.CASCADE) name = models.CharField(max_length=50) class Category(models.Model): name = models.CharField(max_length=50) And, I know that I cannot set Category without quotes to ForeignKey() before Category class is defined as shown below: class Product(models.Model): # Error category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=50) class Category(models.Model): name = models.CharField(max_length=50) Then, I got the error below: NameError: name 'Category' is not defined My questions: What is the difference between the class name with or without quotes in a Django model field to have foreign key relationship? Which should I use, the class name with or without quotes in a Django model field to have foreign key relationship? -
How to display product stock information in a single line per product with varying columns based on store count in Django?
I have 3 tables: Product, Store, Stock. Stock contains the product's quantity and price. Every Product has a Stock entry per store. If there 3 stores, each product will have 2 stock entry with their own price and quantity. I want to display these records on a single line per product where the columns will depend on how many stores there is. Like this: Product Name Store1 Quantity Store1 Price Store2 Quantity Store2 Price Flathead Screw 10 60 20 70 How can I do this? All I can give you now are my models: class ProductCategory(models.Model): categoryid = models.AutoField(primary_key=True) shortcode = models.CharField(max_length=10) categoryname = models.CharField(max_length=50,unique=True) isactive= models.BooleanField(default=True) class Meta: db_table="tblProductCategory" class Product(models.Model): productid = models.AutoField(primary_key=True) sku = models.CharField(max_length=20,unique=True) shortcode = models.CharField(max_length=10) category = models.ForeignKey(ProductCategory, on_delete=models.SET_DEFAULT,null=False,default=0) productname = models.CharField(max_length=50) description = models.CharField(max_length=50) barcode = models.CharField(max_length=20) isactive= models.BooleanField(default=True) class Meta: db_table="tblProduct" class Store(models.Model): storeid = models.AutoField(primary_key=True) storename = models.CharField(max_length=50) class Meta: db_table="tblStore" class Stock(models.Model): stockid = models.AutoField(primary_key=True) store = models.ForeignKey(Store, on_delete=models.SET_DEFAULT,null=False,default=0) product = models.ForeignKey(Product, on_delete=models.SET_DEFAULT,null=False,default=0) threshold = models.IntegerField(default=0) cost = models.FloatField(default=0) price = models.FloatField(default=0) discountprice = models.FloatField(default=0) stock = models.FloatField(default=0) class Meta: db_table="tblProductStock" and my current view: def get_product(request): recordsTotal = 0 draw = int(request.GET['draw']) start = int(request.GET['start']) length = int(request.GET['length']) products … -
''404 Not Found'' Django media files
I'm trying to serve an image from a docker volume, but I can't quite get a hang of it. error message Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/fergana_api/files/36/movies/movie.mp4 Using the URLconf defined in fergana_api.urls, Django tried these URL patterns, in this order: admin/ api/schema/ [name='api-schema'] api/docs/ [name='api-docs'] api/ [name='all-runs'] tests/<slug:test_session_id> [name='single-run'] tests/<slug:test_session_id>/<slug:test_name> [name='single-test'] ^static/(?P<path>.*)$ ^files/(?P<path>.*)$ The current path, fergana_api/files/36/movies/movie.mp4, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. settings.py STATIC_URL = 'static/' MEDIA_URL = 'files/' MEDIA_ROOT = '/var/web/media/' STATIC_ROOT = BASE_DIR / 'static_files' # location of static files STATICFILES_DIRS = [ BASE_DIR / 'static' ] app/views.py class SingleTestView(View): def get(self, request, test_session_id, test_name): run = Runner.objects.get(id=test_session_id) path_to_session = to_file('files/', f'{test_session_id}') movies_dir_path = to_file(path_to_session, 'movies') movie_path = to_file(movies_dir_path, test_name.replace('-', '_') + '.mp4') context = { 'movie_path': movie_path } return render(request, "presenter/single_test.html", context) project/url.py if settings.DEBUG: urlpatterns += static( settings.STATIC_URL, document_root=settings.STATIC_ROOT ) urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) single_test.html <video width="320" height="240" controls> <source src="{{ movie_path }}" type="video/mp4"> </video> It seems like the app uses the correct URL to serve files, but it doesn't seem like … -
Django static files in k8s
i have my djanog app and its not working when im doing DEBUG = False this is my ingress.yaml: {{- $ingress := .Values.ingress -}} {{- if $ingress.enabled -}} apiVersion: {{ include "service.ingressAPIVersion" . }} kind: Ingress metadata: name: "{{ include "service.fullname" . }}" namespace: {{ .Release.Namespace }} {{- with $ingress.annotations }} annotations: {{- range $key, $value := . }} {{- printf "%s: %s" $key (tpl $value $ | quote) | nindent 4 }} {{- end }} {{- end }} labels: {{- include "service.labels" . | nindent 4 }} {{- range $key, $value := $ingress.labels }} {{- printf "%s: %s" $key (tpl $value $ | quote) | nindent 4 }} {{- end }} spec: {{- if .Values.ingress.tls }} tls: {{- with $ingress.tls }} {{- toYaml . | nindent 4 }} {{- end }} {{- end }} ingressClassName: {{ $ingress.ingressClassName }} rules: {{- with $ingress.rules }} {{- toYaml . | nindent 4 }} {{- end }} - host: website.net http: paths: - path: /static/ pathType: Prefix backend: serviceName: my-app servicePort: 80 {{- end }} this is in my settings.py: STATIC_URL = "/static/" STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) CONTENT_TYPES = [ ('text/css', '.css'), ('application/javascript', '.js'), … -
Django Python: Infinite Scroll Feed
I am working on a Social Media Website. My Feed has images and Videos uploaded by Users but after like the 6th Content a Bar with Buttons to the next Site appears (a Paginator). I would like to create an Infite Scroll, so if the User reached the end of the Feed of the first Page it automaticly loads the next Feed Page under the other. That's what appears I would be nice if someone could help me. I will upload my Feed.html and my Views.py feed.html {% extends "blog/base.html" %} {% block title %}Feeds{% endblock %} {% block content %} <link href="https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp" rel="stylesheet" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200" /> <div class="col-8"> {% if posts|length == 0 %} <span class="no-feed-text"> <p>You need to follow someone to see their Posts<br>Meanwhile you can give look at your <a class="trending-page" href="{% url 'blog-trends' %}">Search</a> page</p> </span> <br><br> {% endif %} {% for post in posts %} <article class="content-section" style="overflow: auto;"> <div class="mediacontent"> {% if post.extension == '.mp4'%} <video loop controls disablePictureInPicture controlsList="nodownload noplaybackrate" class="video-context" width="500px" height="500px"> <source src="{{ post.file.url }}" type="video/mp4"> </video> {% elif post.extension == '.jpg' or post.extension == '.jpeg' %} <a href="{% url 'post-detail' post.id %}"> <img class="image-context" src="{{ post.file.url }}"> </a> … -
Cannot proceed with multiform view in class based views
I need to create a class based view that: will display one form based on the input from the first form will create another one: the first input is a JSON file that contains the name of the files that need to be passed to the next. I'm stuck - I cannot get the view to act on saving the first form (called initial in the code). I minimized the initial_form_valid function to just one print and it still doesn't run (before it was an attempt to check if the form is valid or not and print the result to the console). And yes, unfortunately for now I must keep putting the CBV in a function to preserve the original urls.py structure. views.py def firmware_cbv(request): class Firmware_view(MultiFormsView, TemplateView): template_name = 'path/firmware_cbv.html' form_classes = {'initial': forms.InitialFirmwareForm, 'details': forms.DetailsFirmwareForm} def get_success_url(self): return self.request.path def get_context_data(self, **kwargs): context = super(Firmware_view, self).get_context_data(**kwargs) forms = self.get_forms(self.form_classes) context["initialSent"] = False context['forms'] = forms context.update({"key1": "val1", "key2": "val2"}) print("the context is now", context) return context def initial_form_valid(self): print("the self in initial form valid is", self) def details_form_valid(self, form): new_firmware = form.save(self.request) return form.details(self.request, new_firmware, self.get_success_url()) fw_view = Firmware_view.as_view()(request) return fw_view forms.py class InitialFirmwareForm(forms.Form): file = forms.FileField() def …