Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Orders and quotes with client register in django
`HTML: `{% csrf_token %} {{ form | crispy }} <select id="id_cliente" name="cliente" onchange="update_cliente_data()"> <option value="">Selecione um cliente...</option> {% for cliente in clientes %} {% with cliente_data=cliente.to_json %} <option id="opcao" value="{{ cliente.id }}" data-cliente="{% for key, value in cliente_data.items %}'{{ key }}': '{{ value|escapejs }}',{% endfor %}">{{ cliente.nome }}</option> {% endwith %} {% endfor %} </select>` SCRIPT: `<script> // Chamar a função update_cliente_data() quando o DOM é carregado document.addEventListener('DOMContentLoaded', function() { console.log('DOM carregado.'); update_cliente_data(); }); function update_cliente_data() { var clienteSelect = document.getElementById('id_cliente'); if (clienteSelect) { var selectedIndex = clienteSelect.selectedIndex; if (selectedIndex !== -1) { var clienteOption = clienteSelect.options[selectedIndex]; //var clienteOpcao = document.getElementById('opcao'); var clienteDataAttr = clienteOption.getAttribute('data-cliente'); //var clienteDataAttr = clienteOpcao.getAttribute('data-cliente'); if (clienteDataAttr) { try { var clienteData = JSON.parse(clienteDataAttr); document.getElementById('id_nome').value = clienteData.nome; document.getElementById('id_cpf').value = clienteData.cpf; document.getElementById('id_email').value = clienteData.email; document.getElementById('id_rg').value = clienteData.rg; document.getElementById('id_cidade').value = clienteData.cidade; document.getElementById('id_telefone').value = clienteData.telefone; document.getElementById('id_numero').value = clienteData.numero; document.getElementById('id_rua').value = clienteData.rua; document.getElementById('id_bairro').value = clienteData.bairro; } catch (error) { console.error('Erro ao analisar os dados do cliente:', error); } } else { console.error('Atributo "data-cliente" não encontrado no elemento selecionado.'); } } else { console.error('Nenhum item selecionado no select.'); } } else { console.error('Elemento com ID "id_cliente" não encontrado no DOM.'); } } </script>`` It all seems correctly for me, but the … -
Create a Profile model for a specific user (Django 4.0)?
Does anybody know how to create a Profile for the user upon completion of the registration form??? (Django) views.py: class UserRegisterView(generic.CreateView): form_class = SignUpForm #Imported from forms template_name = 'registration/register.html' success_url = reverse_lazy('login') def form_valid(self, form): response = super().form_valid(form) return response models.py class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) #rpg_class = models.CharField(max_length=100) def __str__(self): return str(self.user) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() I tried this and it doesnt work, It says something like Internal Server Error: /CodeRPGappMain/register/ Traceback (most recent call last): File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\sqlite3\base.py", line 328, in execute return super().execute(query, params) sqlite3.IntegrityError: NOT NULL constraint failed: CodeRPGappMain_profile.bio Making a Profile manually in the admin isnt going to work So I need it to create itself automatically every time a user signs up, it already creates a user bc of Djangos built in stuff but I need to create its custom model Profile for the user upon completion -
Django Error EnvError Environment Variable Debug Not Set
I am working on Django for beginners and in Django for beginners I am told to create an .env file and have it exisit in the same root directory next to the existing .gitignore file. It teaches that we should never deploy a site into production with DEBUG turned on as it provides a treasure map for hackers to destroy or alter my website. Instead we want debug to be true for local development and false for production. In the instructions it says go into my .env file and set DEBUG=True without spaces and than for my django_project/settings.py file have the DEBUG = env.bool(“DEBUG”) I do this and I get the following error message ERROR MESSAGE: (.venv) andrewstribling@Andrews-MBP blog % python manage.py runserver Traceback (most recent call last): File “/Users/andrewstribling/Desktop/code/blog/manage.py”, line 22, in main() File “/Users/andrewstribling/Desktop/code/blog/manage.py”, line 18, in main execute_from_command_line(sys.argv) File “/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/management/init.py”, line 442, in execute_from_command_line utility.execute() File “/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/management/init.py”, line 382, in execute settings.INSTALLED_APPS File “/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/conf/init.py”, line 102, in getattr self._setup(name) File “/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/conf/init.py”, line 89, in _setup self._wrapped = Settings(settings_module) File “/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/conf/init.py”, line 217, in init mod = importlib.import_module(self.SETTINGS_MODULE) File “/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/importlib/init.py”, line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File “”, line 1030, in _gcd_import File “”, line 1007, … -
Django Queryset Lookup Encrypted Column
I have these 2 classes to encrypt and decrypt an email address in the postgres database using pgcrypto. They both work. One uses a postgres bytea column while the other uses a postgres varchar column. The problem though I face is though is this: >>> CustomUser.objects.filter(email="jbonte30@sunfuesty.com") <QuerySet []> CustomUser.objects.filter(username="jtwlucas").values_list("email", flat=True) <QuerySet ['jtwlucas@arshopshop.xyz']> >>> CustomUser.objects.filter(username="jtwlucas").values_list("email", flat=True) <QuerySet [None]> select PGP_SYM_DECRYPT(email::bytea, 'SECRET_KEY') from authentication_customuser; jtwlucas@arshopshop.xyz 'jtwlucas@arshopshop.xyz' in CustomUser.objects.values_list('email', flat=True) True` Even though that email address exists in the database. The database shows this for the varchar column: xc30d04090302b95c598cd3d427836dd24c01eb524973d9a2742acb4e24091faf0bb6507c338d97dcfac6fbfda038c34fc6bbd59ccad723acf4235c9825fe14981b7ae2e63fc79277cf442480f30249adefaa964b9f19be3592c9f0c219 The database shows this for the bytea column: [binary data] If possible I want the be able to perform the lookups as I am doing them in this example automatically without needing to change my entire code base's ORM querysets. I do not want to use any third party github libraries. #postgres bytea column class SecureEmail(models.EmailField): """Custom Encrypted Field""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.secret_key = str(settings.SECRET_KEY) def from_db_value(self, value, expression, connection): # Decrypt value when reading from database if value is not None: cursor = connection.cursor() cursor.execute("SELECT pgp_sym_decrypt(%s::bytea, %s)::text", [value, self.secret_key]) return cursor.fetchone()[0] def get_prep_value(self, value): # Encrypt value when writing to database cursor = connection.cursor() cursor.execute("SELECT pgp_sym_encrypt(%s::text, %s)", … -
Index page from React Router Dom not showing in Django
I have 2 different apps Landing and Main. Both use react build files as templates and static files to render information on the web page. This works fine for the Landing app but not the Main app, which is probably because despite both using React Router Dom, the routes on the Main app redirect the user to /boards instead of having an index page - so the path is http://127.0.0.1:8000/[username]/boards instead of just http://127.0.0.1:8000/[username]. Instead of being redirected to the correct page, all that is shown is a blank page. I already tested this to see if something would be shown on the webpage if there was an index page and there is. The Landing app's routes does have an index page and this works fine. I also tried adding this re_path re_path(r".*") but this doesn't work either. How do I fix this? Main urls.py urlpatterns = [ # path('', views.index, name='index'), re_path(r".*", views.index, name='index') # does not work ] Main App.jsx export default function App() { const [current, setCurrent] = useState(); return ( <> <BrowserRouter> <Routes> <Route path="/" element={<Layout setCurrent={setCurrent} />} > <Route index element={<Navigate to="/boards" />} /> <Route path="boards" element={<Boards />} /> ... </Route> </Routes> </BrowserRouter> </> ); … -
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