Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'snyk' says my django view code is dangerous, is it?
I have a Django file-sharing app and snyk.io keep reporting me there is Path Traversal Vuln. So I added some 'safe validation functions', but he keeps warning me there is a HIGH-LEVEL vulnerability. I want to know if I can just ignore those issues... Any criticism or suggestions would be appreciated the file sharing view def fileshare_details(request): if request.method == 'GET': pk = request.GET.get('id') try: secretfile = SecretFile.objects.get(pk=pk) path = settings.MEDIA_ROOT / secretfile.content.name return FileResponse( open( path, 'rb' ) ) except SecretFile.DoesNotExist: pass return redirect('/file/') with create view def fileshare_create(request): if request.method == 'POST' and request.FILES: # ... some assigns ... content = request.FILES['file'] is_safe_filename = safe_filename(filename=str(content.name)) if not is_safe_filename: return render( request, 'fileShare/failure.html', { # ... some debug info for the user ... } ) SecretFile.objects.create( content=content, # ... some other values ... ) return redirect('/file/') return render(request, 'fileShare/create.html') with 'safe_filename' function def safe_filename(filename): for unsafe in UNSAFES: if unsafe in filename: return False return True and UNSAFES = { 'root', 'ssh', 'key', 'admin', 'password', 'passwd', 'pw', 'id', 'sys', 'env', 'conf', '\\', '/', '%', } I've read articles about path traversal, and it seems my 'safe_filename' function can filter those filenames as well. As far as I think there … -
How can I fetch videos in Django from my media folder?
I want to render my videos and images using a dinamic JS. For that purpose I've done these codes: const fetchMediaFiles = async() => { const response = await fetch('http://127.0.0.1:8000/myApp/get_media_files'); const files = await response.json(); const content = document.getElementById('content'); for (let i = 0; i < 1; i++) { content.innerHTML = ` <div class="video-active"> <video src= "media/${files[i]}' " controls> Your browser does not support video tag. </video> </div> `; } /* .catch(error => console.log(error)); */ console.log(files); } A HTML with well basically a section, this function in views.py `def get_media_files(request): media_folder = os.path.join(settings.MEDIA_ROOT) files = [] for filename in os.listdir(media_folder): files.append(filename) return JsonResponse(files ,safe=False)` and this code in urls.py: path('get_media_files/', get_media_files, name="get_media_files"), The error I get is 404 and it shows me all the paths from Urls.py which of course doesn't match with my video src. I'd like to know how can I connect those videos or make the folder accesible so I can just use a relative path or something to get that. Thank you all! -
Django: Save data in a Table but at the same time edit or modify data from a different table
#I am trying to save data in the constancia_pro table but at the same time I want to edit or modify the status field from "NO" to "YES" of the lpro_reg table when I save it, but it generates this error: The lpro_reg could not be changed because the data didn't validate.# models.py `class lpro_reg(models.Model): id = models.AutoField(primary_key=True) tipodoc = ( ('V', 'V'), ('E', 'E'), ('J', 'J'), ('G', 'G'), ) tipo = models.CharField(max_length=2, choices=tipodoc, default='J') documento= models.CharField(max_length=15, blank=False) nombre = models.CharField(max_length=150, blank=False) presentante = models.CharField(max_length=150, blank=False) fecha_reg= models.DateField(auto_now_add=True) ramos = models.ManyToManyField(ciuu) direccion = models.CharField(max_length=250, blank=False) n_recibo = models.CharField(max_length=50, blank=True) fecha_recibo = models.DateField() fecha_apert = models.DateField() opciones = ( ('SI', 'SI'), ('NO', 'NO'), ) status = models.CharField(max_length=2, choices=opciones, default='NO') responsable = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: db_table = 'prov_reg' ordering = ['id'] def __str__(self): return str(self.id) class constancia_pro(models.Model): licencia2 = models.AutoField(primary_key=True) n_constanica = models.CharField(unique=True, max_length=13) aprobado = models.OneToOneField(lpro_reg, on_delete=models.CASCADE) fecha_reg = models.DateField(auto_now_add=True) class Meta: db_table = 'pro_const' ordering = ['-licencia2'] def __str__(self): return str(self.licencia2)` views.py `verdatos = get_object_or_404(lpro_reg.objects, pk = id) ultimodato = constancia_pro.objects.first() ultima_id = int(ultimodato.n_constanica)` `if request.method == 'POST': formulario = aprobado_form(request.POST) formulario2 = registroprovicional_form(request.POST, request.FILES, instance=verdatos) if formulario.is_valid(): formulario.instance.n_constanica = ultima_id + 1 formulario.instance.aprobado = lpro_reg.objects.filter(pk = id).first()` formulario2.instance.status … -
Makefile error (make: *** [Makefile:31: test] Error -1073741515)
I am trying to set up my local development environment using the make command make setup as and I get this error. Error code: make: *** [Makefile:31: test] Error -1073741515 Make File: This is part of the Makefile content, /Makefile local_config = --settings=config.local ... setup: # Set up the project database python manage.py migrate ${local_config} Config.local: This is the content of the /config/local.py from .settings import * DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(PROJECT_ROOT, "db.sqlite3"), } } CACHES = { "default": { "BACKEND": "django.core.cache.backends.dummy.DummyCache", } } DEBUG = True TASTYPIE_FULL_DEBUG = True I expected the command to execute normally and setup my development environment. -
Django - ImportError after Installing Angular and React
My Django Server was working perfectly but after installing Angular and React, my Django Server stopped working and started giving following error: I have already researched a lot but unable to resolve error, pls help... Traceback (most recent call last): File "C:\Users\LM\dj\policyboss\manage.py", line 22, in <module> main() File "C:\Users\LM\dj\policyboss\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'policyboss.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() -
How to handle different creator type models for post creator in Django?
Suppose I have Porfile, Post, Teacher and Student Django models, I created Profile model to share the common fields that Teacher and Student have. Question: what is the right way to represent the creator relationship in the post model, and if my following code right, How I can identify the type of the Profile I mean if it's teacher or student, when I get the profile instance from post creator?: class Porfile(models.Model): user = models.OneToOneField(User) . . class Post(models.Model): . creator = models.ForeignKey(Profile, on_delete=models.CASCADE) . class Teacher(models.Model): . profile = models.OneToOneField(Profile) . class Student(models.Model): . profile = models.OneToOneField(Profile) . -
additional field not showing in django admin panel
class CustomUser(AbstractUser): is_admin = models.BooleanField(default=False) company = models.ForeignKey(Company,on_delete=models.CASCADE,null=True) department = models.ForeignKey(Department,on_delete=models.CASCADE,null=True) contact = models.CharField(max_length=17,null=True) whenever i tried to add a user through Djangoo admin site the contact field is not showing class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = '__all__' class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = '__all__' class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['username', 'email', 'is_staff', 'is_admin','department_id','company_id',] list_filter = ['is_staff', 'is_admin'] fieldsets = UserAdmin.fieldsets + ( (None, {'fields': ('is_admin','department_id','company_id','contact',)}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('username', 'email', 'password1', 'password2', 'is_admin','department_id','company_id',), }), ) this is what i used to add field , i tried most of the thing to add this fields to Django user admin but not showing is there any mistake in my code -
DetailView from Django in NextJS 13 (fetching data)
I've got Django based app as my back-end, and NextJS as front-end. I've got a Post model in my Django App with two views - PostDetailView and PostListView. from django.shortcuts import get_object_or_404 from django.template import TemplateDoesNotExist from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import Post from .serializers import PostSerializer from rest_framework.renderers import JSONRenderer from django.http import Http404, HttpResponse class JSONResponse(HttpResponse): def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) class PostListView(APIView): def get(self, request): posts = Post.objects.all() serializer = PostSerializer(posts, many=True) return JSONResponse(serializer.data) class PostDetailView(APIView): def get(self, request, pk): try: post = Post.objects.get(pk=pk) serializer = PostSerializer(post) return Response(serializer.data, status=status.HTTP_200_OK) except Post.DoesNotExist: raise Http404 I've also set up serializers.py and urls.py. #serializers.py from rest_framework import serializers from .models import Post class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' #urls.py from django.contrib import admin from django.urls import include, path from . import views urlpatterns = [ path('api/posts/', views.PostListView.as_view(), name='post-list'), path('api/posts/<int:pk>/', views.PostDetailView.as_view(), name='post-detail'), ] In my NextJS App I'm using new approach for folder structure with src/app. This is my folder structure. - src/app -- blog --- page.tsx (here is my 'ListView') -- [id] --- page.tsx (here is my 'DetailView') … -
Django Datetime formate DD-MM-YYYY
I want to set the date format DD-MM-YYYY but Error django.core.exceptions.ValidationError: ['“23.07.2023 21:00:11” value has an invalid date format. It must be in YYYY-MM-DD format.'] Help Me create_date = models.DateField(blank=False, default=datetime.now().strftime(("%d.%m.%Y %H:%M:%S")))``` I want to set the date format DD-MM-YYYY but Error django.core.exceptions.ValidationError: ['“23.07.2023 21:00:11” value has an invalid date format. It must be in YYYY-MM-DD format.'] -
How to upload a file from request.FILES using Celery in Django?
There's a model called Post which has an image field. The image field gets its value from a form. I don't want media files to be stored locally. So I'm using S3Boto3Storage as my file storage. Is there a way to save the Post model object using celery (so that the image file gets uploaded by celery to not keep the user waiting). I tried writing a celery task to save the object. But apparently you can't just send a file to Celery as a parameter. This is what I have so far: views.py: tasks.upload_image_task.delay( request.user.pk, request.session["post_body"], request.FILES.get("image"), request.session["post_tags"], ) tasks.py: @shared_task def upload_image_task(user_pk, body, image, tags): user = User.objects.get(pk=user_pk) post = Post.objects.create(user=user, body=body, image=image, post_type="IMG") for tag_pk in tags: post.tags.add(Tag.objects.get(pk=tag_pk)) post.save() This will result in Object of type InMemoryUploadedFile is not JSON serializable. I also read that first you can save the file on local and then upload the file using a task. But I want to upload it directly. -
Writing to SQL yields different results with shell / django
I have a simple model: class myJSONField(models.JSONField): def get_prep_value(self, v): if v is None: return value return json.dumps(v, ensure_ascii = False) class Product(models.Model): data = myJSONField() number = models.PositiveIntegerField() Product.create(number = 1, data = {"direction": "süd"}) yields: "{\"direction\": \"s\u00fcd\"}" Testing with sqlite3: conn = sqlite3.connect('db.sqlite3') c = conn.cursor() test = json.dumps({"direction": "Süd"}, ensure_ascii = False) sql = ("""UPDATE test_product SET data = ? WHERE id=1""") c.execute(sql, [test]) conn.commit() yields: {"direction": "süd"} I am using the same db.sqlite3 file for both tests. I do not understand why the ensure_ascii = False flag is ignored by the django logic. How can I obtain a correct JSON in my JSONField (without the escaped ")? -
How to install Virtualenv globally in windows system?
I've installed virtual environment using pip (pip install virtualenv), and it has installed successfully. Then when I try to find the veriosn of my virtualenv (virtualenv --version), it shows the error messgae - 'virtualenv' is not recognized as an internal or external command I've installed virtualenv, and when I want to check if it has installed correctly, it shows error message - 'virtualenv' is not recognized as an internal or external command, operable program or batch file. -
Python/Django Setting up a database model with conditions inside of it
I am currently writing some sort of simple game, which is set up onto a database backend (using Python with Django). I have a database model called Character, which basically has two fields (there are more, but they are not relevant for my question). It basically looks something like this: # Create your models here class Character(models.Model): HUMAN= 'HM' ELF = 'EF' RACE_CHOICES = [ (HUMAN, 'Human'), (ELF, 'Elf'), ] race = models.CharField(max_length=2, choices=RACE_CHOICES) constitution = models.FloatField Basically you can choose a race from the two given above. I want humans to have more constitution than elfs, so the constitution should be dependent on what race the user picks. I know that this is possible by overwriting the save method, but I am also aware that this is not best practice as it can crash the whole database, should any errors occur. I was told that is is, however, possible to use conditions inside the model definition, what I basically need is: if race == human: constitution = 12.0f else: constitution = 8.0f I really don't know how to set this up inside a Django model. Or would it be a better way to define a meta class "Race" and … -
How to use the Tron API to find a transaction by hash
I am createing and webapp where users are able to submit a transaction hash and it will automaticcally check the hash in the relevant wallet to see if a transaction has been received if yes it cheks the amount transfered and if the amount is equall 50 USDT it will perform some logic. Now i`m struck in creating this webapp and i really want some help, I dont understand anything in the docs of the Tron API. Could anyone help me with this. My code: elif request.POST.get("pay_type") == "binance": transaction_hash = request.POST.get("no") tronlink_api_key = "YOUR_TRONLINK_PRO_API_KEY" api_url = f"https://api.tronlink.org/v1/transaction/{transaction_hash}?apiKey={tronlink_api_key}" response = requests.get(api_url) if response.status_code == 200: if Pin.objects.filter( owner=request.user, status="COMPLETED", transaction_hash=request.POST.get("no"), ).exists(): messages.error( request, "It seems that this Transaction Hash/Trix is relevant to another payment. Please try again.", ) return redirect("create_pin") else: transaction_data = response.json() amount = transaction_data.get("data", {}).get("amount", 0) if amount < int(request.POST.get("package")): messages.error( request, f"You have done a transaction of only {amount} USDT but, you should do a payment of {int(request.POST.get('package')) + 10} USDT. Please try again.", ) return redirect("create_pin") else: Pin.objects.create( owner=request.user, package=request.POST.get("package"), p_type=( "RENEW" if ( Pin.objects.filter( owner=request.user, status="COMPLETED" ).exists() ) else "NEW" ), pay_type="BINANCE", status="COMPLETED", transaction_hash=request.POST.get("no"), ) messages.success(request, "Pin applied successfully.") return redirect("dashboard") else: messages.error( request, … -
django.core.exceptions.FieldError: Cannot resolve keyword 'content_type' into field. Choices are: id
I have below classes definition: class A(models.Model): created_time = models.DateTimeField(default=now, null=True, blank=True) t = GenericRelation(T, object_id_field='object_id', content_type_field='content_type', related_query_name='a') class B(A): state_path = models.CharField(max_length=256, blank=True, verbose_name="State Path") f = GenericRelation(F, content_type_field='content_type', object_id_field='object_id', related_query_name='b') class C(B): choice = models.BooleanField(default=False, verbose_name="Enabled") class T(models.Model): created_time = models.DateTimeField(auto_now_add=True, verbose_name="Created Time") # GenericForeignKey fields content_type = models.ForeignKey(ContentType, null=True, blank=True, on_delete=models.DO_NOTHING) object_id = models.PositiveIntegerField(null=True, blank=True) a = GenericForeignKey('content_type', 'object_id') class E(models.Model): username = models.CharField(max_length=128, verbose_name="Username") key = models.TextField(blank=True, verbose_name="Key") class F(E): content_type = models.OneToOneField(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() b = GenericForeignKey('content_type', 'object_id') c = C.objects.get(pk=c_id) c.delete() It returned error: django.core.exceptions.FieldError: Cannot resolve keyword 'content_type' into field. Choices are: id I don't quite get it why... as C doesn't have content_type, and T has on_delete=models.DO_NOTHING for its content_type. Please help correct. Thanks. -
Django request returning null?
So I'm building a chatbot withing Django using chat GPT and I'm following this tutorial https://www.youtube.com/watch?v=qrZGfBBlXpk anyway I don't see any difference in my code yet I'm running into a peculiar problem when I request from my html mile during the message sending process it returns null from the ''chatbot'' def chatbot(request): if request.method == 'POST': message = request.POST.get('message') response = message return JsonResponse({'message': message, 'response': response}) return render(request, 'chatbot.html') whats even weirder is when I console log the message in the JS messageForm.addEventListener('submit', (e) => { e.preventDefault(); const message = messageInput.value.trim() console.log('Message:', message) It shows up in the log? but somewhere along the line it returns null? I noticed when I used the davinci model and the chat would respond but only with nonsense which to me implied it wasnt actually getting MY message it was getting null and returning nonsense this Is the rest of the JS const messageItem = document.createElement('li'); messageItem.classList.add('message', 'sent'); messageItem.innerHTML = `<div class="message-sender"> <div class="message-sender" <b>You<b> </div> <div class="message-content"> ${message} </div> </div>`; messageList.appendChild(messageItem); messageInput.value = ''; const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; fetch('', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urleencoded', 'X-CSRFToken': csrftoken }, body: new URLSearchParams({ 'csrfmiddlewaretoken': csrftoken, 'message': message }) }) .then(response => response.json()) .then(data … -
Django template language is not recognized
I am working on a Django projcet. Yesterday when I left the project I didn't have any problems. Today when I opend the project my {% load static %} was gray, and the next line which is "<!doctype html>" gives me "Unexpected tokens". My project works fine except the templates. I work in a virtual envirment, have my project on github: https://github.com/FREDYKRUGE/Mist2.git. P.S I work with PyCharm proffesional I tried installing all the dependecies again, they were all satisfied, tried activating the venv, it was okay. My docker is up and running. -
Uploading images using forms in Django
I need help. Learning Django at the moment. Doing a simple (for now) project which is basically a site about film photocameras: it contains information, relations between cameras and films... You get the idea. I have created two forms to create a new entry for camera and for film. Here is the models to start with: class Camera(models.Model): ref_to_topic=models.ForeignKey(Topic, on_delete=models.CASCADE) ref_to_brand=models.ForeignKey(Brand, on_delete=models.CASCADE) camera_name=models.CharField(max_length=255) camera_info=models.TextField(null=True, blank=True) camera_image=models.ImageField(upload_to='site_media/camera_images/', null=True, blank=True) when_appeared_date=models.DateField(null=True, blank=True) when_appeared_year=models.IntegerField(null=True, blank=True) when_disappeared=models.DateField(null=True, blank=True) when_disappeared_year=models.IntegerField(null=True, blank=True) when_added=models.DateTimeField(auto_now_add=True) when_updated=models.DateTimeField(auto_now=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, default=1) class Meta(): verbose_name_plural='cameras' def __str__(self): return f"{self.camera_name} - {self.camera_info[:25]}" class Film(models.Model): ref_to_topic=models.ForeignKey(Topic, on_delete=models.CASCADE) ref_to_brand=models.ForeignKey(Brand, on_delete=models.CASCADE) film_name=models.CharField(max_length=255) film_info=models.TextField(null=True, blank=True) film_image=models.ImageField(upload_to='site_media/film_images/', null=True, blank=True) when_added=models.DateTimeField(auto_now_add=True) when_updated=models.DateTimeField(auto_now=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, default=1) class Meta(): verbose_name_plural='films' def __str__(self): return f"{self.film_name} - {self.film_info[:25]}" And here is the forms to full this models using browser: class CameraForm(forms.ModelForm): class Meta: model = Camera fields = ['camera_name', 'camera_info', 'when_appeared_date', 'when_appeared_year', 'when_disappeared', 'when_disappeared_year', 'ref_to_topic', 'ref_to_brand', 'owner', 'camera_image'] labels = { 'camera_name': 'Camera', 'camera_info': 'Info', 'when_appeared_date': 'Started on the market (exact date, can be null)', 'when_appeared_year': 'Strarted on the market (exact year, can be null)', 'when_disappeared': 'When the sales stopped (exact date, can be null)', 'when_disappeared_year': 'When the sales stopped (exact year, can be null)', 'ref_to_topic': 'refered to … -
Problem with Trio package when installing pymongo in my project
i have a django project that runs on ubuntu 20.04 version. i use selenium versio 4.1.5 . the selenium package has the trio package as a dependecy (version 0.22.2). until i added pymongo version (4.4.1) to my project everything worked fine. when installing it i get the following error : Traceback (most recent call last): File "mypath/checknet-api/./manage.py", line 26, in <module> execute_from_command_line(sys.argv) File "mypath/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 381,in execute_from_command_line utility.execute() File "mypath/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "mypath/venv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "mypath/venv/lib/python3.9/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "mypath/<innerpath>/apps.py", line 8, in ready import checknet.main.signals File "mypath/<innerpath>//signals.py", line 6, in <module> from .tasks import execute File "mypath/<innerpath>/tasks.py", line 7, in <module> from .bots import ( File "mypath/<innerpath>/fbi_crawler.py", line 2, in <module> from pymongo import MongoClient File "/mypath/venv/lib/python3.9/site-packages/pymongo/__init__.py", line 92, in <module> from pymongo.mongo_client import MongoClient File "mypath/venv/lib/python3.9/site-packages/pymongo/mongo_client.py", line 61, in <module> from pymongo import ( File "mypath/venv/lib/python3.9/site-packages/pymongo/uri_parser.py", line 32, in <module> from pymongo.srv_resolver import _HAVE_DNSPYTHON, _SrvResolver File "mypath/venv/lib/python3.9/site-packages/pymongo/srv_resolver.py", line 21, in <module> from dns import resolver File "mypath/venv/lib/python3.9/site-packages/dns/resolver.py", line 30, in <module> import dns._ddr File "mypath/venv/lib/python3.9/site-packages/dns/_ddr.py", line 12, in <module> import dns.nameserver File "mypath/venv/lib/python3.9/site-packages/dns/nameserver.py", line 5, in <module> import dns.asyncquery File "mypath/venv/lib/python3.9/site-packages/dns/asyncquery.py", line 38, in <module> from dns.query … -
Python django Usermodel extending to custom user model
The problem is i need an extra field to add my Django usermodel via a custom user model called 'is_admin' so ,this is the code i added to model class CustomUser(AbstractUser): is_admin = models.BooleanField(default=False) but i registered this model to admin.py when i tried to add a user using django admin page the password stores as plain not hashing hos to solve this problem AUTH_USER_MODEL = 'cAdmin.CustomUser' i've already changed the default user model and admin.py from django.contrib import admin from .models import CustomUser,Priority from django import forms from django.contrib.auth.admin import UserAdmin # Register your models here. admin.site.register(CustomUser) admin.site.register(Priority) -
not showing HttpResponse in django python
`settings.py `INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sample' ] ` sample/views.py from django.shortcuts import render from django.http import HttpResponse def hello(request): return HttpResponse("hello world") mainapp/ urls.py from django.contrib import admin from django.urls import path from sample import views urlpatterns = [ path('hello/',views.hello), path('admin/', admin.site.urls) ] but when i run python manage.py runserver it is not shoing the 8000/hello/ page -
Initialize Model w Foreign Keys in Django
I have a Model that represents a card. A card will only ever have two card faces, the front and the back. The card faces contain a background image, with a number of related data fields containing strings and positions to render the strings on it. I want to have the base image as a file and then render the strings onto it so I can print them out through a printer. I've done DB modelling before but I don't consider myself an expert. I also tend to overthink things so I might just be driving myself crazy when there's a simple solution to do what I want. My googleFu is mostly just leading me around in circles. I want to prevent anyone from trying to add or delete the card faces. I also want to pre-populate the object so that it only ever has a front and back. The relationship for Card to CardFace is one to exactly two. But I'm having trouble trying to figure out how to do this model. I've actually got the rendering part working. It's more a matter of when it should be done. I want to save the original unchanged background image so … -
In Django, how to use HTMX or Django-Autocomplete-Light for a dependent combobox? (using the same database table)
I am using for the first time, in Django, HTMX and Django-Autocomplete-Light a try. I've read tutorials on the web and created test projects, but I can't get what I want. Most of the tutorials use ForeignKey and create two tables (that's easy), while I have all the data on the same table. I want to use only one table. Could someone show me the code of how to achieve this? I prefer HTMX, but Django-Autocomplete-Light is also fine. Choose one of the two, both are fine ID | COUNTRY | DEPARTURE | DESTINATION | | france | paris | lyon | | france | marseilles| grenoble | | spain | madrid | barcelona | | spain | seville | malaga | In the main combobox, called country, there are: Spain and France. In the second combobox are the trips for each country, made up of two columns. I would like to see them separated by a dash (departure-destination), for example: Madrid-Barcelona, Seville-Bilbao CMBX1 CMBX2 france > paris-lyon marseille-grenoble spain > madrid-barcelona seville-malaga -
Auto Deploy Django with GitHub Actions CI/CD And Configure Gunicorn & Nginx
I want to deploy a Django Web App in cloud server. I already have the project. But deploying it using CI/CD and cloud server is tough. I want to use GitHub Actions for CI/CD and in my cloud server, I want to configure Gunicorn and Nginx. Can someone help me with step by step process to do all these? -
How to do an authentication between django and nextjs 13?
Can I build authentication system between django and nextjs 13 ? If yes, How can I do that ? I'm really stuck I wanted to use JWT token based authentication but because nextjs 13 uses server components I didn't know how and where can I store access and refresh tokens. Thanks..