Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 ? -
How can I let users update the data in database through HTML in Django?
what I want do make is that show the existing data in the database to a user through HTML page. let a user update the existing data if he wants to do. Promblem 1> the problem is that,when running my code, a user input the new data and clicked 'update' button, but the update did not work. Problem 2> I set memo field in model like this : memo=models.CharField(max_length=100) However,after running the code, it just showed only one character of long characters in HTML. Please refer to the below codes and result image. <models.py> class Memo(models.Model): memo = models.CharField(max_length=100) user_input = models.CharField(max_length=100) def __str__(self): return f" {self.memo} | {self.user_input} " <forms.py> from django import forms from report.models import Upload, Memo class UploadFileForm(forms.ModelForm): class Meta: model=Upload fields=('upload_file',) class InputForm(forms.Form): memo = forms.CharField() user_input = forms.IntegerField() <views.py> def input(request): items = Memo.objects.all() if request.method == 'POST': form = InputForm(request.POST) if form.is_valid(): # Get the item instance based on the memo from the form memo = form.cleaned_data['memo'] item = Memo.objects.get(memo=memo) # Update the item with the new data from the form item.memo = form.cleaned_data['memo'] item.user_input = form.cleaned_data['user_input'] # Update other fields as needed item.save() return redirect('report/success.html') # Redirect to the table display page … -
Static files won't load
I`ve created a new Django project and ran into a problem with static images. So, apparently when i was connecting my css and javascript files with static it worked well, but when i tried to connect images they won't load. here is my settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_DIRS = ['static'] # Default primary key field type # https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' LOGIN_REDIRECT_URL = '/' urls.py from django.contrib import admin from django.urls import path, include from store import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('mstore.urls')), ] if settings.DEBUG: from django.conf.urls.static import static urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) here is example of how i display it in template <a href="#" class="item__image"> <picture><source srcset="img/collections/featured/02.webp" type="image/webp"><img src="{% static 'mstore/img/collections/featured/02.png' %}" alt="Lore Walnut"></picture></a> Please, before answering note that i checked the src of the image in browser, and it worked. src of image in browser i copied this link and pasted in browser and got this enter image description here Besides, css and js works great, so i think the problem is in images I tried to run python manage.py collectstatic and it worked perfectly. -
unable to fetch the data of uploaded JSON file in database Django
I am trying to create a panel where the user uploads his JSON file and it shows result in a specific manner using the D3.js library but it causing some error here is the code models.py class JSONFile(models.Model): user = models.ForeignKey(User ,on_delete=models.CASCADE,related_name='file') files = models.FileField(upload_to='json_files', null=True) uploaded_at = models.DateTimeField(default=timezone.now,editable=False) views.py def home(request): if request.method == 'POST': form = JSONFileUploadForm(request.POST, request.FILES) if form.is_valid(): json_data = json.load(form.cleaned_data['files']) json_str = json.dumps(json_data) return render(request, 'visualization.html', {'json_str': json_str}) else: form = JSONFileUploadForm() return render(request, 'home.html', {'form': form}) and in Visualization.html <h2>Data Visualization</h2> <div id="visualization"></div> <script src="https://d3js.org/d3.v7.min.js"></script> <script> var jsonData = {{ json_str|safe }}; </script> the file gets uploaded in my media but I am unable to show it in visualization.html traceback -
having issue to update user profile in Django
I wanted to make an update profile function where users can update their data by filling out a form. My website is running well without any errors, but whenever I fill up the form & hit submit the profile doesn't update itself & also new data is not saved. Here are my codes: views.py: def userProfile(request): return render(request, 'home/profile.html') def updateProfile(request): if request.method == 'POST': profile = UserProfile.objects.get(pk=request.user.profile.pk) profile_form = UserProfile(request.POST, instance=profile) if profile_form.is_valid(): profile_form.save() return redirect('profile') else: profile = UserProfile.objects.get(pk=request.user.profile.pk) profile_form = UserProfile(instance=profile) return render(request, 'profile.html', { 'profile_form': profile_form, 'errors': profile_form.errors() }) forms.py from django import forms from .models import user class UserProfile(forms.ModelForm): class Meta: model = user fields = ['username', 'first_name', 'last_name', 'email'] models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class Contact(models.Model): sno= models.AutoField(primary_key=True) name= models.CharField(max_length=255) phone= models.CharField(max_length=13) email= models.CharField(max_length=100) content= models.TextField() timeStamp=models.DateTimeField(auto_now_add=True, blank=True) def __str__(self): return "Message from " + self.name + ' - ' + self.email profile.html {% extends 'base.html' %} {% block title %} User Profile {% endblock title %} {% block body %} <div> <h1 class="m-4" style="color: teal;">User Profile</h1> <h2 class="m-4"> Welcome {{user.username}} </h2> <h2 class="m-4"> First Name: {{user.first_name}} </h2> <h2 class="m-4"> Last … -
Registering custom path converters in django
I am learning Django custom path converter and its registration while I understand all the string integer sledge and uuid Types of url modifications but while registering a custom path converter I have problems and I didn't understand the syntax of its registration need help to solve this problem class FourDigitYearConverter: regex = "[0-9]{4}" def to_python(self, value): return int(value) def to_url(self, value): return "%04d" % value what is the use of regex class level variable , and the use of to_python , to_url methods below is Registration code but i cna understand it if i understand the above code from django.urls import path, register_converter from . import converters, views register_converter(converters.FourDigitYearConverter, "yyyy") urlpatterns = [ path("articles/2003/", views.special_case_2003), path("articles/<yyyy:year>/", views.year_archive), ..., ] I want to understand the core functionality of To_url and to_python method and the use of class level regex variable