Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
hwo can i fix git init problem not working
enter image description here i alredy use git init enter image description here my file not become green and i can not do anything about git. it alway said i nedd permission enter image description here immage below is what i want that i capture from youtuber:Zinglecode enter image description here pls help. i'm very new.this is my first website and i nver learn anything about code before. i need the way to fix this problem. why its become like this. -
gunicorn not picking up changes in django code even after restarting
I have this web application that I built with django, and deployed with gunicorn and nginx on GCP Compute Engine Instance. I serve the static files with nginx. For nginx, whenever I push new code to the server, run collectstatic, and restart nginx, I see the static file update working fine. The problem begins with the server code. Whenever I push code to my django views, or run migrations, or push code to my html file, and restart gunicorn, I don't see the changes right away. It takes about a full day for the change to take effect. I have tried reloading daemon, restarting gunicorn, restarting nginx but the issue persists For the nginx, here is my location settings on nginx configuration location /static/ { alias /home/user/app/backend/static/; } location / { proxy_pass http://127.0.0.1:8000; } There you can see that I serve the static file using nginx, then pass every other request to the app. Then when I push code to my github, pull it into the app, and run python3 manage.py collectstatic Then restart nginx with sudo systemctl restart nginx Everything works great. Now for the part that I think the problem comes from. If I make a change to … -
Unable to run the server after export on another computer (migrations worked)
I am lost with what is probably a very simple issue configuring a django / mysql project. I have a working project on a computer A, which I just want to be able to use with a computer B. On computer A, I have an Eclipse project, using Pydev and Django, a local virtual environnement, and a local database running with Mysql. What I have done: I exported the virtual environnement (including django) and created the same one on computer B; I used Gitlab in order to get all the files with the code ; I installed Mysql, and created a database with the same name, and a user with the same informations (id / pwd). The migrations went well, the tables are created like I expected. However, I cannot find a way to run the server. When I try, I get multiple errors saying one (and only one) of the Apps is not loaded yet, then another error, which seems to be related to the database. Here are some of the messages: Traceback (most recent call last): File "/home/francois/snap/eclipse/67/amd64/plugins/org.python.pydev.core_10.2.1.202307021217/pysrc/_pydev_runfiles/pydev_runfiles.py", line 460, in __get_module_from_str mod = __import__(modname) File "/home/francois/eclipse-workspace/iou/members/forms.py", line 2, in <module> from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UsernameField File … -
With FileField, opening file before inserting database
I have models, serializer and viewsets with FileField class Drawing(SafeDeleteModel): drawing = f.FileField(upload_to='uploads/') class DrawingSerializer(ModelSerializer): drawing = serializers.FileField() class DrawingViewSet(viewsets.ModelViewSet): queryset = m.Drawing.objects.all() serializer_class = s.DrawingSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) print("serializer request:",request.data['drawing']) # this is myfile.pdf self.perform_create(serializer) print("serializer seliarizer",serializer.data['drawing']) # myfile_ccA3TjY.pdf try: doc = fitz.open(file_path) # open to check if it is correct pdf except; raise Exception("file is not valid pdf") When uploading file,request.data['drawing'] is myfile.pdf, serializer.data['drawing'] is real name myfile_ccA3TjY.pdf. ( when there is the same name file) So for opening file with fitz, I need to know the real name myfile_ccA3TjY.pdf. I have to do self.perform_create to know the real file name, and it creates the row. However I want to cancel inserting to database when file is not valid pdf. With this code database inserting is executed even file is not correct pdf. Is there any way to open the file without calling self.perform_create? -
My web application dont load styles files when in production
My project in Django https://github.com/alex-martins2305/ToDo4 works very fine in production, bootstrap, css, everything loads perfect. But in deploy to render.com the css file dont load. I already checked: In github the files are avaliable in static/css/styles.css; run collectstatic; cleaned browser data; tryed in mozzila and chrome (desktop and mobile); In chrome i can see in inspection/network the reason to not apply the style file: Refused to apply style from 'https://todo4-hk3r.onrender.com/static/ccs/styles.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. -
CSS template block tag
Sorry guyz, I am still newbie in django, I want make a website using django and find some problem, hope you guyz understand: this is the base.html : {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- My CSS --> {% block css_app%} <link rel="stylesheet" type="text/css" href="{% static "css\styles.css" %}" /> {% endblock %} <!-- Bootstrap CSS Icon --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" /> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" /> <title>{% block title %}Achmad Irfan Afandi {% endblock %}</title> </head> <body> <div class="container-flow"> <div class="row"> <!-- Contain-Menu --> {% include 'snippets/contain-menu.html' %} <!-- End Contain-Menu --> <!-- Contain-Isi --> {% include 'snippets/contain-isi.html' %} <!-- End Contain-Isi --> </div> </div> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> </body> </html> In that base.html above, I use include tag for contain-isi: and this is code for contain-isi: {% block img_page %} <div class="col-8 text-end col-isi"> <div class="text-start img">Home</div> </div> {% endblock %} I use that base.html for another app, but the prolem is, can I use and change img_page for another app in fact the that block is not inside base.html … -
Django postgresql model constraint on Charfield
I'm using Django and Postgresql. I've created a CharField in a model, with db_collation of type 'case_insensitive'. I added a unique_together constraint for that field and another field. Seems like the DB identifies '1', '01', '001' as the same, although it's a string (charField), so I'm getting this error message when trying to create different objects with those values - psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint... I don't understand why it identifies them as the same value although it's a string (and it actually saved as '1', '01', '001'... and not all as '1' for example) This is the field in the model: my_identifier = models.CharField(db_collation="case_insensitive", db_index=True, max_length=100, null=True) This is the collation definition: CreateCollation( "case_insensitive", provider="icu", locale="und-u-ks-level2-kn-true", deterministic=False, ) And this is the unique_together definition: unique_together = ('my_identifier', 'container_id') -
how do i resolve this error " ModuleNotFoundError: No module named 'allauth.accountusers' "
I am working on a simple django project with the homepage which displays simple static files stored in my database I tried to use django-allauth package to get the login with email functionality I am using docker container so i installed the django-allauth package while the container was running with the following command "$ docker-compose exec web pipenv install django-allauth==0.52.0" then i stopped my already running docker container and restarted it again with the --build flag this time to rebuild the whole image again with the following command " $ docker-compose down $ docker-compose up -d --build " then i thought to run migrate to update my database " docker-compose exec web python manage.py migrate " i got this error (in the CMD console which was not in administrator mode though but it doesn't matter) after the migration command Traceback (most recent call last): File "/code/manage.py", line 22, in \<module\> main() File "/code/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/usr/local/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.11/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/apps/config.py", line 178, in create mod = import_module(mod_path) ^^^^^^^^^^^^^^^^^^^^^^^ File … -
Why am I getting an error stating unsupported file when I've specified I want to use .mp3
I'm trying to make a music player with Django and Postgresql, I've created a song model that is working in the database except when I try to upload an audio file with a .mp3 extension. Does anyone know how to fix this issue? Thanks models.py: from django.db import models from django.contrib.auth.models import User from cloudinary.models import CloudinaryField from recordroomapp.helper import get_audio_length from .validators import validate_is_audio class Artist(models.Model): artist = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.artist class Song(models.Model): title = models.CharField(max_length=100, unique=False) slug = models.SlugField(max_length=100, unique=True) song = models.FileField( upload_to='media/', validators=[validate_is_audio], null=True) song_length = models.DecimalField( blank=True, max_digits=10, decimal_places=2, null=True) songinfo = models.ForeignKey( "Artist", on_delete=models.CASCADE, related_name='song_post', null=True) updated_on = models.DateTimeField(auto_now=True) # featured_image = CloudinaryField('image', default='placeholder') created_on = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField(User, related_name='song_likes', blank=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title # def __init__(self): # return self.song_length def save(self, *args, **kwargs): if not self.song_length: audio_length = get_audio_length(self.song) self.song_length = f'{audio_length:.2f}' return super().save(*args, **kwargs) def number_of_likes(self): return self.likes.count() class Comment(models.Model): post = models.ForeignKey( Song, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=100) email = models.EmailField() body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=False) class Meta: ordering = ['created_on'] def __str__(self): return f"Comment {self.body} by {self.name}" views.py: from … -
How can I solve in python to work my subpage?
I would like to call another html file (Magamrol.html) from another, but this happens when I am trying to open: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: [name='index'] admin/ polls/ The current path, Magamrol.html, didn’t match any of these. My app is polls and the project name is mysite. The mysite\polls\urls.py: from django.urls import path from . import views from polls import views urlpatterns = [ path('', views.index, name="index"), path('', views.magamrol, name='Magamrol') ] mysite\polls\views.py: from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse("Üdvözöllek a honlapomon!") def index(request): return render(request, 'index.html') def magamrol(request): return render(request, 'Magamrol.html') mysite\urls.py: from django.contrib import admin from django.urls import include, path from polls import views urlpatterns = [ path('',views.index,name="index"), path('admin/', admin.site.urls), path('', include('polls.urls')) ] Does anyone know how can be solved this problem? Thanks -
Would you like to encounter mountain gorillas in Uganda or Rwanda
Encounter Mountain Gorillas in Rwanda and Uganda Website: davsafaris.com Email: info@davsafaris.com Tel: +256757795781 or +256701412430 Discover the Thrills of Uganda Gorilla Safaris Embarking on a gorilla safari in Uganda is a remarkable journey into the captivating world of these magnificent creatures. Nestled within the lush rainforests of Uganda, the country's gorilla population thrives, offering an unparalleled opportunity for wildlife enthusiasts and adventure seekers alike. When planning a Uganda gorilla safaris, it is recommended to work with experienced tour operators who can arrange all the logistics, including transportation, accommodation, permits, and knowledgeable guides. They will ensure a smooth and unforgettable journey, allowing you to focus on the incredible experiences that await you. Encounter Mountain Gorillas in Rwanda and Uganda Website: davsafaris.com Email: info@davsafaris.com Tel: +256757795781 or +256701412430 -
Django url in a tag doesnt work because it adds new parameters to the url and doesnt remove unnecessary ones
I googled a lot, but I guess I use the wrong keywords to find the solution: I have this urls.py file: path('site1', views.site1, name='site1'), path('site2/<slug:topic>', views.site2, name='site2'`), I want to add an a-tag to site1. So I would use the following: <a href="{% url 'site1' %}>Link to site1</a> The problem is now that I get an error because the "site1" is added to the end of the current url. So the url looks like this "...site2/site1". What do I have to change to get rid of this error? Thanks in advance! -
"CSRF Token Missing" in Django - {% csrf_token %} has been included
I have been trying to make a simple login page, and my form is submitting, however, I keep getting csrf failure. I had tried to put the tag in several places, but nothing works. I have included the tag in different places, used different posts to change small things, but nothing worked. The first is my template html, and it loads. The latter is the view.py file, which should just render a view. <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <title>Login Page</title> </head> <body> <h1>Login Page</h1> <form action="" method="post"> {% csrf_token %} <div class="form-group"> {% csrf_token %} <label for="exampleInputEmail1">Email address</label> <input style = "max-width: 50%;" type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> <div class="form-group"> {% csrf_token %} <label for="exampleInputPassword1">Password</label> <input style = "max-width: 50%;" type="password" class="form-control" id="exampleInputPassword1" placeholder="Password"> </div> <button href="/verify" style = "margin-top: 15px; margin-left: 25%; padding-right: 30px; padding-left: 30px;" type="submit" class="btn btn-primary">Submit</button> </form> <button style = "margin-top: 30px; margin-left: 25%; padding-right: 30px; padding-left: 30px;" type="submit" class="btn btn-primary">Sign Up</button> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then … -
how connect js with python in django project
I want to receive Excel from the user with an html page and transfer it to Python using the ajaxc algorithm in js So it should be stored in a specific folder and processed by Excel using Python libraries and so on Give the user a new Excel download link in the form of a rental link `from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt import os @csrf_exempt def process_excel(request): if request.method == 'POST': excel_file = request.FILES.get('excelFile') if excel_file: # Define the path to save the uploaded excel file save_path = 'D:/updatepj/' file_path = os.path.join(save_path, excel_file.name) # Save the uploaded excel file with open(file_path, 'wb') as destination: for chunk in excel_file.chunks(): destination.write(chunk) # Create a response message response_data = {'message': 'Excel file uploaded successfully.'} return JsonResponse(response_data) else: response_data = {'message': 'No file was uploaded.'} return JsonResponse(response_data, status=400) response_data = {'message': 'Invalid request method.'} return JsonResponse(response_data, status=405) Create your views here. class DashboardView(LoginRequiredMixin, TemplateView): pass dashboard_view = DashboardView.as_view(template_name="dashboards/index.html") dashboard_crm_view = DashboardView.as_view(template_name="dashboards/dashboard-crm.html") ` the views.py i got error :Method Not Allowed: /process_excel -
Next.js <Link /> navigation causes session logout on Django page
I am working on an application that combines both Next.js and Django (using django-nextjs package). The authentication is managed by Django using session-based authentication. Here's the sequence of events leading to the issue: From the homepage (a Next.js page) where I'm not logged in, I navigate to a Django-based login page. After successfully logging in, I get redirected to a Next.js page. So far, everything works correctly, and I can access user data from the session cookie. As long as I navigate between Next.js pages, the session remains active, and I remain logged in. If I manually enter a URL to a Django page that requires authentication or refresh the page, it recognizes my session, and I remain logged in. However, if I navigate to a Django page using the Next.js <Link /> component, I get logged out instantly. What's puzzling is that the session seems active and recognized across both frameworks until I use the Next.js component to navigate to a Django page. When I do this, Django no longer recognizes my session. What could be causing the session to be lost when navigating via the component? Has anyone faced a similar issue, and how can I fix this? … -
Integrating neural net with Django
I have a sync Django setup, but want to be able to serve neural net predictions. The problem is that running NN prediction requires loading tensorflow library that takes super long to load every time (a few seconds), so this is not an option for every request. I tried instantiating my NN model within a socket server and connecting to it from my django views, but this requires async-ing the entire Django setup. Also not what I want. Is there a way to make these two play nicely together without too much overhead? -
Refused to apply style because its MIME type (text/html) is not supported stylesheet MIME type, and strict MIME checking is enabled
I am working on a django project and I have created index.html file in template folder. Style.css is not working meaning style is not applying on any of the html files and is showing "Refused to apply style because its MIME type(text/html) is not supported stylesheet MIME type, and strict MIME checking is enabled. I have tried working with style.css in external folder and also the common folder as well but the html file remained unchanged. Style can't be applied on any of the html attribute. -
How to resolve "django.urls.exceptions.NoReverseMatch: Reverse for 'activate' not found."
I'm currently working on a local project using Django 4.2 as backend. I'm trying to do account activation based on email. Below is my code snippet. Project urls.py from django.contrib import admin from django.urls import path, include from .auth_token import CustomAuthToken urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('api-token-auth/', CustomAuthToken.as_view()), path('portal-user/api/', include('portal_user.urls', namespace="portal_user")) ] portal_user urls.py from django.urls import path from .views import activate app_name = "portal_user" urlpatterns = [ path( 'activate/<slug:uidb64>/<slug:token>/', activate, name="account-activate"), ] portal_user views.py def send_account_activation_mail(self): mail_subject = 'Welcome to Our Platform! Activate Your Account' mail_message = render_to_string('portal_user/account_activate_email.html', { "first_name": f"{self.first_name}!", "uidb": urlsafe_base64_encode(force_bytes(self.pk)), "token": account_activation_token.make_token(self), "activate_url": CLIENT_DOMAIN }) try: email = EmailMessage( subject=mail_subject, body=mail_message, to=[self.email] ) email.content_subtype = "html" email.send() except BadHeaderError: return HttpResponse("Invalid header found!") except Exception as e: return HttpResponse("Something went wrong!") def activate(request, uidb64, token): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = PortalUser.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, PortalUser.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() return Response({"message": "activation_successful"}, status=status.HTTP_200_OK) else: return Response({"message": "activation_failed"}, status=status.HTTP_400_BAD_REQUEST) Account Activation Mail Template account_activate_email.html <a href="{{ activate_url }}{% url 'portal_user:account-activate' uidb64=uid token=token %}"> {{ activate_url }}{% url 'portal_user:account-activate' uidb64=uid token=token %} </a> Whenever I'm trying to send email to users using send_account_activation_mail … -
How should I safely add an entry to a database for my Django website without a user entering any data?
I am building a website using Django and Spotipy. When a new user enters the website, they press a button and are redirected to Spotify's login page to authorize the website. I would like to use the get_or_create() method to create a new entry in my database for that Spotify user if one does not already exist. However, the Django documentation says to use get_or_create() only in POST requests. The issue is that after authorizing my website on the Spotify page, you are directed to a callback view where the request method is GET. How would I go about creating a POST request in the callback view so I can safely add the user? Alternatively, is it bad practice to add to a database on a callback page? If so, when and how would you reccommend I add the users information? I considered using get() and create() separately but I imagine anytime create() is used should be in a POST request. After doing some reading, it also seems that it may be possible to use pythons request library, but this seems like it would be unnecessary. -
Django Admin: has_delete_permission
I need to implement a prohibition on removing the last ingredient from a recipe. So that the recipe is not left empty without ingredients, or make the recipe deleted when the last ingredient is deleted. model class Recipe(models.Model): name = models.CharField( max_length=200 ) author = models.ForeignKey( User, related_name='recipes', on_delete=models.CASCADE, null=True, ) text = models.TextField( ) image = models.ImageField( upload_to='recipes/' ) cooking_time = models.PositiveSmallIntegerField( validators=( MinValueValidator( MIN_VALUE ), MaxValueValidator( MAX_VALUE ), ) ) ingredients = models.ManyToManyField( Ingredient, related_name='recipes', through='IngredientRecipe' ) admin class RecipeAdmin(admin.ModelAdmin): list_display = ('name', 'author', ) list_filter = ('name', 'author', ('tags', admin.RelatedOnlyFieldListFilter),) inlines = (IngredientRecipeInline, TagRecipeInline) class IngredientRecipeInline(admin.TabularInline): model = IngredientRecipe min_num = 1 class IngredientAdmin(admin.ModelAdmin): list_display = ('name', 'measurement_unit', ) class IngredientRecipeAdmin(admin.ModelAdmin): list_display = ('recipe', 'ingredient', 'amount', ) list_filter = ('ingredient',) i try min_num = 1 but it doesnt work -
I have an error when running my Django application
I'm following a tutorial on deploying a machine learning model via django framework. Here's the link to the tutorial Link1 I followed all the steps correctly up to step 3. First, I wrote all the code myself. Seeing that my application wasn't working, I copied and pasted all the Django code from the site. Here's the link to my project on gitHub Link2 I'm using python 3.6 and django==2.2.4 When I run python manage.py runserver in my terminal, I get this error message: (venv) C:\Users\SEYDOU GORO\my_ml_service2\backend\server>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\SEYDOU GORO\my_ml_service2\venv\lib\site-packages\django\urls\resolvers.py", line 604, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\SEYDOU GORO\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\SEYDOU GORO\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\SEYDOU GORO\my_ml_service2\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\SEYDOU GORO\my_ml_service2\venv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\SEYDOU GORO\my_ml_service2\venv\lib\site-packages\django\core\management\base.py", line 423, in check databases=databases, File "C:\Users\SEYDOU GORO\my_ml_service2\venv\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\SEYDOU GORO\my_ml_service2\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\SEYDOU … -
ManyToMany category field -- Display title instead of id in django restframework
ManyToMany category field -- Display title instead of id in django restframework Models class Category(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(max_length=50,null=False, unique=True) def __str__(self): return self.title class BlogPostModel(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE,null=True,blank=True) category = models.ManyToManyField(Category, related_name='catitems') title = models.CharField(max_length=255) body = models.TextField() slug = models.SlugField(max_length=255,null=False, unique=True) background_image = models.ImageField(upload_to='post-images',blank=True) image1 = models.ImageField(upload_to='post-images',blank=True) image2 = models.ImageField(upload_to='post-images',blank=True) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title i want display category's title instead of category's id Serializer class PostSerializer(serializers.ModelSerializer): author = serializers.CharField(source='author.email', read_only=True) class Meta: model = BlogPostModel fields = ['author','category','title','body','slug','background_image','created_date'] This is the result of my codes: "category": [ 1, 2, 3 ], And i want this: "category": [ Category title(1)، Category title(2)، Category title(3) ], -
How to write a serializer to pass SVG files via DRF API using drf_extra_fields
I'm trying to make a serializer to pass an SVG file between an API and a client. models.py: class Event(models.Model): name = models.CharField(blank=True, null=True, max_length=256, verbose_name='Название') cover = models.ImageField(blank=True, null=True, upload_to='events/images/', verbose_name='Баннер') category = models.ForeignKey('Category', blank=True, null=True, on_delete=models.DO_NOTHING, verbose_name='Категория') tags = models.ManyToManyField('Tag', verbose_name='Тэги') description = models.TextField(blank=True, null=True, verbose_name='Описание') age_limit = models.IntegerField(default=0, verbose_name='Возрастное орграничение') artists = models.ManyToManyField(Artist, blank=True, related_name='events_artist', verbose_name='Артисты') platform = models.ForeignKey('Platform', blank=True, null=True, on_delete=models.DO_NOTHING, verbose_name='Площадка') video = models.TextField(blank=True, null=True, verbose_name='Ссылка на видео') price = models.IntegerField(default=0, verbose_name='Цена') total_tickets = models.IntegerField(blank=True, null=True, verbose_name='Всего билетов') tickets = models.ManyToManyField(CustomUser, blank=True, related_name='events_user', verbose_name='Билеты') open = models.BooleanField(default=True, verbose_name='Событие открыто') comments = models.ManyToManyField('Comment', blank=True, related_name='events_comment', verbose_name='Комментарии') when = models.DateTimeField(blank=True, null=True, verbose_name='Дата и время') def __str__(self): return self.name class Meta: verbose_name = 'Событие' verbose_name_plural = 'События' serializers.py: class EventSerializer(serializers.ModelSerializer): cover = Base64ImageField(represent_in_base64=True, required=False) category = CategorySerializer(required=False) tags = TagSerializer(many=True, required=False) artists = ArtistSerializer(many=True, required=False) platform = PlatformSerializer(required=False) comments = CommentSerializer(many=True, required=False) tickets = CustomUserSerializer(many=True, required=False) class Meta: model = Event fields = ('id', 'name', 'cover', 'category', 'tags', 'description', 'age_limit', 'artists', 'platform', 'video', 'price', 'total_tickets', 'tickets', 'open', 'when', 'comments') But when I try to POST a cover with an SVG image converted to BASE64, I get the error {"cover":["Please upload a valid image."]}. Please tell me how to … -
router port forwarding to server not worked in iphone
I developed a simple website using Django framework for some tasks, the Django server currently running on my local network but in some case there is a user wan't to access website outside local network (from home) so I configured the port forwarding in my router to host where django server run into it the website runs on different devices and operating systems like linux, windows and android but except for the iPhone and this error appear in server Any help would be greatly appreciated! Traceback (most recent call last): File "/usr/lib/python3.11/socketserver.py", line 691, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python3.11/socketserver.py", line 361, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python3.11/socketserver.py", line 755, in __init__ self.handle() File "/home/mahmoud/Downloads/project/env/lib/python3.11/site-packages/django/core/servers/basehttp.py", line 229, in handle self.handle_one_request() File "/home/mahmoud/Downloads/project/env/lib/python3.11/site-packages/django/core/servers/basehttp.py", line 237, in handle_one_request self.raw_requestline = self.rfile.readline(65537) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.11/socket.py", line 706, in readinto return self._sock.recv_into(b) ^^^^^^^^^^^^^^^^^^^^^^^ TimeoutError: [Errno 110] Connection timed out -
How to use JavaScript to replace div content in Django/Flask template?
I have a Django/Flask template : <div class="progress-dot-container"> {% for question in range(max_value) %} <div class="progress-dot"></div> {% endfor %} </div> I want to use JavaScript to change the template to: <div class="progress-dot-container"> {% for question in range(max_value) %} <div class="progress-dot {{active}}"></div> {% endfor %} </div> I have no idea where to start ,I only know how to directly use JavaScript to change the class name ,but this is not what I want ,any friend can help ?