Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
wanted to install face_recogination
Building wheel for dlib (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for dlib (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [78 lines of output] running bdist_wheel running build running build_ext <string>:125: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. Building extension for Python 3.11.1 (tags/v3.11.1:a7a450f, Dec 6 2022, 19:58:39) [MSC v.1934 64 bit (AMD64)] Invoking CMake setup: 'cmake C:\Users\aakas\AppData\Local\Temp\pip-install-1rhspvxa\dlib_5ca8c32667e347dba6c125d560c25827\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\aakas\AppData\Local\Temp\pip-install-1rhspvxa\dlib_5ca8c32667e347dba6c125d560c25827\build\lib.win-amd64-cpython-311 -DPYTHON_EXECUTABLE=F:\codeClause\faceAuth\env\Scripts\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\aakas\AppData\Local\Temp\pip-install-1rhspvxa\dlib_5ca8c32667e347dba6c125d560c25827\build\lib.win-amd64-cpython-311 -A x64' -- Building for: NMake Makefiles CMake Error at CMakeLists.txt:5 (message): !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! You must use Visual Studio to build a python extension on windows. If you are getting this error it means you have not installed Visual C++. Note that there are many flavors of Visual Studio, like Visual Studio for C# development. You need to install Visual Studio for C++. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -- Configuring incomplete, errors occurred! Traceback (most recent call last): File "F:\codeClause\faceAuth\env\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 353, in <module> main() File "F:\codeClause\faceAuth\env\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "F:\codeClause\faceAuth\env\Lib\site-packages\pip\_vendor\pyproject_hooks\_in_process\_in_process.py", line 251, in build_wheel return _build_backend().build_wheel(wheel_directory, config_settings, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\aakas\AppData\Local\Temp\pip-build-env-9jngamvo\overlay\Lib\site-packages\setuptools\build_meta.py", line 416, in build_wheel return self._build_with_temp_dir(['bdist_wheel'], '.whl', ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\aakas\AppData\Local\Temp\pip-build-env-9jngamvo\overlay\Lib\site-packages\setuptools\build_meta.py", line 401, in _build_with_temp_dir self.run_setup() File "C:\Users\aakas\AppData\Local\Temp\pip-build-env-9jngamvo\overlay\Lib\site-packages\setuptools\build_meta.py", line 338, in run_setup exec(code, locals()) File "<string>", line 218, in <module> File "C:\Users\aakas\AppData\Local\Temp\pip-build-env-9jngamvo\overlay\Lib\site-packages\setuptools\__init__.py", … -
Getting rain data and rain forecast using openweather map api
Am having a hard time to call rain data from openweather map api. Have anyone ever tried calling the rain data of current weather and it's amount. Also, I have not been able to make predictions like it will rain. Like making the forecasts about rainfall probability. I tried using rain = data['weather'][0]['rain'] I used the same way to call the temperature, description and humidity but on rain it does not work. Am on free plan -
Heroku Migrate not Applying Migrations(Django)
From the first image heroku run python/python3 manage.py migrate is running successfully and applying the migrations. From the second image while trying to create a superuser, I get the error 'unapplied migrations' I have been debugging for almost an hour and it's getting into my nerves. A solution will be helpful. -
Cannot get session data inside a template
I have a Django app with pages as a website. I have a separate Vue app that uses Django Rest Framework for providing the data. I log in on the Vue app and not on the Django app but I would like to show on the Django app that I am logged in also. I have this view for loggin a user in and it works perfectly and I can see the session entry is created in the database. @api_view(["POST"]) def LoginUser(request, *args, **kwargs): email = request.data.get("email") username = request.data.get("username") password = request.data.get("password") if email is None: exists = User.objects.filter(username=username).exists() else: exists = User.objects.filter(email=email).exists() if exists: if email is None: user = User.objects.get(username=username) else: user = User.objects.get(email=email) if user.is_active and user.email_verified_at is not None and user.password != "": if email is None: user = authenticate(username=username, password=password) else: user = authenticate(email=email, password=password) if user: session = SessionStore() session['loggedin'] = True session.save() serializer = LoginSerializer(user) token, created = Token.objects.get_or_create(user=user) response_data = { "Authorization": token.key, "verified": user.verified, "upgraded": user.upgraded, "user": serializer.data } return Response(response_data, status=HTTP_200_OK) else: return Response("Wrong email and/or password", status=HTTP_401_UNAUTHORIZED) else: return Response("Account not active! Changed your email or password?") else: return Response("Email is not registered, please register") On the normal … -
How can i make sure an object wont be added twice
i want to add a movie to watchlist, this is the Movie model from django.db import models # Create your models here. from django.db import models from django.contrib.auth.models import User from Crew.models import * # from Movies.models import Audience_Review from Details.models import * # Create your models here. # Foreign keys are bookmarked class Movie(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE,default=True) name=models.CharField(max_length=100,unique=True) slug=models.SlugField(max_length=100,unique=True,blank=True) year=models.CharField(max_length=5,blank=True) language=models.CharField(max_length=50,blank=True) release=models.CharField(max_length=100,blank=True) rating=models.CharField(max_length=20,blank=True) audience_score=models.CharField(max_length=20,blank=True,null=True) poster=models.ImageField(upload_to='movies/poster',blank=True) cover=models.ImageField(upload_to='movies/cover',null=True,blank=True) duration=models.CharField(max_length=50,default=None,blank=True) streaming=models.ForeignKey(Streaming,on_delete=models.CASCADE,blank=True,null=True) ott=models.TextField(max_length=50,blank=True,null=True) starring= models.ForeignKey(Actor,on_delete=models.CASCADE,related_name='actors',blank=True,null=True) actors=models.ManyToManyField(Actor,related_name='actor',blank=True) Characters=models.ManyToManyField(Character,related_name='character',blank=True) director=models.ForeignKey(Director,on_delete=models.CASCADE,blank=True,null=True) writers=models.ManyToManyField(Writer,related_name='writer',blank=True) cinematographer=models.ForeignKey(Cinematographer,on_delete=models.CASCADE,null=True,blank=True) based =models.CharField(max_length=100,blank=True,null=True) genres=models.ManyToManyField(Genre,blank=True) certification=models.ForeignKey(Certification,on_delete=models.CASCADE,null=True,blank=True) synopsis=models.TextField(max_length=1000,blank=True) trailer=models.CharField(max_length=500,blank=True) def __str__(self): return self.name this is my Watchlist model, the movie is taken as a foreignkey from django.db import models from django.contrib.auth.models import User from Movies.models import Movie # Create your models here. class Watchlist(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) movie=models.ForeignKey(Movie,on_delete=models.CASCADE) quantity=models.IntegerField(default=1) date=models.DateField(auto_now_add=True) def __str__(self): return self.movie.name this is the url i use to add it to watchlist: href="{% url 'Watchlist:add_watchlist' mov.id %}" this is the path from django.urls import path from Watchlist import views app_name='Watchlist' urlpatterns = [ path('view_watchlist',views.view_watchlist,name='view_watchlist'), path('add_watchlist/<int:p>',views.add_watchlist,name='add_watchlist'), path('delete_watchlist/<int:p>',views.delete_watchlist,name='delete_watchlist') ] this is the views.py type herefrom django.shortcuts import render,redirect from Movies.models import Movie from Movies.views import * from Watchlist.models import Watchlist from django.contrib import messages # from django.contrib.auth.decorators import login_required # Create your views here. def view_watchlist(request): user=request.user watchlist=Watchlist.objects.filter(user=user) #filter … -
How to delete message.info in python django after refreshing the page?
views.py def index(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('register:index') else: messages.info(request, "Username or password incorrect.") return render(request, 'login/login.html') login.html <form action="" method="POST" class="poster"> {% csrf_token %} <div class="input-group mb-4"> <span class="input-group-text"><i class="fas fa-user-alt"></i></span> <input class="form-control" placeholder="Username" required="" type="text" name="username"> </div> <div class="input-group mb-4"> <span class="input-group-text"><i class="fas fa-user-alt"></i></span> <input type="password" id="myInput" placeholder="Password" name="password" class="form-control" data-toggle="password"> </div> <div class="input-group mb-4 d-grid"> <input type="button" class="btn btn-primary" onclick="myFunction()" value="Show password" style="color: aliceblue;" id="show"> </div> <div class="d-grid"> <button type="submit" class="btn btn-success">Sign in</button> <br> <p class="text-center"> Don't have an account? <a href="{% url 'register:index' %}">Sign up</a> </p> </div> </form> {% if messages %} <ul class="messages"> {% for message in messages %} <li style="list-style-type: none; color:rgb(195, 67, 67);"> {{ message }} </li> {% endfor %} </ul> {% endif %} I don't know how to make clear page after refreshing. The message "Username or password incorrect." is always displaying after inputs was incorrect. I've gooogled this problem but it seems to be that everyone pass this problem somehow :/ -
Django Test Client Session expiry
from django.test import Client is not taking expiry I'm setting in my view def form_valid(self, form): remember_me = form.cleaned_data["remember_me"] print("Remember me:", remember_me) # Debug print if not remember_me: self.request.session.set_expiry(1) self.request.session.modified = True return super().form_valid(form) When calling it in testcase def test_form_valid(self): self.client.session.create() # Create a new session for this test case response = self.client.post(reverse('user:login'), {'username': 'testuser', 'password': 'testpassword', 'remember_me': False}, follow=True) expiry_age = self.client.session.get_expiry_age() self.assertRedirects(response, reverse('guarantee:guarantee_list'), fetch_redirect_response=False) print('Session Expiry:', expiry_age) # Since it's not setting to 0 or 1, let's check if it's default (2 weeks) two_weeks_in_secs = 2 * 7 * 24 * 60 * 60 self.assertNotEqual(expiry_age, two_weeks_in_secs) getting Session Expiry: 1209600 -
need help about add function in python django [closed]
the Problem is, that i can not add a new entry. nothing happens when i klick the button! i have checked everything but find no error. i found the project on youtube and wanted to build these to my needs. to do this I watched the video and enter the code. this is my first python code project with django - can someone help me . . . ? here´s my data from the project views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from App.models import Customer from django.contrib import messages from django.http import HttpResponseRedirect # function to insert customer @login_required(login_url = "login") def add_customer(request): if request.method == "POST": if request.POST.get('plantname') and request.POST.get('last_name') and request.POST.get('first_name') and request.POST.get('address') and request.POST.get('zip_code') and request.POST.get('place') and request.POST.get('phone') and request.POST.get('phone2') and request.POST.get('email') and request.POST.get('startup') and request.POST.get('plant_power') and request.POST.get('grid_operator') and request.POST.get('feedintariff') and request.POST.get('own_consumption') and request.POST.get('effect_limit') and request.POST.get('specific_annuayl_yield') and request.POST.get('portal') and request.POST.get('sn_homemanager') and request.POST.get('sn_wifi_modul') and request.POST.get('passwort_portal') and request.POST.get('inverter1') and request.POST.get('inverter1_sn') and request.POST.get('inverter2') and request.POST.get('inverter2_sn') and request.POST.get('batterieinverter') and request.POST.get('batterieinverter_sn') and request.POST.get('batteriemodul') and request.POST.get('plant_password') or request.POST.get('description') and request.POST.get('appointment') and request.POST.get('appointment_done'): customer = Customer() customer.plantname = request.POST.get('plantname') customer.last_name = request.POST.get('last_name') customer.first_name = request.POST.get('first_name') ....... customer.appointment_done = request.POST.get('appointment_done') customer.save() messages.success(request, "Customer added successfully") return HttpResponseRedirect('/backend') else: return render(request, "add.html") urls.py … -
Which is the better django workflows?
Which django-workflow is easy to implement for a project? Iam trying in viewflows and some of the errors are not yet fixed.And is this a good workflow to implement or not?.Iam trying in many ways and not able to get a final result. -
How to send a mail for Mandatory fields if user is updating and non mandatory fields should save in DB in django
If user the is having SPOC role and if user Updating any Mandatory fields in frontend , in back end a mail should trigger to PL with user entered data and existing data of that filed in DB. But data should not save in DB(Data we got in front end by json format) if user is updating any non mandatory fields it should directly save in DB i am implanted this code in django using Curd operation Result which i got : if passed mandatory filed mail is not trigging it saving as new record in DB My code is : @api_view(['PUT']) @csrf_exempt @transaction.atomic def UpdateOnboarding(request): if request.method == 'PUT': data = { "id": 4, "EmpID" : 22470200, } records = Onboarding.objects.filter(id=data['id']) mandatory_fields = ['EmpID ', 'EMP_Name','LAN_Request_Number'] if any(field in data for field in mandatory_fields): if NewUser.UserRole == "SPOC": records = Onboarding.objects.first() send_mail(data,records) # sending mail part return JsonResponse({'message': 'Mail Sent to PL.'}) else: return JsonResponse({'message': 'Invalid'}) instance = Onboarding(**data) instance.save() else: return JsonResponse({'message': 'Not a Put Method'}) data which we got from front in json format for testing purpose i have given data in code data = json.loads(request.body) can anyone please help me -
502 bad gateway error on Django Nginx Graphql gunicorn application
My technology stack is, Django Graphql nginx gunicorn Below is the function which is used to reset the password. It is using GraphQLClient call where I am providing api endpoint to reset the password. def password_reset(request, token): message = '' messageStatus = False if request.method =='POST': password1 = request.POST.get('password1','') password2 = request.POST.get('password2','') client = GraphQLClient('http://leagueoftennis.com/graphql/') query = """ mutation PasswordReset($password1: String!, $password2:String!, $token:String!){ passwordReset(newPassword1: $password1, newPassword2: $password2, token: $token) { errors success } } """ variables = {'token': token, 'password1':password1, 'password2':password2} result = client.execute(query, variables) result_json = json.loads(result) if result_json['data']['passwordReset']['success']: message = "Your password has been set." messageStatus = True elif result_json['data']['passwordReset']['errors']: if 'nonFieldErrors' in result_json['data']['passwordReset']['errors']: message = result_json['data']['passwordReset']['errors']['nonFieldErrors'][0]['message'] elif 'newPassword2' in result_json['data']['passwordReset']['errors']: message = result_json['data']['passwordReset']['errors']['newPassword2'][0]['message'] else: message = "Something Went Wrong. Try Again!" else: message = "Link is expired!" context = { 'messageStatus': messageStatus, 'message': message, 'token': token, } template = loader.get_template('account/password_reset.html') return HttpResponse(template.render(context, request)) Above method is called when user clicks on below link, http://leagueoftennis.com/activate/eyJlbWFpbCI6ImthbHBlc2h0YXdkZUBvdXRsb29rLmNvbSIsImFjdGlvbiI6ImFjdGl2YXRpb24ifQ:1qMLtK:IUaG2ZYF1vdavJhuVzXAsYotR3agrfPqnJzTpmijRU0 But in return I am getting 502 bad gateway error. Below is my nginx config, upstream sports_league { server web:8000; } server { listen 80; location / { proxy_pass http://sports_league; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias … -
Only one movie is being added to watchlist
iam working on a movie app and wants to add movie to watchlist. this is my Movie model which is on the app Movies from django.db import models # Create your models here. from django.db import models from django.contrib.auth.models import User from Crew.models import * # from Movies.models import Audience_Review from Details.models import * # Create your models here. # Foreign keys are bookmarked class Movie(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE,default=True) name=models.CharField(max_length=100,unique=True) slug=models.SlugField(max_length=100,unique=True,blank=True) year=models.CharField(max_length=5,blank=True) language=models.CharField(max_length=50,blank=True) release=models.CharField(max_length=100,blank=True) rating=models.CharField(max_length=20,blank=True) audience_score=models.CharField(max_length=20,blank=True,null=True) poster=models.ImageField(upload_to='movies/poster',blank=True) cover=models.ImageField(upload_to='movies/cover',null=True,blank=True) duration=models.CharField(max_length=50,default=None,blank=True) streaming=models.ForeignKey(Streaming,on_delete=models.CASCADE,blank=True,null=True) ott=models.TextField(max_length=50,blank=True,null=True) starring= models.ForeignKey(Actor,on_delete=models.CASCADE,related_name='actors',blank=True,null=True) actors=models.ManyToManyField(Actor,related_name='actor',blank=True) Characters=models.ManyToManyField(Character,related_name='character',blank=True) director=models.ForeignKey(Director,on_delete=models.CASCADE,blank=True,null=True) writers=models.ManyToManyField(Writer,related_name='writer',blank=True) cinematographer=models.ForeignKey(Cinematographer,on_delete=models.CASCADE,null=True,blank=True) based =models.CharField(max_length=100,blank=True,null=True) genres=models.ManyToManyField(Genre,blank=True) certification=models.ForeignKey(Certification,on_delete=models.CASCADE,null=True,blank=True) synopsis=models.TextField(max_length=1000,blank=True) trailer=models.CharField(max_length=500,blank=True) def __str__(self): return self.name i want to add movies to watchlist,and this is my Watchlist model which is in the app Watchlist from django.db import models from django.contrib.auth.models import User from Movies.models import Movie # Create your models here. class Watchlist(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE,default=User) movie = models.OneToOneField(Movie,on_delete=models.CASCADE) slug=models.SlugField(unique=True,max_length=50) date_added=models.DateField(auto_now_add=True) def __str__(self): return self.movie.name iam calling this function from this address in the movie detail page. {% url 'Watchlist:add_watchlist' mov.id %} this is the path from django.urls import path from Watchlist import views app_name='Watchlist' urlpatterns = [ # function based path path('add_watchlist/<int:p>',views.add_watchlist,name='add_watchlist'), path('view_watchlist',views.watchlist,name='view_watchlist'), path('delete_watchlist/<int:p>',views.delete_watchlist,name='delete_watchlist'), ] this is the views.py of watchlist from django.shortcuts import render,redirect from Movies.models import Movie from Movies.views … -
My mail webapp wont display sent emails or send the emails CS50 project
im doing project 3 mail in cs50w and my code wont work. its supposed to display sent emails and send them but it wont work. please help. heres inbox.js document.addEventListener('DOMContentLoaded', function() { // Use buttons to toggle between views document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox')); document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent')); document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive')); document.querySelector('#compose').addEventListener('click', compose_email); document.querySelector("#compose-form").addEventListener('submit', send_email) // By default, load the inbox load_mailbox('inbox'); }); function compose_email() { // Show compose view and hide other views document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display = 'block'; document.querySelector('#email-detail-view').style.display = 'none'; // Clear out composition fields document.querySelector('#compose-recipients').value = ''; document.querySelector('#compose-subject').value = ''; document.querySelector('#compose-body').value = ''; } function view_email(event){ fetch(`/emails/${id}`) .then(response => response.json()) .then(email => { // Print email console.log(email); document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display = 'none'; document.querySelector('#email-detail-view').style.display = 'block'; document.querySelector('#email-detail-view').innerHTML = ` <ul class="list-group"> <li class="list-group-item"><strong>From:</strong>${email.sender}</li> <li class="list-group-item"><strong>To:</strong>${email.sender}</li> <li class="list-group-item"><strong>Subject:</strong>${email.sender}</li> <li class="list-group-item"><strong>Timestamp</strong>${email.sender}</li> <li class="list-group-item">${email.body}</li> ` if(!email.read){ fetch(`/emails/${email.id}`, { method: 'PUT', body: JSON.stringify({ read: true }) }) } const btn_arch = document.createElement('button'); btn_arch.innerHTML = email.archived ? "Unarchive" : "Archive"; btn_arch.className = email.archived ? "btn btn-success" : "btn btn-danger"; btn_arch.addEventListener('click', function() { fetch(`/emails/%{email.id}`, { method: 'PUT', body: JSON.stringify({ archived: !email.archived }) }) .then(() => { load_mailbox('archive')}) }); document.querySelector('#email-detail-view').append(btn-arch); const btn_reply = document.createElement('button'); btn_reply.innerHTML = "Reply"; btn_reply.className = "btn btn-info"; btn_arch.addEventListener('click', function() … -
I'm having trouble applying a js file inside my django template
I'm learning the thing with Django and I'm trying to adapt a bootstrap template for the index page I have it as follows At home.html {% load static %} <!DOCTYPE html> <!-- This is a starter template page. Use this page to start your new project from scratch. This page gets rid of all links and provides the needed markup only. --> <html lang="en"> <head> <meta charset="utf-8"> <title>{{title}}</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback"> <link rel="stylesheet" href="{% static 'lib/AdminLTE-3.2.0/plugins/fontawesome-free-6.4.0/css/all.min.css' %}"> <link rel="stylesheet" href="{% static 'lib/AdminLTE-3.2.0/css/adminlte.min.css' %}"> <script src="{% static 'lib/AdminLTE-3.2.0/plugins/jquery/jquery.min.js' %}"></script> <script src="{% static 'lib/AdminLTE-3.2.0/plugins/bootstrap/js/bootstrap.min.js' %}"></script> <script src="{% static 'lib/AdminLTE-3.2.0/js/adminlte.min.js' %}"></script> <script src="{% static 'lib/sweetalert2-9.10.0/sweetalert2.all.min.js' %}"></script> <script src="{% static 'js/functions.js' %}"></script> {% block head %} {% endblock %} </head> {% block body %} {% endblock %} </html> In index.html {% extends 'home.html' %} {% load static %} {% block head %} <link rel="shortcut icon" type="image/x-icon" href="{% static 'homepage/images/favicon.png' %}" /> <link rel="stylesheet" href="{% static 'homepage/plugins/themefisher-font/style.css' %}"> <link rel="stylesheet" href="{% static 'homepage/plugins/bootstrap/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'homepage/plugins/lightbox2/css/lightbox.min.css' %}"> <link rel="stylesheet" href="{% static 'homepage/plugins/animate/animate.css' %}"> <link rel="stylesheet" href="{% static 'homepage/plugins/slick/slick.css' %}"> <link rel="stylesheet" href="{% static 'homepage/css/style.css' %}"> <script src="{% static 'homepage/plugins/jquery/jquery.min.js' %}"></script> <script src="{% static 'homepage/plugins/parallax/jquery.parallax-1.1.3.js' %}"></script> <script src="{% static 'homepage/plugins/lightbox2/js/lightbox.min.js' %}"></script> <script src="{% … -
Async tasks in Flask using rabbitmq and Celery
I created a Django restful API. I send a post request to my Django API which then sends a message to rabbitmq. I have a microservice(Flask) that listens to that queue and processes the information sent by the message broker. I want Flask to be able to process the messages in the queue sent by django asynchronously. I'm trying to use Celery for this but I'm stuck because I see that the task is received but not processed. Below is my code(Sorry for the mess): cel.conf.update(app.config, broker_url='amqp://guest:guest@localhost:5672/', result_backend='rpc://') @cel.task() def process_task(data): print("Processing task with data:", data) time.sleep(5) print("Processing task with data:", data) return "TASK IS DONE" @app.route('/persons/') def hello_world(): def test_x(ch, method, properties, body): decode_data = body.decode('utf-8') print("Process start") process_task.apply_async(args=('a',)) print("Done!") ch.basic_ack(delivery_tag=method.delivery_tag) connection_parameters = pika.ConnectionParameters('localhost') connection = pika.BlockingConnection(connection_parameters) channel = connection.channel() channel.queue_declare(queue='test_micro', durable=True) channel.basic_qos(prefetch_count=1) channel.basic_consume(queue='test_micro', on_message_callback=test_x) print('Started test creating Consuming') channel.start_consuming()``` -
AttributeError: 'HttpResponse' object has no attribute 'data'
I'm currently building out some unit tests for my django application, however my test_views test keeps returning an error when run, and I'm unsure as to what it means and how to resolve it. This is the error I get: AttributeError: 'HttpResponse' object has no attribute 'data' This is the traceback: File "C:\Users\t-dalour\app\blog\requests\unit tests\test_views.py", line 15, in test_user_can_register_successfully self.assertEqual(res.data['email'], self.user_data['email']) ^^^^^^^^ And this is my test_views.py code: from django.test import TestCase, Client from django.urls import reverse from requests.models import Post from .test_setup import TestSetUp class TestViews(TestSetUp): def test_user_cannot_register_with_no_data(self): res=self.client.post(self.register_url) self.assertEqual(res.status_code, 200) def test_user_can_register_successfully(self): res=self.client.post( self.register_url, self.user_data, format="json") self.assertEqual(res.data['email'], self.user_data['email']) self.assertEqual(res.data['username'], self.user_data['username']) self.assertEqual(res.status_code, 201) I've tried searching the internet for a solution to the error, but can't find anything relating to it. I'm assuming it's related to the 'res.data' part? If anyone could help with how I could fix this it would be very appreciated -
Python multiple model files
This post is probably a bit more meta and less technical but.... I come from a background in C# and other C style languages. Been doing it a long time so old habits are hard to break. One of the hardest things about Python for me has been the lack of scope indicators for example. In C# there are curly braces and parenthesis and of course line break tokens all over the place. I get why python doesn't have them. But a thought occurred to me as I'm working on a django web app and the number of models I have is starting to pile up. So when I ask this question, it might just be a 'we've always done it this way' sort of thing on my part. In C# every class is generally expected to be in it's own .cs file. This does resort in large applications have hundreds of those files. Personally I find it easier to late stuff in multiple files inside visual studio, for example, than I do trying to find a single class inside one huge omnibus models.py file in pycharm. Obviously I know I can have my files any way I want. if … -
Exception Error on Password Reset loop for Django Project
I have created a login system with the ability to reset the password. The request is working perfectly when I click on "Forgot Password?"I receive the reset link however when I click the link in the email I get the error message. "Exception Type: TypeError at /accounts/reset_password_validate/MzM/brm129-52c795f84dc89b21234642b2166f5c4f/ Exception Value: reset_password() got an unexpected keyword argument 'uidb64'" I kept thinking the URL path was not routing but I have changed this twice and I am getting the same error message. URL.py from django.urls import path from . import views urlpatterns = [ # Other URL patterns... path('registerUser/', views.registerUser, name='registerUser'), path('registerBusiness/', views.registerBusiness, name='registerBusiness'), # Update the URL pattern to use the login view #path('accounts/login/', views.login, name='login'), path('login/', views.user_login, name='login'), path('logout/', views.logout, name='logout'), path('myAccount/', views.myAccount, name='myAccount'), path('custDash/', views.custDash, name='custDash'), path('bussDash/', views.bussDash, name='bussDash'), path ('activate/<uidb64>/<token>/', views.activate, name='activate'), path('forgot_password/', views.forgot_password, name='forgot_password'), path('reset_password/', views.reset_password, name='reset_password'), path('reset_password_validate/<str:uidb64>/<str:token>/', views.reset_password, name='reset_password_validate'), ] views.py from django.shortcuts import render , redirect from django.contrib.auth.hashers import make_password from business.forms import BussForm from .forms import UserForm from .models import User, userProfile from django.contrib import messages, auth from django.contrib.auth import authenticate, get_user_model, login as auth_login from .utils import detectUser, send_verification_email from django.contrib.auth.decorators import login_required, user_passes_test from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.contrib.auth.tokens import default_token_generator from … -
Different migration behavior when running with `--database`
We have a specific migration that fails when run with --database rather than running on the default connection. The migration attempts to insert a row omitting one of the fields. The model that has non-null fields and a default defined in the model. When run against the default database, this migration succeeds, but when run with --database it fails as it tries to insert null. This is not specific to the database being targeted. If I take the definition of this second database and plug it into default and run the migration, it succeeds. It only fails when it runs with a non-default database connection. This is happening on 2.2.28, but I tried upgrading up to 3.2.20 and the same behavior persists (not able to try with 4.x due to postgres version conflicts). -
FOREIGN KEY constraint failed when I'm creating a new category
I'm getting a FOREIGN KEY constraint failed error when I'm trying to create a new category in the admin panel, and this is the models.py file: `import datetime from django.db import models from UserAuthentication.models import User from shortuuid.django_fields import ShortUUIDField from django.utils.html import mark_safe STATUS=( ("Vente", "Vente"), ("Location", "Location"), ) Specification=( ("W/C douche", "W/C douche Interne"), ("W/C douche", "W/C douche Externe"), ("Eau", "Eau"), ("Cloture", "Cloture"), ("wifi", "Wifi"), ) Bookings_status = ( ("Accepter", "Accepter"), ("Refuser", "Refuser"), ("Traitement", "Traitement"), ) def user_directory_path(instance, filename): return 'user_{0}/{1}'.format(instance.user.id, filename) # Create your models here. class CategorieBienImmobilier(models.Model): cid1 = ShortUUIDField(unique=True, length=10, max_length=30, prefix="cbi", alphabet='abcdefg12345') title = models.CharField(max_length=200) picture = models.ImageField(upload_to='user_directory_path') class Meta: verbose_name_plural = "Categorie de bien Immobilier" def category_image(self): return mark_safe('<img src="%s" width="50" height="50" />' % (self.picture.url)) def __str__(self): return self.title class Ville(models.Model): Vid1 = ShortUUIDField(unique=True, length=10, max_length=30, prefix="vil", alphabet='abcdefg12345') title = models.CharField(max_length=200) picture = models.ImageField(upload_to='user_directory_path') class Meta: verbose_name_plural = "Ville" def ville_image(self): return mark_safe('<img src="%s" width="50" height="50" />' % (self.picture.url)) def __str__(self): return self.title class BienImmobilier(models.Model): Bid = ShortUUIDField(unique=True, length=10, max_length=30, prefix="bil", alphabet='abcdefg12345') title = models.CharField(max_length=200) proprietaire = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) description = models.TextField(null=True, blank=True) categoriebienimmobilier = models.ForeignKey(CategorieBienImmobilier, on_delete=models.SET_NULL, null=True) ville = models.ForeignKey(Ville, on_delete=models.SET_NULL, null=True) status = models.CharField(choices=STATUS, max_length=30) picture = models.ImageField(upload_to='user_directory_path', default="Bid.jpg") Prix … -
How to add a custom display in Django admin UI for user with only "view" permission?
If I want to change how an object is added or changed in the Django admin UI, I can simply override the form (docs). For a user with only "view" permission (no add, no change, no delete), that form doesn't even show up. If I want to change how an object is displayed in the admin UI for a user with only "view" permission on the "detail page", what do I do? P.S. When I say "detail page" I mean the page rendered when you click on the object in the list view. The URL ends in "change", but nothing can be changed for a user without change permission. EDIT: Maybe change_form_template? EDIT 2: A related way to ask this might be: how are read-only fields shown on the change form, and how do I customize a read-only field display? I think if you don't have "change" permission, it's rendering the fields as read-only. EDIT 3: This answer says you can't customize read-only fields. So maybe this is not possible? -
Django static don't read bootstrap javascripts file
When I import bootstrap css and js to django as static, css file connected and works, but js file show me error: "GET /static/bootstrap/js/bootstrap.min.js HTTP/1.1" 404 179. My 'main.html' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> {% load static %} <!-- Bootstrap --> <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}" /> <!-- DataTables --> <!-- Bootstrap JS --> <script src="{% static 'bootstrap/js/bootstrap.min.js' %}" /> <!-- DataTables JS--> <!-- DataTable Scripts --> </head> <body> {% include 'navbar.html' %} <main> <div class="container"> {% if messages %} {% for message in messages %} <div class="alert alert-{{message.tags}}">{{message}}</div> {% endfor %} {% endif %} {% block context %} {% endblock context %} <footer class="footer"> <div class="container"> <p>© Copyright {% now "Y" %} by <a href=""></a></p> </div> </footer> </div> </main> </body> </html> My 'setting.py' STATIC_URL = "static/" STATICFILES_DIRS = [ BASE_DIR / "static", ] My project folder structure: I need import css and js files as static, but django don't see js files, I don't understand what I'm doing wrong. -
How to redirect django to Google directly with Allauth
I don't have a code problem but a little aesthetic, I'm trying to make a simple login to an app with Django and be able to enter with Google and when I put the label to enter I would like it to direct the user directly to Google as it usually is, but the label sends them to an intermediate Allaut interface and then press another button and go, I would like to skip that interface but I've tried and it always directs me there Urls of proyect: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include("allauth.urls")), path('', include("pagina.urls")) ] Urls of app: from django.urls import path from . import views urlpatterns = [ path("", views.home), path("logout", views.logout_view) ] And the button's code: {% load socialaccount %} <h1>Google Login</h1> <a href="{% provider_login_url 'google' %}?next=/">Login with Google</a> -
Very slow queries in Django view for model with a lot of nested relationships
We have a dynamic endpoint that has a huge amount of nested aggregation before fetching all of the records. We've tried indexing the keys, but it didn't seem to make a difference on the speed. We looked at a few different methods of caching things, but because of the scale of the data, it's changing very frequently at a low level. Are there any other options or suggestions that we can try to do to optimize the aggregation of the records? For reference, we have a Job model with a bunch of data about that job. There are a few 1-to-many relationships between Job and some other models such as JobTask. There is also some data we need that has a 1-to-many relationship with JobTask. This means that there is a lot of essentially nested data we need for each job. As the database has grown, this query is getting noticeably slower for the users and we are trying to see if there is anything we can do to optimize it. We tried using the Prefetch() class in all of these prefetch_related() calls but that wasn't any help. Below are the views for the job and job list, which is … -
Considerations when replacing a Mixin with abstract Model subclass?
I have multiple Models that all need some shared functionality. My existing code uses a Mixin class: class MyMixing: some_class_variable = None @classmethod def get_headers(cls): return [field.name for field in cls._meta.fields] # ... and my models look like: class Something(models.Model): name = models.CharField(max_length=50) The above code shows an example, where my IDE shows error, because MyMixin doesn't have _meta. And there are multiple such issues, especially as I'm trying to add some more common functionality So I'm thinking it might be better to replace MyMixin with MyModel: class MyModel(models.Model): class Meta: abstract = True some_class_variable = None @classmethod def get_headers(cls): return [field.name for field in cls._meta.fields] then my models will look like: class Something(MyModel): name = models.CharField(max_length=50) Could this mess up my existing data? Other than database (and, of course, silly typos), is there anything else that might go wrong with that change?