Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sending email from same domain, but non existent user name with google SMTP
I want to be able to send an email from a random user address, that uses my domain. So for example: random1234akdh@mydomain.com. I'm using google as my email provider, and from what i can tell when using smtp it requires authentication for an existing account. Is there any way to create this spoof email temporarily? -
How to run Celery tasks on model creation in Django
In Laravel, we have an Observer pattern which observes events on create and on update of the given model, having some dirty fields on it. It allows to run jobs asynchronously on some events in the database table. In Django, how would we use the combination of django and celery to achieve the same goal? For example, I want to change the table row after it was created asynchronously. -
Django , get following list and followers list of a particular user
Created a UserProfile model with a through M2M field. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default=None , null= True) relationships = models.ManyToManyField('self', through='Relationship', symmetrical=False, ) In the through model, is the Relationship table which has the foreign keys of UserProfile who are related to each other on a follower, following relationship. class Relationship(models.Model): from_person = models.ForeignKey(UserProfile,on_delete=models.CASCADE,related_name='from_people') to_person = models.ForeignKey(UserProfile,on_delete=models.CASCADE,related_name='to_people') so basically, if UserA wanted to create a relationship between himself and another userB, it'll be a simple addition like; Relationship.objects.get_or_create( from_person=UserA, to_person= UserB) There are two foreign keys in the relationship model relating to each other. Now when I have a UserProfile instance, which query is appropriate to determine the users UserProfile is following? I am guessing I have to use filter() and include an argument to determine from_person = selfor something similar but can't seem to wrap my head around it. Below are methods under UserProfile #Get relationships def get_relationships(self): return self.relationships.all() #Get followers def get_related_to(self): return self.related_to.all() -
Dynamic dictionary keys in DJango table
I am absolutely new to Django need help. I have a dynamic list of dictionaries which I want to display in django table. [{'index': 'Price', 'Price': 1.0}, {'index': 'Sale', 'Price': 1.0}, {'index': 'Reviews', 'Price': -1.0}] "index" key will remain constant but second key is dynamic. I want to show this data in a table. I can show the value of first key but cant figure out how to show the value of dynamic key. My django template code is as below <div class="container fluid"> <table class="table table-striped"> <h2 class="text-center">Correlation with {{var}}</u></h2><br> <thead> <tr> <th>Index</th> <th>Score</th> </tr> {% for var in variable %} <tr> <td>{{var.index}}</td> <td>{{var.{{input}}</td> </tr> {% endfor %} </thead> </tbable> </div> Views.py def corelation(request): if request.method == "POST": var_input = request.POST.get('variable') data = {'Price':[23, 65], 'Sale':[76, 82], 'Reviews':[52, 34]} df = pd.dataframe(data) corr = df.corr() var_corr = corr[var_input].sort_values(ascending = False) #this is for showing item wise correlation() fucntion json_varCorr = var_corr.reset_index().to_json(orient ='records') data_varCorr = [] data_varCorr = json.loads(json_varCorr) context = {'variable': data_varCorr, 'input':var_input, } return render(request, 'variable.html', context) -
Is offline Django app is a good alternation for desktop app?
The task: Build an offline app to store and manage internal documents. The app has a features to sync between machines. My question: Should I go for an offline django app or a desktop app? Since, the stored documents needs to be in high level of privacy. Thank you! -
Getting logged out after logging in
I'm currently developing a Django web app, however I have an issue: After login, the user clicks on any button eg. Home (which has been linked to views with the @login_required decorator) and gets logged out and redirected back to the login page. I'm using Firebase for the authentication. My views.py: def postsign(request): email=request.POST.get('email') passw=request.POST.get('pass') try: user=auth.sign_in_with_email_and_password(email,passw) except: message="Invalid credentials. Try again." return render(request,"login.html", {"msg":message}) session_id=user['idToken'] request.session['uid']=str(session_id) return render(request,"pick.html") @login_required(login_url='login') def pick(request): return render_to_response('pick.html') My pick.html: {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>FYP - Is Your Network Safe?</title> <!-- Bootstrap core CSS --> <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'vendor/bootstrap/css/loader.css' %}" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="{% static 'vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Varela+Round" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template --> <link href="{% static 'css/grayscale.min.css' %}" rel="stylesheet"> <script src="https://api.mapbox.com/mapbox-gl-js/v1.11.1/mapbox-gl.js"></script> <link href="https://api.mapbox.com/mapbox-gl-js/v1.11.1/mapbox-gl.css" rel="stylesheet" /> </head> <body id="page-top"> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav"> <div class="container"> <a class="navbar-brand js-scroll-trigger" href="#page-top">TestPage</a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> Menu <i class="fas fa-bars"></i> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li … -
Post method not allowed on Django Rest Framework
I'm working on a small project using Django Rest Framework and VueJS, i have a small bug after sending my POST request i get 405 POST Method Not Allowed, i don't know why since my request url is /contact/create/ This is my code : class ContactView(viewsets.ViewSet): def create(self, request): serializeObject = ContactSerializer(data = request.data) if serializeObject.is_valid(): serializeObject.save() contactObject = Contact.objects.all() contactSerializer = ContactSerializer(contactObject, many=True) return Response(contactSerializer.data, status = status.HTTP_201_CREATED) return Response(serializeObject.errors, status.HTTP_400_BAD_REQUEST) -
How to convert blob url into mp3 audio in django
So I'm working with recording audio from browser for which it is using Mic recorder API, now this Api after recording returns a blob url which I send to my project's django backend but the problem is how to get that audio file back from blob url at backend? For your reference this is how it generate blob url: const Mp3Recorder = new MicRecorder({ bitRate: 128 }); stop = () => { Mp3Recorder.stop() .getMp3() .then(([buffer, blob]) => { const blobURL = URL.createObjectURL(blob); console.log(blobURL); this.setState({ blobURL, isRecording: false }); this.sendAudioFile(blobURL); }) .catch((e) => console.log(e)); }; and this is code for sending blob url to django backend sendAudioFile = (url) => { let data = new FormData(); data.append("file", url); return axios .post("http://localhost:8000/recordings/", data, { headers: { "Content-Type": "multipart/form-data", }, }) .then((res) => { console.log(res); return res; }); Pls suggest a good solution as I've already gone through various stackoverflow answers for similar questions but the problem is not getting solved. -
Gunicorn not starting on AWS EB instance?
I am deploying a Django project onto an AWS EB instance. It runs perfectly locally. When I deploy through the CLI, it generates a Procfile that contains the command to start the gunicorn server. However, it is not getting started. I can SSH into the instance, run "python manage.py runserver" or run the line from the Procfile to start gunicorn, both start the server and get things working great. However, this should happen when the project is deployed, and it is not. I do not get any errors when making migrations, running the server, or manually starting gunicorn. So why is it not starting automatically? After deploying and going to the site, it gives a 502 error. -
Setting a cookie with samesite none on Django 2.2
I am trying to set a specific cookie to have samesite='None' for a Django project on version 2.2.x. I continue to get the below error. raise ValueError('samesite must be "lax" or "strict".') which I can see is coming from venv/lib/python3.9/site-packages/django/http/response.py if samesite: if samesite.lower() not in ('lax', 'strict'): raise ValueError('samesite must be "lax" or "strict".') self.cookies[key]['samesite'] = samesite I have tried to following: Set this globally in settings eg CSRF_COOKIE_SAMESITE = 'None', SESSION_COOKIE_SAMESITE = 'None' Setting this on the cookie that need it via set_cookie(name, value=value, secure=True, samesite='None') Both approaches don't work. I have also tried to installed the package django-cookies-samesite and adding its middleware, however it doesn't seem to make a difference. # example MIDDLEWARE = ( "django_cookies_samesite.middleware.CookiesSameSite", # other middleware ) When I set the value to None instead of 'None' no value is added and I believe Chrome falls back to lax when there isn't a value there. Is there a way around this? I can see the newer versions of Django support this however doing that upgrade for this project isn't possible at the moment. -
How to make views method accept images from form in Django?
I am trying to create objects in the database and store images user uploaded to the form. This form creates a items with an image and saves. My question is how to write the method so that it knows how to handle the image that was uploaded? This is just for development so I am not hosting to AWS but simply storing Images locally. Note: I am also creating my form the old fashion way and not creating a form.py file. >This is the error im getting: MultiValueDictKeyError at /createWish 'photos' => image = request.POST['photos'],>[enter image description here][1] **Views.py** def createItem(request): print(request.POST) validationErrors = Item.objects.validateItem(request.POST) if len(validationErrors) > 0: for key,value in validationErrors.items(): message.error(request, value) return redirect('wishes/add') loggedInUser = User.objects.get(id = request.session['loggedInID']) newItem = Item.objects.create( name = request.POST['itemName'], uploader = loggedInUser, image = request.POST['photos'], description = request.POST['desc'] ) return redirect('/home') **addItem.html** <form class="col-lg-8 offset-lg-2 " action="/createWish" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="row justify-content-center"> <input class="form-control form-control-lg mb-5" type="text" name="itemName" placeholder="Add Items here..."> <input class="form-control form-control-lg mb-5" type="text" name="desc" placeholder="Add short description here..."> <input type="file" class="form-control-file mb-5" name="photos" id="exampleFormControlFile1"> <span class="input-group-btn mb-5"> <button class="btn btn-primary">Add Item</button> </span> </div> </form> -
django-rest-framework-simplejwt override CustomTokenObtainPairView add get() endpoint
I've modified the CustomTokenObtainPairView class to make use of external authorization (via an Oauth provider). Now, the login endpoint which I overrided to this: re_path(r'^api/oauth/$', views.user_views.token_obtain_pair, name='api-oauth'), works as intended when the request is a POST. The problem is the oauth provider sends a request to this endpoint but it's a GET. I need to make this view accept GET requests and do what it would normally do in a POST. I can't seem to find a way to do it. I've added a get method as this: class CustomTokenObtainPairView(TokenObtainPairView): serializer_class = CustomTokenObtainPairSerializer def get_serializer_class(self): return CustomTokenObtainPairSerializer def get(self, request, *args, **kwargs): return self.post(request, *args, **kwargs) but I still get a 405 Method Not Allowed error. How can I modify my view so that it also accepts get requests? -
django concatenate filter model
why this is not working? I can't concatenate the filter with another variable? I have a feeling that I'm being very dumb. I'm new at django and trying a couple of things with the model. When I use: birthdate__contains='-03-' works fine, but with the variable, nothing shows up at the url from django.shortcuts import render from .models import Employee from datetime import datetime # Create your views here. def index(request): currentMonth = datetime.now().month mes_atual = '-'+str(currentMonth)+'-' employees = Employee.objects.filter( birthdate__contains=mes_atual ) context = { 'employees' : employees } return render(request, 'index.html', context) thanks in advance -
Django m2m field custom queryset removing used options
I hope you can help me, I'm making an school app which have students, teachers, courses and groups that belong to a course. A course can have many groups with different students, no student can repeat on each group of the same course. To store students in group I use m2m field, but what I want is to show on m2m field queryset only the students that are active but not subscribed to the course, I achieved how to load that queryset but the problem is that even if I only select one student, all the students in the m2m field are related to the group instead of only the selected ones. I hope you can help me with that, let me show you what I'm doing: class Course(models.Model): name = models.CharField(verbose_name=_('Name'), max_length=100, blank=True, null=True) def get_all_groups(self): if self.usergroup_set.all(): return self.usergroup_set.all() return None def get_all_student_in_course(self): # Get all students in the course of each group students = None if self.get_all_groups(): for group in self.get_all_groups(): if students: students = students | group.get_students() # Combine all querysets in one else: students = group.get_students() # Setting initial queryset to combine return students def get_all_available_students(self): # Get all active students that are not taking … -
Django channels messaging app: Message not sending to websocket
I have completed this youtube tutorial (github link to code) on how to use channels and redis in Django(v. 3.1.7) to make an instant chat app. I did change a couple things from the tutorial, because he is on a different Django version. The error I get when I use his code is explained in this other stackoverflow post. I have messages saving to the database and I am successfully loading the 10 most recent messages on page load. But When I click the "send" button, I do not see the message show up in the list of messages (but it does save to the database). When I run redis-cli and type 'ping', I get 'PONG' in return so I think redis is working properly. When I click send, there are no javascript errors in the dev console and no python errors. It just does not show for me (or for a different logged in user who is in the same room). views.py: from django.shortcuts import render import json from django.contrib.auth.decorators import login_required from django.utils.safestring import mark_safe def index(request): return render(request, 'chat/index.html') @login_required def room(request, room_name): # OLD: WORKING (Mar 22, 6pm) return render(request, 'chat/room.html', { 'room_name': room_name }) routing.py: … -
Serializing the permissions objects of Permission Class in Django
I am writing a REST API to create Group and assign permissions to that group, for that I used GET method to get all the permissions available within using: permissions = Permission.objects.all() Now how do I serialize the list of objects in permissions so that I can get list of permissions in json and use it in frontend to assign the permissions while creating a group. Here is Snippet of code so far i have came Groupserializer class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('name','permissions') Views class UsersGroupCreateView(APIView): permission_classes = [IsAdminUser] def post(self , request , *args, **kwargs): serializer = GroupSerializer(data = request.data) if serializer.is_valid(): data = serializer.validated_data group = Group.objects.create(name = data.get('name')) return Response({"status":"Group Created"},status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST class GetPerm(APIView): def get(self, request, *args, **kwargs): data = Permission.objects.all() permissions = PermissionSerializer(data = request.data) return Response({"list":"I WANT LIST OF PERMISSIONS"}) Any help would be appreciated !! -
Why is my app getting stuck on navigation
I have a route in my Angular app that is /service-categories. Here's the ngOnInit to the component that is loaded on that route: ngOnInit() { this.apiDataService.readData(env.routes.services.getServiceCategories, false, 'get').subscribe(response => { this.serviceCategories = response.data.map(serviceCategory => new ServiceCategory(serviceCategory)); }); } Here's the API view in Django REST Framework that gets those service categories: @api_view(['GET']) def service_categories(request): try: serviceCategories = ServiceCategory.objects.all() serializer = ServiceCategorySerializer(serviceCategories, many=True) return generic_data_response(serializer.data) except: return generic_internal_server_error_response() Everything works fine until I log in using Facebook. The route is /login and here is the code that handles that: this.socialAuthService.authState.pipe( switchMap((user: SocialUser) => { if (user && user.authToken) { this.socialUser = user; return this.authService.convertToken(user.provider.toLowerCase(), user.authToken) } else { return throwError(new Error('An unexpected error occurred.')); } }) ).subscribe((res) => { if (res.status === 200) { localStorage.setItem('__bn_api_current_user', JSON.stringify(this.socialUser)); localStorage.setItem('__bn_api_access', res.body.access_token); localStorage.setItem('__bn_api_refresh', res.body.refresh_token); this.router.navigate(['service-categories']); } }); localStorage is updated just fine but, upon navigating to service-categories, the application hangs. I can see the call to the API to get the service categories, and it goes into a pending state and just waits and waits until the app crashes. -
Django many to many autofilling user
I want to keep track of users that are associated with each team, but as soon as this code is executed every user in my database is added to my model. How do I avoid this? I have tried doing add() and remove() but none of them change the fact that every single user is stored in the database as soon as it loads. Thanks class Team(models.Model): name = models.CharField(max_length=120) abbreviation = models.CharField(max_length=3) id = models.IntegerField(primary_key=True) link = models.CharField(max_length=120) wins = models.IntegerField(default=0) losses = models.IntegerField(default=0) ties = models.IntegerField(default=0) points = models.IntegerField(default=0) users = models.ManyToManyField(User) def getTeams(): import requests baseUrl = "https://statsapi.web.nhl.com/" # INITALIZING THE DATA IN THE DATA DICTIONARY r = requests.get(baseUrl + '/api/v1/teams') originalData = r.json() # i dont need the copyright, only care about the teams originalData = originalData["teams"] for team in originalData: id = team["id"] try: databaseTeam = Team.objects.get(id = id) except Exception: Team.objects.create(id = id) databaseTeam = Team.objects.get(id = id) databaseTeam.name = team["name"] databaseTeam.abbreviation = team["abbreviation"] databaseTeam.link = team["link"] databaseTeam.save() print("done") @login_required def myTeamView(request): t1 = Thread(target=getTeams) t1.start() return(render(request, "teams/myTeams.html", {})) -
kindly demonstrate about nginx server
Is it possible to nginx server login through putty software then use vim editor directly update the backend source file? nor it have to download all file and edit them then again deploy on nginx server. it is for python language -
Django open user-inputed url links on another tab
I am trying to open the new URL link that is inputted by user via another tab. For example, in a post format, user can create a post with a link in it. Django automatically detects that it is a link and then I would like the users to be directed to a new tab. This is the html code: <div class="post-list-preview">{{ post.text|linebreaksbr|urlize }} </div> Because there is no tab, I cant use _target='blank' -
Deploy DRF API with VueJS frontend project
I'm trying to figure out how to deploy Django project (DRF API) with VueJS project. /django_project/ /django_project/django_project/settings.py # +other stuff /django_project/frontend/ # the VueJS project /django_project/frontend/dist/ # the directory created by `npm run build` I want to deploy it on DigitalOcean apps so it needs to act (probably) as a Django project because there is no space for setting up another server. The goal is an ability to deploy project after every git push. I was thinking about adding one (and only except API views) view that serves index.html file from VueJS project but I'm not sure how to make it work "automatically" so the app server will just do collectstatic to make everything work properly (eg. both VueJS frontend project and Django backend project). -
Chartjs + moment() not displaying on django
i've tried this code one this online js : https://jsfiddle.net/prfd1m8q/ and it's working perfectly but when i paste it on my index.html on Django like this: <div class="btcprices-chart" id="btcprices"> <canvas id="myChart3"></canvas> <script> function newDate(days) { return moment().add(days, 'd'); } var config = { type: 'line', data: { labels: [newDate(-4), newDate(-3), newDate(-2), newDate(-1), newDate(0)], datasets: [{ label: "My First dataset", data: [10, 11, 12, 13, 14], }] }, options: { scales: { xAxes: [{ type: 'time', time: { displayFormats: { 'millisecond': 'MMM DD', 'second': 'MMM DD', 'minute': 'MMM DD', 'hour': 'MMM DD', 'day': 'MMM DD', 'week': 'MMM DD', 'month': 'MMM DD', 'quarter': 'MMM DD', 'year': 'MMM DD', } } }], }, } }; var ctx = document.getElementById("myChart3").getContext("2d"); new Chart(ctx, config); </script> i get nothing that's displaying (take note that i use chartjs with other values and it's working but whn i tried this method "just to display the date" it's not working) Any idea why ? -
Django and S3 Bucket aws Admin Static files
I have a django project, i wanted to configure S3 Bucket in order to store the static files. Once create, the site loads but there files are not retrieved from the bucket so there is no CSS even for the admin page as in the screen shot : Here is the settings used for the bucket configurations : STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') AWS_ACCESS_KEY_ID = '************' AWS_SECRET_ACCESS_KEY = '********************' AWS_STORAGE_BUCKET_NAME = 'BUCKET_NAME' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' offcourse i added (storages) to the installed apps. The bucket policy (CORS) is set to : [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "PUT", "POST", "DELETE" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [ "x-amz-server-side-encryption", "x-amz-request-id", "x-amz-id-2" ], "MaxAgeSeconds": 3000 I tried also (py manage.py collectstatic) without uploading manually, an admin folder appears in the bucket, but still even after using "Collectstatic" i still have the same problem (no css, no images, ...) I'm running in circles and can't find a solution, i'd very much appreciate if someone could help. Thank you in advance -
Why are Django and Vue not agreeing on CORS policies?
VueJS + NuxtJS on the front, Django on the back. Installed django-cors-headers and it seems to be replying with the CORS headers only when the Origin header is set on the request, which Vue is not setting for some reason (or it should be the browser). # http GET http://localhost:8000/issuers/ Origin:http://localhost:3000 HTTP/1.1 200 OK Access-Control-Allow-Credentials: true Content-Length: 107 Content-Type: application/json ... However: # http GET http://localhost:8000/issuers/ HTTP/1.1 200 OK Content-Length: 107 Content-Type: application/json ... Ideas? Thanks in advance. -
Como posso filtrar uma lista de objetos "votos" pela fk da lista de "alternativas" em minha view e os enviar como contexto?
Eu gostaria de fazer uma view que mostrasse o texto da enquete, listasse as alternativas da enquete (essas partes estão ok) e exibir a quantidade de votos de cada uma dessas alternativas. É possível fazer isso apenas na view? Obs.: Consegui fazer utilizando uma templatetag, mas com a mesma não consigo filtrar o resultado da votação por determinado período que minha próxima etapa. Agradeço se alguém puder me ajudar. #Meus Models class Enquente(models.Model): enquete_texto = models.TextField(max_length=500) def __str__(self): return self.enquete_texto class Alternativa(models.Model): enquete = models.ForeignKey(Enquente, on_delete=models.CASCADE) nome_alternativa = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return self.nome_alternativa class Voto(models.Model): alternativa = models.ForeignKey(Alternativa, on_delete=models.CASCADE) quant_votos = models.IntegerField(default=0, null=True, blank=True) data_voto = models.DateField(auto_now=True) def __str__(self): return str(self.quant_votos) # Minha View def resultado_enquete(request, id): enquete = Enquente.objects.get(pk=id) alternativas = Alternativa.objects.filter(enquete_id=enquete.id) votos = Votos.objects.filter(alternativas) #Só pra exemplificar total_votos = sum(votos.values_list('quant_votos', flat=True)) context = { 'enquete': enquete, 'alternativas': alternativas, 'total_votos': total_votos } return render(request, 'resultado_enquete.html', context) # Meu template de forma resumida {{ enquete.enquete_texto }} {% for alternativa in alternativas %} <p>{{ alternativa.nome_alternativa }} - Votos: {{ total_votos }}</p> {% endfor %}