Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
KeyError: 'author' in def_validate Django
I am getting this error inside django validation. if attrs['author'].id == self.context['request'].user.pk: KeyError: 'author' Here is my django model and serializer code. class CalendarTime(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE,related_name='calendartimes') time= models.CharField(max_length=50) date = models.CharField(max_length=300) timestamp = models.DateTimeField(auto_now_add=True) allowstocks = models.BooleanField(default=False) stock = models.IntegerField(default='0') class Meta: constraints = [models.UniqueConstraint(fields=['author', 'time','date'],name='unique_calendartime')] class CalendarTimeSerializer(serializers.ModelSerializer): class Meta: model = CalendarTime fields = ("id","author","allowstocks","stock","time","date","timestamp") def validate(self, attrs): attrs = super().validate(attrs) if attrs['author'].id == self.context['request'].user.pk: return attrs raise ValidationError('Unauthorized Request') The validate code works fine in other functions.Does anybody know where the issue comes from? -
How to use Postgres & MongoDB simultaneously in Django?
I am looking for a solution to work with Postgres and MongoDB simultaneously in my Django project. I have large data which I would like to store in MongoDB and Postgres for user management, billing, and other things to manage. I have tried to use a library pip install django, which is outdated, and not able to find any solution. Please guide me with an authentic solution! Thanks -
Django: how do i substract numbers from another number and return the new_value in django
i have a model field called main_all_earning and it looks like this main_all_earning = models.IntegerField(default=0), i also have a form where user are allowed to input any amount they want to withdraw from main_all_earning, i have written the logic for it to subtract the value from the form which is called amount from the main_all_earning, but the main_all_earning does noot update. What could be the issue? Views.py def withdrawal_request(request): user = request.user profile = Profile.objects.get(user=user) main_all_earning = profile.main_all_earning if request.method == "POST": form = WithWithdrawalRequestForm(request.POST) if form.is_valid(): new_form = form.save(commit=False) new_form.user = request.user if new_form.amount > main_all_earning: messages.warning(request, "You cannot withdraw more than your wallet balance.") return redirect("core:withdrawal-request") elif pending_payout >= main_all_earning: messages.warning(request, "You have reached your wallet limit") return redirect("core:withdrawal-request") elif new_form.amount >= main_all_earning: messages.warning(request, "You have reached your wallet limit") return redirect("core:withdrawal-request") else: new_form.save() main_all_earning = main_all_earning - new_form.amount messages.success(request, f"Withdrawal Request Is Been Processed... You would get a bank alert soon") return redirect("core:withdrawal-request") else: form = WithWithdrawalRequestForm(request.POST) context = { "form":form, "main_all_earning":main_all_earning, } return render(request, "core/withdrawal-request.html", context) context = { "form":form, "main_all_earning":main_all_earning, } return render(request, "core/withdrawal-request.html", context) -
can you pass array into django url without passing in path
say I have a url I want to pass data to like this: {% url 'video_form' {'text': 'text', 'file': video.file, 'image': image} %} and get it like this: def video_form(request): print(text) print(file.url) print(image.url) kind of like POST instead of GET. Can I pass the values in the backend instead of the url like this: path('video_form/<str:text>/', views.video_form, name='video_form') which would not let me pass text inputs in them. -
why is uwsgi cursing and removing instances?
I am trying to test-run a django project on my VPS for the first time. I followed a step-by-step tutorial on a blog (thanks to a nice guy on #django channel at liberachat). The setup involves uWSGI and nginx. The django project files are at /srv/www/site/*. uwsgi configuration is at /etc/uwsgi.d/mysite.com.ini, and nginx configuration is at /etc/nginx/conf.d/mysite.com.conf. Here is what happens when I start uwsgi (systemctl start uwsgi): Jul 29 14:35:09 mysite.com uwsgi[6998]: [uWSGI] getting INI configuration from mysite.com.ini Jul 29 14:35:09 mysite.com uwsgi[6318]: Fri Jul 29 14:35:09 2022 - [emperor] curse the uwsgi instance mysite.com.ini (pid: 6998) Jul 29 14:35:09 mysite.com uwsgi[6318]: Fri Jul 29 14:35:09 2022 - [emperor] removed uwsgi instance mysite.com.ini How do I interpret and fix that? contents of /etc/uwsgi.d/mysite.com.ini: procname-master = demosite # Now paths can be specified relative to here. chdir = /srv/www/ # allow nginx uid = 981 gid = 981 chmod-socket = 644 socket = server.sock # Task management ; Max 4 processes processes = 2 ; Each running 4 threads threads = 2 ; Reduce to 1 process when quiet cheaper = 1 ; Save some memory per thread thread-stack-size = 512 # Logging plugin = logfile ; Log request details … -
400 error when posting PushSubscription object to server
I am setting up push notifications using service workers + websockets using Django Channels and Django WebPush to receive the subscription and send a message back to the service worker. While I am able to register a service worker and receive the PushSubscription object containing details of a push subscription. I then try to send this subscription to an end point in webpush 'save_information' that should have the subscription. However, when I attempt to do this I get the error: Response {type: 'cors', url: 'http://127.0.0.1:8000/webpush/save_information', redirected: false, status: 400, ok: false, …}body: (...)bodyUsed: falseheaders: Headers {}ok: falseredirected: falsestatus: 400statusText: "Bad Request"type: "cors"url: "http://127.0.0.1:8000/webpush/save_information"[[Prototype]]: Response This is the code I have in my service worker/ the code related to getting a subscription and sending through the subscription: const saveSubscription = async (subscription) => { const browser = navigator.userAgent.match(/(firefox|msie|chrome|safari|trident)/ig)[0].toLowerCase(); const data = { status_type: 'subscribe', subscription: subscription.toJSON(), browser: browser, }; const res = await fetch('http://127.0.0.1:8000/webpush/save_information', { method: 'POST', body: JSON.stringify(data), headers: { 'content-type': 'application/json' }, credentials: 'include' }); handleResponse(res); } const handleResponse = (res) => { console.log(res); } ... self.addEventListener('activate', async () => { try { const applicationServerKey = urlB64ToUint8Array('***') const options = { applicationServerKey, userVisibleOnly: true } const subscription = await … -
Python multiple single dictionary return [closed]
[{'ITEM': '001', 'Name': 'test', 'Count': '01', 'cid': 1}][{'ITEM': '002', 'Name': 'test1', 'Count': '02', 'cid': 1}] i want to convert in single list Like That, [{'ITEM': '001', 'Name': 'test', 'Count': '01', 'cid': 1},{'ITEM': '002', 'Name': 'test1', 'Count': '02', 'cid': 1}] I want to return it Also. I tried lots of but unable to get solution. Thanks in advance. -
Why does my django app sometimes takes ages to load a small page
I have a very simple Django app running on a vps running Ubuntu 22.04, sometimes the page loads (for example the admin screen) take >10 seconds, while other times it's instant. I'm serving using Gunicorn, the website receives no traffic yet. What would be a good way to diagnose this? What are some common mistakes in config? -
Nginx not serving static files
I know this has been asked a lot but I have tried every answer I have found for hours and still not getting this to work. I am running Django on a linux server that serves a react app. The html loads fine but all the static files including the js is just getting a 404 not found error. Here is my setting.py currently. I have tried changing it around a bit from other answers i have seen as well. DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = "/home/user/project/static/" STATICFILES_DIRS = [ BASE_DIR / "static/", ] my ngix settings server { server_name domain.app www.domain.app; location /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/user/project/static/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen [::]:443 ssl; # managed by Certbot listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/domain.app/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/domain.app/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } Tried so many combinations of this file with no luck. Some people suggested the Nginx user did not have correct permissions so I also changed the nginx.conf to the same user as the static files … -
Django channels changes in html appear to every client connected
Hi i have a web live chat app and i have an option for users to create a room of their own, but the problem is that i have to refresh on every other client so they can see the room and the database changes, i tried using WebSocket for the rooms lobby and on room creation recieve and send to everyone a "refresh" but i have already a socket for chat rooms and it seems like manipulating two websockets wont work, they collide on .send in the backend. Is there any option for me to make a "refresh" for all running clients upon room creation without using channels?. thank you :) this is the room creation code : html side <div class="create-room-container"> <form action'.' method='post' class="create-room-form"> {% csrf_token %} <div class="room-labels"> <label for="room-name">Room Name :</label> <input type="text" id="room-name" name="room-name" placeholder="Enter room name..."> </div> <input type="submit" value="Create Room" class="create-room-button"> </form> views.py side @login_required def rooms(request): if request.method == 'POST': room_owner = request.user room_name = request.POST['room-name'] if not Room.objects.filter(slug = room_name).exists(): if room_name == '' or room_name.isspace() or room_name.startswith(' '): messages.info(request, 'Invalid room name, spaces-only or string that starts with spaces is invalid.') else: new_room = Room(owner = room_owner,name = room_name,slug … -
Error in using crispy form in django when i created signup from
In template /home/vivekdevkar/Desktop/code/Django/social_media/socialenv/lib/python3.10/site-packages/crispy_forms/templates/bootstrap4/uni_form.html, error at line 8 -
Loading static file to a css file django-python
I have a css file and I want to link another static file to it.How can I accomplish this @font-face { font-family: 'tinymce-mobile'; font-style: normal; font-weight: normal; src: url("fonts/tinymce-mobile.woff?8x92w3") format("woff"); } how can I load this "font/static-mobile.woff" Both {% load static %} and {% load staticfiles%} are not working -
Live Data in Django - Ajax
My aim is to add data to see on the screen whithout refreshing the page. In this code I use un setInterval, but I don't like it. I want to use a method that updates data only when I add new data with the admin Django. JavaScript let tab = document.getElementById('tabella'); setInterval(function() { fetch("{% url 'ajax' %}") .then(response => response.json()) .then(result => { tab.innerHTML = ''; for(let i in result.users) { var text = `<tr><td>${result.users[i].nome}</td> <td>${result.users[i].cognome}</td> <td>${result.users[i].telefono}</td> <td>${result.users[i].email}</td></tr>`; tab.innerHTML += text; } }); }, 1000) views.py def Home(request): return render(request, 'index.html') def Ajax(request): queryset = Utenti.objects.all() return JsonResponse({'users':list(queryset.values())}) urls.py from django.urls import path from .views import Home, Ajax urlpatterns = [ path('', Home, name='index'), path('ajax', Ajax, name='ajax'), ] -
can you create a model object in a model method in Django
is something like this possible: class Comment(models.Model): video = models.ForeignKey(Video, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField() def create_comment_in_template(self, video, user, text): Comment.objects.create(video=video, user=user, text=text) ///// no return -
How to send an email through Sendgrid (in django) as a reply to an email I received from let's say an end user?
So I figured out how to send single/bulk email(s) and then also how to receive emails through SendGrid. What I want to do now is to send an email which will be a reply to an email I received. So basically, I don't want to create a new conversation on let's say Gmail or Outlook, I want my email to be a reply and fall under the hood of another email that I received. -
Django on_delete=models.CASCADE not working when using related_name
I have a model named Proposal which is related to the model Customer by two different fields. I want that if any of the related users gets deleted the proposal will also get deleted. However, the on_delete=models.CASCADE is not achieving that. I guess I could use a signal to trigger this behaviour but I want to know if there is a better way to make it work in Django 4.0. class Proposal(models.Model): # foreign keys created_by_customer = models.ForeignKey(Customer, blank=False, on_delete=models.CASCADE) accepted_by_customer = models.ForeignKey(Customer, blank=True, null=True, on_delete=models.CASCADE, related_name='accepted_by_customer') This is my test with Pytest: @pytest.mark.django_db def test_delete_proposal_from_created_by_customer(): """ Deleting customer that created the proposal must delete proposal """ created_proposal = random_proposal() buyer = random_customer() created_proposal.created_by_customer = buyer created_proposal.created_by_customer.delete() -
How do i check for duplicates in django MongoDB database
I have an table in mongodb with 5000 records. I need to find the email_id field duplicate values from that table. How can i find it. -
Displaying Foreignkey table Data in Django?
I'm a Django Beginner and I was dealing with same problem as in :(How to display Foreignkey table Data in Django?) but the solution to mine was pretty simple which left me to wonder HOW? And even after I got rid of the problem I've a query . My Models were : class Customer(models.Model): name = models.CharField(max_length=64, unique=False) cust_id = models.CharField(max_length=10, unique=True) class Employee(models.Model): name = models.CharField(max_length=64, unique=False) salary = models.BigIntegerField() emp_id = models.CharField(max_length=10, unique=True) class Order(models.Model): order_id = models.CharField(max_length=64, unique=True) assigned_to = models.ForeignKey(to=Employee, on_delete=models.CASCADE) given_by = models.ForeignKey(to=Customer, on_delete=models.CASCADE) bill = models.IntegerField(null=False) As you can see my Order model contains " assigned_to " so in HTML template I wrote it as : {% for x in my_orders %} <tr> <td>{{ x.assigned_to }}</td> </tr> {% endfor %} and all I was getting a blank space I went to shell and get the queryset which showed it as "assigned_to_id" instead of "assigned_to". and then changing in HTML as : {% for x in my_orders %} <tr> <td>{{ x.assigned_to_id}}</td> </tr> {% endfor %} worked for me. Why is that? -
How to Fill Form Automatically After Fill a Value on a Form(AutoFill) Django/Ajax/Etc
Im Stuck in progress for autofill some form, I just wanna do something like this https://miro.medium.com/max/1200/0*muz52MGfi2K93nMt.gif, Here The Model Class I Have : from django.db import models class Contact(models.Model): name = models.CharField(max_length=100) email= models.EmailField() message= models.TextField() def __str__(self): return self.name Then I have Views.py Function Like This: def autofill(request): if is_ajax(request=request): term = request.GET.get('name') contact = Contact.objects.all().filter(name__icontains=term) response_content = list(contact.values()) return JsonResponse(response_content, safe=False) return render(request, 'form_autofill.html') def value_autofill(request): values = Contact.objects.values('name', 'email', 'message') data_dict = {} for dict in values: data_dict[dict['name']] = dict['email'], dict['message'] return JsonResponse(data_dict) There are two function here autofill and value_autofill. the idea is retrieve data from db then convert it into json file based on input value from the template. here the form_autofill.html code : {% block content %} <body> <h2>HTML Forms</h2> <form action="", method="GET"> {% csrf_token %} <label for="name">Name:</label><br> <input type="text" id="name" name="name"><br> <label for="email">Email:</label><br> <input type="text" id="email" name="email" ><br><br> <label for="message">Message:</label><br> <input type="text" id="message" name="message" ><br><br> <input type="submit" value="Submit"> </form> <script> $(document).ready(function() { async function getValues(event, ui) { let url = "{% url 'ajax:values' %}"; let results = await fetch(url);; let data = await results.json(); return data; }; async function AutoCompleteSelectHandler(event, ui){ let vals= await getValues(); $('#email').val(vals[ui.item.value]); }; $("#name").autocomplete({ source: "{% url 'ajax:autofill' %}", … -
How to set a custom url with "admin/" properly? (Django)
I set the custom url "admin/success/" with "admin/" as shown below: # "core/urls.py" urlpatterns = [ path("admin/", admin.site.urls), path("admin/success/", success, name='success'), # Here ] And, this is "views.py": # "core/views.py" from django.http import HttpResponse def success(request): return HttpResponse("Hello World") Then, I got "Page not found (404)" error as shown below: But, when I removed "admin/": # "core/urls.py" urlpatterns = [ # path("admin/", admin.site.urls), # Here path("admin/success/", success, name='success'), ] The custom url is displayed properly as shown below: So, are there any ways to properly set the custom url "admin/success/" with "admin/" so that the custom url is displayed properly? -
TR, TH, TD was created but TABLE NOT
i Need understand it but not be able to. My ClassForm (in view): class FormContact(forms.Form): name = forms.CharField(label='Nome', max_length=100, required=False) subject = forms.CharField(label='Assunto', max_length=100, required=False) message = forms.CharField(label='Mensagem', widget=forms.Textarea, required=False) My extended Template: {% extends 'site.html' %} {% load static %} {% block content %} <form class="contato" id="contato" action="{% url 'contato' %}" method="post"> <h1>Contato</h1> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> <script src="{% static 'js/form_contact.js' %}"></script> {% endblock %} Now, in the navigator (inspector -> elements) <form class="contato" id="contato" action="/contato/" method="post"> <h1>Contato</h1> <input type="hidden" name="csrfmiddlewaretoken" value="???"> <label for="id_name">Nome:</label> <input type="text" name="name" maxlength="100" id="id_name"> <label for="id_subject">Assunto:</label> <input type="text" name="subject" maxlength="100" id="id_subject"> <label for="id_message">Mensagem:</label> <textarea name="message" cols="40" rows="10" id="id_message"></textarea> <input type="submit" value="Submit"> /form> AND, in the navigator (Ctrl+U) View Code <form class="contato" id="contato" action="/contato/" method="post"> <h1>Contato</h1> <input type="hidden" name="csrfmiddlewaretoken" value="YmeKARCvhCLs1EsHedcO1h4OldOaVZ3WKiqGAVZTEJbrYq9ElBVzKQ2EWdHZPw0J"> <tr> <th><label for="id_name">Nome:</label></th> <td> <input type="text" name="name" maxlength="100" id="id_name"> </td> </tr> <tr> <th><label for="id_subject">Assunto:</label></th> <td> <input type="text" name="subject" maxlength="100" required id="id_subject"> </td> </tr> <tr> <th><label for="id_message">Mensagem:</label></th> <td> <textarea name="message" cols="40" rows="10" required id="id_message"></textarea> </td> </tr> <input type="submit" value="Submit"> </form> My doubt is: Why, in the Ctrl+U, was created the elements TR, TH and TD but TABLE not? I can't understand it It is this form same? -
Use Like on Date in sql query
SELECT survey_id, orchardist_name, village, panchayat, dev_block, tehsil, district, survey_id AS ACTION FROM hd_survey_head WHERE created_on BETWEEN '%%' AND '%%' AND dev_block='CHAUPAL' AND panchayat LIKE '%%' AND village LIKE '%%' On my live website, there is a start date and end date option which is mandatory to fill to run a query in the backend to fetch some data with other dropdowns as well. Now the problem is I want to make it optional not mandatory and still run the query is it possible if yes please tell me how to edit this query to work. -
How to aggregate sum of several previous aggregated values in django ORM
In use: django 3.2.10, postgresql 13.4 I have next query set with aggregation function Count queryset = Model.objects.all().aggregate( trues=Count('id', filter=Q(criteria=True)), falses=Count('id', filter=Q(criteria=False)), ) What I want: queryset = Model.objects.all().aggregate( trues=Count('id', filter=Q(criteria=True)), falses=Count('id', filter=Q(criteria=False)), total=trues+falses, <--------------THIS ) How to do this? -
Add column with status to csv while uploading using django
I have created a method to read and upload csv using python django. But, if i want to add a column with status to the csv getting uploaded, how to do? -
django_python3_ldap using multiple OU in LDAP_AUTH_SEARCH_BASE
need some help... i'm using django_python3_ldap and it works fine when i change settings.py for each run using different LDAP_AUTH_SEARCH_BASE . userxxx is logged in with LDAP_AUTH_SEARCH_BASEOU=Users,OU=xxx Accounts,OU=ZZZ,DC=domain,DC=local useryyy is logged in with LDAP_AUTH_SEARCH_BASEOU=Users,OU=yyy Accounts,OU=ZZZ,DC=domain,DC=local i have tried with LDAP_AUTH_SEARCH_BASEOU=OU=Users,OU=xxx Accounts,OU=yyy Accounts,OU=ZZZ,DC=domain,DC=local and this gives noSuchObjec ..... 0000208D: NameErr: DSID-03100241, problem 2001 (NO_OBJECT), any hint?