Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to login to django auth account via the ContextTitleMixin
class SurveyListView(ContextTitleMixin, ListView): model = Survey title_page = 'Survey List' paginate_by = app_settings.SURVEY_PAGINATION_NUMBER['survey_list'] paginator_class = NewPaginator def get_queryset(self): user = authenticate(username='guest', password='guest11') self.request.user = user query = self.request.GET.get('q') if query: object_list = self.model.objects.filter(name__icontains=query) else: object_list = self.model.objects.all() return object_list def get_context_data(self, **kwargs): page_number = self.request.GET.get('page', 1) context = super().get_context_data(**kwargs) page_range = context['page_obj'].paginator.get_elided_page_range(number=page_number) context['page_range'] = page_range return context -
How can I optimize response time in this python code? (django)
The get_assets method obtains a list of assets from the database and for each item in the list calls the __build_asset_response method to build a response in dictionary format. However, when there are many assets, the time to do the build_asset_response is very high. Does anyone know a method to optimize the time? def get_assets(user, data): if data.get('asset_id'): assets = Asset.objects.filter(pk__in=data['asset_id']) return [__build_asset_response(asset) for asset in assets] assets = Asset.objects.filter(QueryHelper.filter_by_rol(user)) return [__build_asset_response(asset) for asset in assets] This is the buil_asset_response private method: def __build_asset_response(asset): asset_dict = { 'id': asset.pk, 'name': asset.name, 'accessibility': manage_accessibility.build_accessibility_type_response(asset.accessibility), 'folder': "", 'user_id': { 'id': asset.user.id, 'name': str(asset.user) }, 'organization': { 'id': asset.idOrganization.id, 'name': str(asset.idOrganization), }, 'asset_type_id': asset.idAssetType and __build_asset_type_response(asset.idAssetType) or {}, 'file': settings.MEDIA_URL + asset.archivo.name, 'tag_ids': [tag.name for tag in asset.tag_ids.all()], 'lastModified': timezone.localtime(asset.last_modified_date).strftime("%Y-%m-%d %H:%M:%S"), 'used_in_publication': asset.used_in_publication } if asset.idFolder: folder = manage_folder.build_folder_response(asset.idFolder) else: folder = '' asset_dict.update({ 'folder': folder, }) return asset_dict -
How can I get data to pop up using django
please how can I get attribut id_benevole Class Participer(Models) i need to show it in the pop up i use this method but nothing is displayed Thanks in advance This is -------->Models.py class Participer(models.Model): id_benevole = models.CharField(max_length=150,null=False,blank=False) id_mission = models.CharField(max_length=150,null=False,blank=False) participer = models.ForeignKey(Mission, on_delete=models.CASCADE,null=True,blank=True) # def __str__(self): def __str__(self): return self.id_mission This is ------->Views.py def getLB(request): participerss=Participer.objects.all() context={ 'participerss':participerss } print(participerss) return render(request, 'home/Association.html',context) This is ----------> Association.html {% for miss in missions %} <th scope="row">{{miss.id}}</th> <td>{{miss.nom}}</td> <td>{{miss.domaine}}</td> <td>{{miss.lieu}}</td> <td style="white-space: nowrap;width: 1%;" >{{miss.date_publier}}</td> <td style="text-align: center;">{{miss.nombre_participant}}</td> <td>{{miss.association.association.nom_association}}</td> <td><a type="button" class="btn btn-danger mt-5" data-bs-toggle="modal" data-bs-target="#myModal" class="col-11 text-center mt-3">Voir liste des bénévoles</a></td> <div class="modal mt-5" id="myModal" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="d-flex justify-content-center text-danger"> <h4>Liste des bénévoles participants</h4> </div> {% for par in participerss %} <div class="modal-header"> {{par.id_mission}} {{par.id_benevole}} </div> {% endfor %} <div class="modal-footer"> <div class="col-11 text-center mt-3"> <input class="btn gradient-bg" type="submit" value="Confirmer"/> <input type="button" class="btn gradient-bg" data-bs-dismiss="modal" value="Annuler"/> </div> <div> </div> </div> </div> {% endfor %} -
Detected path traversal attempt - Django/Heroku(Bucketeer)
I'm getting this error when trying to upload using FileField. I'm using Bucketeer on Heroku to upload to an AWS bucket. I've seen a few threads on this issue but haven't been able to figure it out. The file upload view: class UploadTicketAttachment(APIView): permission_classes = [] parser_classes = (MultiPartParser, FormParser) def post(self, request, format=None): user = request.user serializer = AttachmentSerialiazer(data=request.data) if serializer.is_valid(raise_exception=True): serializer.validated_data['uploaded_by'] = user serializer.save() return Response(serializer.data['id']) else: return Response(f'{serializer.errors}, attachment upload failed') The model: class Attachment(models.Model): file = models.FileField(upload_to="/ticket_attachments", blank=True, null=True) created_on = models.CharField(max_length=20, null=True) uploaded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, related_name="uploaded_by") parent_ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE, null=True, related_name="attachment") def __str__(self): return self.file.name For the settings/bucketeer configuration I followed which uses django-storages: https://dev.to/heroku/properly-managing-django-media-static-files-on-heroku-o2l I don't think the issue is on that end since I set it up the exact same way in another project and it works fine with the only difference being that the other project uses ImageField instead of FileField. Django version is 4.0.2. Any ideas? Thanks -
My own backend sends two Objects instead of one in http response?
I got a backend in django wich is supposed to send me data, but instead of one object I get two objects (inside of the http response). The weird thing about that, is that it does not happen all the time, sometimes its just one and sometimes there are two... This is how the response looks like (In the network analytics): { "id": 1, "sumScore": 270, "sumRequests": 55, "buttonOne": 55, "buttonTwo": 10, "buttonThree": 10, "buttonFour": 10, "buttonFive": 55, "buttonSix": 55, "buttonSeven": 55, "buttonEight": 10, "buttonNine": 10, "myResult": 4 }{ 'REDIRECT_REDIRECT_UNIQUE_ID': 'YxTgq5gPaMxcbxlxyS6l0QAAAAM', 'REDIRECT_REDIRECT_DOCUMENT_ROOT': '/kunden/homepages/29/d920390454/htdocs/MyWebsite', 'REDIRECT_REDIRECT_UI_SUEXEC_DEFAULT_CHROOT_ID': '14', 'REDIRECT_REDIRECT_UI_SUEXEC_FSTATD_UNIXSOCKET': '/run/ui-fstatd.suexec.socket', 'REDIRECT_REDIRECT_UI_SUEXEC_STATISTICS_UNIXSOCKET': '/homepages/sclientMF/http.sock.bin', 'REDIRECT_REDIRECT_HTTPS': 'on', 'REDIRECT_REDIRECT_DBENTRY__RSCLVL_CPU': '40', 'REDIRECT_REDIRECT_DBENTRY__RSCLVL_MEM': '768', 'REDIRECT_REDIRECT_DBENTRY__RSCLVL_PROCSOFT': '15', 'REDIRECT_REDIRECT_DBENTRY__RSCLVL_PROCHARD': '27', 'REDIRECT_REDIRECT_DBENTRY__RSCLVL_JIMDO': '800', 'REDIRECT_REDIRECT_DBENTRY__RSCLVL_CPU_JIMDO': '60', 'REDIRECT_REDIRECT_DBENTRY__RSCLVL_MEM_JIMDO': '768', 'REDIRECT_REDIRECT_DBENTRY__RSCLVL_PROCSOFT_JIMDO': '24', 'REDIRECT_REDIRECT_DBENTRY__RSCLVL_PROCHARD_JIMDO': '24', 'REDIRECT_REDIRECT_DBENTRY_HOST': 'api.tor-netzwerk-seminarfach2024.com', 'REDIRECT_REDIRECT_DBENTRY_VALUE': '/kunden/homepages/29/d920390454/htdocs/MyWebsite:d0000#CPU 6 #MEM 10240 #CGI 524360 #NPROC 12 #TAID 109180236 #LANG 0 #RSCLVL 300 #CHROOT 15', 'REDIRECT_REDIRECT_DBENTRY_DOCROOT': '/kunden/homepages/29/d920390454/htdocs/MyWebsite', 'REDIRECT_REDIRECT_DBENTRY_HASH': 'd0000', 'REDIRECT_REDIRECT_DBENTRY__CPU': '6', 'REDIRECT_REDIRECT_DBENTRY__MEM': '10240', 'REDIRECT_REDIRECT_DBENTRY__CGI': '524360', 'REDIRECT_REDIRECT_DBENTRY__NPROC': '12', 'REDIRECT_REDIRECT_DBENTRY__TAID': '109180236', 'REDIRECT_REDIRECT_DBENTRY__LANG': '0', 'REDIRECT_REDIRECT_DBENTRY__RSCLVL': '300', 'REDIRECT_REDIRECT_DBENTRY__CHROOT': '15', 'REDIRECT_REDIRECT_DBENTRY': '/kunden/homepages/29/d920390454/htdocs/MyWebsite:d0000#CPU 6 #MEM 10240 #CGI 524360 #NPROC 12 #TAID 109180236 #LANG 0 #RSCLVL 300 #CHROOT 15', 'REDIRECT_REDIRECT_STATUS': '200', 'REDIRECT_UNIQUE_ID': 'YxTgq5gPaMxcbxlxyS6l0QAAAAM', 'REDIRECT_DOCUMENT_ROOT': '/kunden/homepages/29/d920390454/htdocs/MyWebsite', 'REDIRECT_HTTPS': 'on', 'REDIRECT_STATUS': '200', 'UNIQUE_ID': 'YxTgq5gPaMxcbxlxyS6l0QAAAAM', 'HTTPS': 'on', 'HTTP_HOST': 'api.tor-netzwerk-seminarfach2024.com', 'CONTENT_LENGTH': '48', 'HTTP_SEC_CH_UA': '" Not A;Brand";v="99", "Chromium";v="104", "Opera";v="90"', 'HTTP_SEC_CH_UA_MOBILE': … -
How to change membership status from active to expired after subscription end date in django
After the expiry date i would like to change the subscription status to inactive. So what is the best way to achieve this. My Subscription models as follows: class Subscription(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) membership = models.ForeignKey(Membership, on_delete=models.SET_NULL, null=True) start_date = models.DateTimeField(_('Start Date'), null=True, blank=True) expiry_date = models.DateTimeField(_('Expiry Date'), null=True, blank=True) token = models.TextField(_('Token'), max_length=100, null=True, blank=True) active = models.BooleanField(_('Active'), default=False) Thanks! -
Django: Form submit button not loading blog post {{ post.slug }} value in second form
My Django template renders the post.slug value in the first 'edit' form button correctly but on the modal pop up for the 'delete' it does not. This was working a week or so ago. The 'Edit' button works perfectly, yet with almost identical code, under a Bootstrap modal (for confirmation of the post deletion) the 'Delete' button does not load the value="{{ post.slug }}" my template: {% extends "base.html" %} {% block content %} <div class="post-opinion"> <h3>{{ user }}'s Posts</h3> </div> <div class="container-fluid"> <div class="row"> <!-- Blog Entries Column --> <div class="col-12 mt-3 left"> <div class="row"> {% for post in post_list %} <div class="col-md-4"> <div class="card mb-4"> <div class="card-body"> <div class="image-container"> {% if "placeholder" in post.featured_image.url %} <img class="card-img-top" src="https://codeinstitute.s3.amazonaws.com/fullstack/blog/default.jpg"> {% else %} <img class="card-img-top" src=" {{ post.featured_image.url }}"> {% endif %} <div class="image-flash"> <p class="author">Author: {{ post.author }}</p> </div> </div> <a href="{% url 'post_detail' post.slug %}" class="post-link"> <h2 class="card-title">{{ post.title }}</h2> <p class="card-text">{{ post.excerpt }}</p> </a> <hr /> <p class="card-text text-muted h6">{{ post.created_on}} <i class="far fa-heart"></i> {{ post.number_of_likes }}</p> <div> <form method="post"> {% csrf_token %} <button type="submit" class="btn btn-primary mt-3" value="{{ post.slug }}" name="edit">Edit</button> <button type="button" class="btn btn-danger mt-3" data-toggle="modal" data-target="#delete-confirmation"> Delete </button> </form> </div> </div> </div> </div> {% … -
How can I post data to my view function using AJAX and return html view using the data I send
at java script I have a function and inside the function I have this code. datam = {'username' : username , 'usernameId' : id} url = `http://127.0.0.1:8000/chat/dms/` datam=JSON.stringify(datam) $.ajax({ type: "POST", url: url, data: datam , headers: {'X-CSRFToken': csrftoken}, mode: 'same-origin', contentType: "application/json", cache:false, error: function(xhr, status, error) { console.log('!212') }, complete: function (response) { roomid=response.responseJSON.data console.log(roomid) window.location.href =`http://127.0.0.1:8000/chat/${roomid}/` console.log('completed') } }); and in the views I have this code def chat_room(request ,room_name): oda = room.objects.get(id= room_name) messages = message.objects.filter(room=oda) chat = room.objects.filter(id = room_name).first() print(chat) #return JsonResponse({'room_name' : room_name} ,status= 200) return render(request , 'chatroom.html' , {'a' : chat , 'messages' : messages}) But I cant render the html page ı wanted. Ajax gives error. How Can I render html page using the data That I send via AJAX. How can I post data to my view function using AJAX and return html view using the data I send -
How to add text into a link in src=" "
I have this src="https://open.spotify.com/embed/track/1Go9q6KaCpAsQ0wkZFGzY2?utm_source=generator" and I want it to be like this src="https://open.spotify.com/embed/track/{{ spotify_trackid }}?utm_source=generator" how can I do this using django without it breaking the link? sorry for the bad explanation i'm pretty new to this -
how to return result to html django
I want to make text file contains with b'Y\xf5\x11m' (it's result from encryption). And I want txt file can be downloaded using html. But I got next error when I return it: 'int' object has no attribute 'get' Here's the code: def create_file(f): with open("file.txt", 'w') as file: download = file.write(str(f)) print(download) return download I called that func like this: #in views download = create_file(enc) print(download) #in urls path("create_file", views.create_file, name="create_file"), #in html <a href="{% url 'create_file' %}"> -
django CK-Editor not working in production shared hosting
My Django application has a django-ckeditor which seemed to work fine in the local host but dosent work in the production enviornment . I have used proper static path settings cause all of my other static files are loading properly . but the ck-editor is not working fine . This is my settings.py file . STATIC_URL = '/static/' # Add these new lines STATIC_ROOT = "/home/username/public_html/static/" MEDIA_URL = '/media/' MEDIA_ROOT = "/home/username/public_html/media/" CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_BASEPATH = "/home/username/public_html/static/ckeditor/ckeditor/" CKEDITOR_UPLOAD_PATH = 'uploads/' This is my wsgi.py file import os from django.core.wsgi import get_wsgi_application from whitenoise import WhiteNoise os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hrnindia.settings') application = get_wsgi_application() application = WhiteNoise(application, root="/home/username/public_html/static/") application.add_files("/home/username/public_html/static/ckeditor/ckeditor/", prefix="more-ck-files/") application.add_files("/home/username/public_html/static/ckeditor/", prefix="more-files/") I have tried out all the other solutions like configuring the path and using whitenoise . But nothing seems to make the ck-editor work . -
Best practice for Python typing out of dictionary (self.fields type in Django ModelForm)
I have a form like this class MerchantBrandsForm(forms.Form): brands = forms.ModelChoiceField(required=True, queryset=None) def __init__(self: merchant: Merchant): self.fields['brands'].queryset = merchant.brands.all() But I have an error with mypy with the queryset as fields has a type Dict[str, Field], which cause error: "Field" has no attribute "queryset". I know I can cast the fields using cast or ignore the typing, but I don't think this is a clean solution. What is the best way to assign brands queryset without ignoring the type or using cast function? -
AttributeError: 'NoneType' object has no attribute 'is_superuser'
I'm working with Django, and I keep getting this error when trying to create a new superuser inside the terminal: AttributeError: 'NoneType' object has no attribute 'is_superuser' I've tried everything I've looked up to fix it. No luck. Also, this code is greyed-out inside my user model, and when I hover over the text it says: Code is unreachable Pylance if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) email = email.lower() user = self.model( email = email, name = name ) user.set_password(password) user.save(using=self._db) return user Here is my full user model: from abc import abstractmethod from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class UserAccountManager(BaseUserManager): @abstractmethod def create_user(self, email, name, password=None): if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) email = email.lower() user = self.model( email = email, name = name ) user.set_password(password) user.save(using=self._db) return user def create_realtor(self, email, name, password=None): user = self.create_user(email, name, password) user.is_realtor = True user.save(using=self._db) return user def create_superuser(self, email, name, password=None): user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) # … -
'utf-8' codec can't decode byte 0xa0 in position 0: invalid start byte django
so i have variable contains in bytes and i want to save it to str. but how to do it? i tried various kinds of ways, but always got error 'utf-8' codec can't decode byte 0xa0 in position 0: invalid start byte i want to save the result encrypt file to text file. so i have the proof it the file was encrypt. here;s my ways 1: def create_file(f): response = HttpResponse(content_type="text/plain") response['Content-Disposition'] = 'attachment; filename=file.txt' filename = f print(filename) name_byte = codecs.decode(filename) print(name_byte) return response my ways 2 : def create_file(enc): with open("file.txt", "w", encoding="utf-8") as f: enc = enc.decode('utf-8') f.write(enc) my ways 3: def create_file(f): file = open("file.txt", "w") f = f.decode('utf-8') download = file.write(f) file.close() print(download) return download f = b'\xa0\x0e\xdc\x14' f is the return result of encrypt -
Is it possible to return the display name of a choice in Django?
So when you make choices for a form/model you do this: EXP_CHOICES = ( ('1ST','First'), ('2ND','Second'), ....... ('XXX','YYY'), ) # where XXX is the value stored in the database and YYY is what you see in a form. This also applies to the queries, so when you have the mentioned choices and select one, do a query on the model and it returns '1ST'/'2ND'/'XXX'. But what if you want to display the YYY instead? So we know that '1ST' is 'First', but we want to make it user readable. Is there a way to access that EXP_CHOICES and write out the YYY tied to them, or you must make an if&else/selector to be like {% if data.chosen == '1ST'%} First {% elif ... %} ... {% endif %} -
Django annotate: sum all records by asset | only one table
My django model: class Movimentacao(models.Model): product = models.CharField(max_length=300) value = models.DecimalField(max_digits=19, decimal_places=2) I'm trying to SUM all value by product using django annotate. I tried: query = Movimentacao.objects.annotate(total=Sum('value') ).values('product', 'total' ).order_by('product') There are a lot of repeated products (multiple lines) with different values and I'd like to group all same products and sum their respective values. But it's showing all records without grouping and summing all of them. I wouldn't like to use aggregate in this case. Tks -
Access a json object form views django
i have tired a number of suggestions but need help. in my views.py def findnamesurname(request): username = request.POST['username'] obj = Users.objects.all().values("first_name") return HttpResponse(obj) in my json $.ajax({ url: "/findnamesurname", method: "POST", data: { 'csrfmiddlewaretoken': '{{csrf_token}}', "username": data, }, success: function (data) { alert(JSON.stringify(data)) } }) } I want to get first name please in a viable I get the following when i alert: {'first_name': 'Daniel'} How to access this object please. -
What type of database replication is used by Digital Ocean's read-only nodes?
I'm working on two Django projects that need to share a PostgreSQL database, a database which needs to be replicated for read-only operation. The reason is that one of the projects mostly performs write operations while the other performs read operations. To achieve this, I'm considering Digital Ocean's read-only nodes. The question that comes to my mind how long it takes to propagate a write operation in the primary sever to the read-only server located in the same datacenter, so that future read requests return consistent results. And, more importantly, is the replication synchronous or asynchronous ? Some solutions are synchronous, meaning that a data-modifying transaction is not considered committed until all servers have committed the transaction. This guarantees that a failover will not lose any data and that all load-balanced servers will return consistent results no matter which server is queried. In contrast, asynchronous solutions allow some delay between the time of a commit and its propagation to the other servers, opening the possibility that some transactions might be lost in the switch to a backup server, and that load balanced servers might return slightly stale results. Asynchronous communication is used when synchronous would be too slow. https://www.postgresql.org/docs/current/high-availability.html -
Why I am getting django.db.utils.IntegrityError even after removing default=0?
I am new to Django. I was working on a project whose one of the database tables has a recursive foreignkey. I am sharing that table here. class Categories(models.Model): name = models.CharField(max_length=25) slug = models.CharField(max_length=25) parent = models.ForeignKey("self",on_delete=CASCADE,default=None,blank=True) My database migration did not work when the default was 0. It worked fine when there was null = True. The problem occurred when I removed the null and set default to 0. After having the error, I removed the default=0 and set the null to true. Whatever I try I still have the same problem when I run the python manage.py migrate command. This is my problem: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, stock_app Running migrations: Applying stock_app.0005_alter_categories_parent...Traceback (most recent call last): File "C:\Users\Rakin Shahriar\Desktop\stock-image-sharing-platform\stock_image_sharing_platform\myenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.ForeignKeyViolation: insert or update on table "stock_app_categories" violates foreign key constraint "stock_app_categories_parent_id_b0ca10d8_fk_stock_app" DETAIL: Key (parent_id)=(0) is not present in table "stock_app_categories". The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Rakin Shahriar\Desktop\stock-image-sharing-platform\stock_image_sharing_platform\myenv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\Rakin Shahriar\Desktop\stock-image-sharing-platform\stock_image_sharing_platform\myenv\lib\site-packages\django\core\management\__init__.py", line 413, in … -
Permission has not appear in the admin site
Django 4.1 class ExamPart(models.Model): name = models.CharField(max_length=255, null=False, default="") class Meta: permissions = [('fipi', 'n-fipi')] Problem I have set a permission to the model. Then I created a new user in the admin site. And wanted to grant him this privilege. But I can't see this permission in the admin site. Could you help me? -
cannot get 404 page while entering a invalid url
project Url.py handler404 = 'patient.views.handler404' Patient views.py def handler404(request,exception): return render(request, 'error/404.html') 404.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>404ERROR</title> <link href="{% static 'css/404style.css' %}" rel="stylesheet"> </head> <body> <h2>Page Not Found</h2> </body> </html> And also turn off debug=False but still its shows server error(500) -
Failed to execute 'send' on 'WebSocket': Still in CONNECTING state. while using Django, Nginx, Dophne
daphne.service file [Unit] Description=WebSocket Daphne Service After=network.target [Service] Type=simple User=root #Group=www-data WorkingDirectory=/var/www/html/app EnvironmentFile=/var/www/html/app/.env ExecStart=/var/www/html/Env/myapp/bin/python3 /var/www/html/Env/myapp/bin/daphne -b 0.0.0.0 -p 8000 config.asgi:application #Restart=on-failure [Install] WantedBy=multi-user.target My nginx configuration file upstream channels-backend { server localhost:8000; } server { server_name my.domain.com; location = /favicon.ico { access_log off; log_not_found off; } location /static { alias /var/www/html/app/staticfiles/; } location / { include proxy_params; proxy_pass http://unix:/var/www/html/app/gunicorn.sock; } location /ws/ { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Url-Scheme $scheme; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_pass channels-backend; } client_max_body_size 500M; } my asgi.py file """ ASGI entrypoint. Configures Django and then runs the application defined in the ASGI_APPLICATION setting. """ import os from channels.auth import AuthMiddlewareStack from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator, OriginValidator import base.urls os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( base.urls.websocket_url_patterns, ) ) ), }) So these things are easily available on the internet and I used it. The problem here is in the front end I have connected like this this.state.notificationSocket = new WebSocket( 'wss://' + window.location.host + '/ws/notification/' ); this.state.notificationSocket.onmessage = function(e) { const data = JSON.parse(e.data); console.log('ON MESSAGE'); … -
Sum numbers and group them by the given month, is there a 'best practice'?
I don't know what I messed up. I tried so many methods and solutions and so far this works the best, but the ordering is messy. I want to sum the expenses grouped by the month extracted from the datefield it was given. So far I made this: def index(req): qs = Expense.objects.filter(pom='OUT').annotate(month=TruncMonth('when')).values('month').annotate(total_amount=Sum('amount')) # pom='OUT' -- expense (there are expenses and incomes) return render(req, 'index.html', {'data': qs}) which works perfectly, returns them as "sept. 15.000, aug. 10.000" which is nice! But the last/latest month is always at the bottom so I wanted to give it an order_by, which returns each unique object in the model (so if sept. 15.000 came up as sept.15 10.000 and sept.22 5.000, when they're not summed up but returned/shown separately). What did I mess up? EQ: The mentioned query (without order_by) returns a queryset as of <QuerySet [{'month': datetime.date(2022, 8, 1), 'total_amount': 15000.0}, {'month': datetime.date(2022, 9, 1), 'total_amount': 16000.0}]> by default making it look they all have been recorded at the start of the given month. Drop a reply for further information if I forgot to include something/explained something poorly! -
How to properly import an existing Django project in Eclipse/Pydev?
I cannot figure how to import correctly an existing Django project in Eclipse/Pydev, and I can't find my way in the documentation of Pydev. My question is pretty simple : I have an existing project from a different computer, that I want to migrate on a new one. I installed Eclipse and Pydev on the new machine, and everything seems normal for a new project: I can create a new Django project and run it without issue. I also have been able to import my pre-existing project, but when I run the project, I encounter the following error : Finding files... done. Importing test modules ... Traceback (most recent call last): File "/home/francois/.p2/pool/plugins/org.python.pydev.core_9.3.0.202203051235/pysrc/_pydev_runfiles/pydev_runfiles.py", line 468, in __get_module_from_str mod = __import__(modname) File "/home/francois/eclipse-workspace/Test/Test/urls.py", line 20, in <module> path('', include('myApp.urls')), File "/home/francois/anaconda3/envs/ipaidenv/lib/python3.10/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/home/francois/anaconda3/envs/ipaidenv/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/home/francois/eclipse-workspace/Test/myApp/urls.py", line 2, in <module> from . import views File "/home/francois/eclipse-workspace/Test/myApp/views.py", line 2, in <module> from myApp.forms import CreateGroupForm, JoinGroupForm File "/home/francois/eclipse-workspace/Test/myApp/forms.py", line 4, in <module> from .models import Group, User File "/home/francois/eclipse-workspace/Test/myApp/models.py", line 2, in <module> from django.contrib.auth.models import AbstractUser File "/home/francois/anaconda3/envs/ipaidenv/lib/python3.10/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager … -
Django REST API JWT user verification failed : No active account found with the given credentials
i am using django JWT for account validation but fails for every user that is not super user but works for superuser created using python manage.py createsuperuser Here is the model for User profile class AccountManager(BaseUserManager): def create_user(self, name, phone, email, password=None, **extra_fields): """ Creates and saves a User with z given name,phone,email and password. """ user = self.model(name=name,email=self.normalize_email(email),phone=phone) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, name, phone, email, password=None, **extra_fields): user = self.create_user(name, phone, email, password, **extra_fields) user.is_admin = True user.is_superuser = True user.is_staff = True return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email address',max_length=255,unique=True,) phone = models.CharField(max_length=15,unique=True) name = models.CharField(max_length=150,unique=True) picture = models.ImageField(blank=True, null=True) date_joined = models.DateTimeField(default=timezone.now) last_login = models.DateTimeField(null=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) objects = AccountManager() USERNAME_FIELD = 'phone' REQUIRED_FIELDS = ['name', 'phone', 'email', 'password'] def __str__(self): return self.name and here is my signup API function that creates a normal user def signup(request): if request.method == 'POST': try: values = [request.POST.get('name'),request.POST.get('email'),request.POST.get('phone'),request.POST.get('password'),request.POST.get('password2')] user = Account.objects.create_user(name=values[0],phone=values[2],email=values[1],password=values[3]) user.save() # send email verification current_site = get_current_site(request) mail_subject = 'Activate your account.' message = f'{current_site.domain}/account/activate/{urlsafe_base64_encode(force_bytes(user.pk))}/{account_activation_token.make_token(user)}' to_email = values[1] send_mail(mail_subject, message, 'youremail', [to_email]) return JsonResponse({'success': 'User registered successfully.But need to activate account.'}) except Exception: extype, exc, tb = sys.exc_info() print(f"\t\t****** …