Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery : Parallel tasks with a custom log format for each task
I'm new to Celery and trying to parallelize multiple instances of the following task : tasks.py @app.task() def scrap_launcher(user_email): from myapp import scrap_user extra = {'user_email':user_email} # ---- I want to display the user_email for each log ---- logger = logging.getLogger(__name__) syslog = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s | %(user_email)s | %(levelname)s : %(message)s') syslog.setFormatter(formatter) logger.setLevel(logging.INFO) logger.addHandler(syslog) logger = logging.LoggerAdapter(logger, extra) # ---- Running the script for 1 user ---- scrap_user.run(user_email,logger) No surprises, when I run res = group(scrap_launcher.s(user_email) for user_email in list_users_email) res.delay() it creates multiple loggers and I get an insane number of duplicates logs. Where should I set up the Logger to get unique logs with a custom format for each user ? -
How to implement a notification queue for users?
Let's say I have users who create events of different time periods(max: 7days), and I have to send notifications to users when their event has ended. In between the time of each event, a user can cancel that event. To accomplish this I had the following implementation in mind: Mimic a priority queue using a database: Put the events in a database indexed and sorted by end time of events and erase events on deletion by the user or when it becomes the topmost event and current time is greater than its end time. This would mean I would have to poll the database every time to check for completed events. Considering that, I am not sure whether this is the right way to do this. So my question is are there any better methods or better, existing technologies that help to accomplish this sort of behavior? PS: Currently my backend is in django, so technologies easily integratable with django would be preferred. -
How to delete collection automatically in mongodb with pymongo ? (Django doesn't delete mongodb collection)
I have Django app which creates collections in MongoDB automatically. But when I tried to integrate the delete functionality, collections that are created with delete functionality are not deleted. Collections that are automatically created are edited successfully. This method is called in another file, with all parameters. An interesting thing to note is when I manually tried to delete via python shell it worked. I won't be deleting the collections which are not required anymore. import pymongo from .databaseconnection import retrndb #credentials from another file all admin rights are given mydb = retrndb() class Delete(): def DeleteData(postid,name): PostID = postid tbl = name + 'Database' liketbl = PostID + 'Likes' likecol = mydb[liketbl] pcol = mydb[tbl] col = mydb['fpost'] post = {"post_id":PostID} ppost = {"PostID":PostID} result1 = mydb.commentcol.drop() #this doesn't work result2 = mydb.likecol.drop() #this doesn't work print(result1,'\n',result2) #returns none for both try: col.delete_one(post) #this works pcol.delete_one(ppost) #this works return False except Exception as e: return e Any solutions, I have been trying to solve this thing for a week. Should I change the database engine as Django doesn't support NoSQL natively. Although I have written whole custom scripts that do CRUD using pymongo. -
Django filtering model on datetime with interger and datetime
I try to make a query to select all the object that where modified since a specified time This time is now - max_schedule_delay where max_schedule_delay is a data from the object (see code sample below). I try multiple thing .. but here I am. Maybe you will be able to help me find a way. Environment python 2.7 django 1.11 database : Posgresql Sample code from django.db import models class MyObject(models.Model): # last modification date mtime = models.DateTimeField(auto_now=True, db_index=True, null=True) # maximum delay before rescheduling in seconds max_schedule_delay = models.IntegerField(null=True) What I want to achieve select * from MyObject where (mtime + max_schedule_delay > now) from django.db.models import F, ExpressionWrapper,, TimeField, DateTimeField from django.db.models.functions import Cast import datetime now = datetime.datetime.now() MyObject.objects.filter(max_schedule_delay__lte=now - F("mtime")) # here max_schedule_delay is a integer, so this query is not possible # I try to split this query in two, but still not wotking MyObject.objects.annotate(threshold=ExpressionWrapper(now - F("max_schedule_delay"), output_field=DateTimeField())).filter(mtime__gte=F("threshold")) MyObject.objects.annotate(as_date=Cast("max_schedule_delay", TimeField())) Any help is welcome, Thanks ! -
Django: How to manipulate data in the value of django form field name like form_field[]
How I manypulate dynamic form field like <input type="text" name="field_name[]" value=""/> in django framework. How to save , fetch data or search field_name[]; And do you have resources like how to deal with it. My full code: https://codepen.io/naowal/pen/poEaKBe -
CRUD Operation Not Updating One Field
I am trying to add a new column to my User form called stakeholder_quadrant, but I am running into weird scenarios. 1) when I create a new item, it does not actually save the value that i enter in this field, and 2) when I go to update an item, the form pops up with stakeholder_group&stakeholder_quadrant concatenated within the stakeholder_group field and nothing in the stakeholder_quadrant field (e.g. RobD instead of stakeholder_group = Rob and stakeholder_quadrant = D). I believe the issue is within my javascript portion... I went through this and re-created every line where there is stakeholder_group mentioned for my new stakeholder_quadrant field, but when I do that my forms don't work at all. Any idea what's causing these errors? models class Stakeholder(models.Model): employee = models.CharField(max_length=200) stakeholder_group = models.CharField(max_length=200) description = models.CharField(max_length=200) stakeholder_quadrant = models.CharField(max_length=200) def __str__(self): return self.stakeholder views class CrudView(TemplateView): template_name = 'polls/stakeholders.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['users'] = Stakeholder.objects.all() return context class CreateCrudUser(View): def get(self, request): employee = request.GET.get('employee', None) description = request.GET.get('description', None) stakeholder_group = request.GET.get('stakeholder_group', None) stakeholder_quadrant = request.GET.get('stakeholder_quadrant', None) obj = Stakeholder.objects.create( employee = employee, description = description, stakeholder_group = stakeholder_group, stakeholder_quadrant = stakeholder_quadrant ) user = {'id':obj.id,'employee':obj.employee,'description':obj.description,'stakeholder_group':obj.stakeholder_group,'stakeholder_quadrant':obj.stakeholder_quadrant} data = … -
Nginx unit not working with django (ModuleNotFoundError: No module named 'encodings')
I keep getting: ModuleNotFoundError: No module named 'encodings' in the unit error logs when trying to add new configuration. Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' 2020/12/31 19:51:50 [notice] 13294#13294 process 13297 exited with code 0 2020/12/31 19:51:50 [info] 15500#15500 discovery started 2020/12/31 19:51:50 [notice] 15500#15500 module: java 11.0.8 "/usr/lib/unit/modules/java11.unit.so" 2020/12/31 19:51:50 [notice] 15500#15500 module: perl 5.26.1 "/usr/lib/unit/modules/perl.unit.so" 2020/12/31 19:51:50 [notice] 15500#15500 module: php 7.2.24-0ubuntu0.18.04.6 "/usr/lib/unit/modules/php.unit.so" 2020/12/31 19:51:50 [notice] 15500#15500 module: python 2.7.17 "/usr/lib/unit/modules/python2.7.unit.so" 2020/12/31 19:51:50 [notice] 15500#15500 module: python 3.6.9 "/usr/lib/unit/modules/python3.6.unit.so" 2020/12/31 19:51:50 [notice] 15500#15500 module: python 3.7.5 "/usr/lib/unit/modules/python3.7.unit.so" 2020/12/31 19:51:50 [notice] 15500#15500 module: ruby 2.5.1 "/usr/lib/unit/modules/ruby.unit.so" 2020/12/31 19:51:50 [info] 15499#15499 controller started 2020/12/31 19:51:50 [notice] 15499#15499 process 15500 exited with code 0 2020/12/31 19:51:50 [info] 15514#15514 router started 2020/12/31 19:51:50 [info] 15514#15514 OpenSSL 1.1.1 11 Sep 2018, 1010100f 2020/12/31 19:52:40 [info] 15597#15597 "example_python" application started 2020/12/31 19:52:40 [info] 15602#15602 "example_python" application started 2020/12/31 19:54:20 [info] 15766#15766 "example_python" application started 2020/12/31 19:54:20 [info] 15767#15767 "example_python" application started 2020/12/31 19:54:20 [notice] 15499#15499 process 15597 exited with code 0 2020/12/31 19:54:20 [notice] 15499#15499 process 15602 exited with code 0 2020/12/31 19:57:49 [info] 16117#16117 "django" application started Fatal Python error: Py_Initialize: Unable to get … -
Accessing Django Foreign Key Object Values through Django Shell
How do I correctly access Foreign Key Values through the Django Shell? I am trying to access the Foreign Key Values of the Placement Field (an integer from 1 to 8) through the Django Shell. When I query I receive values greater than 8 (the max of data currently entered), which is unexpected. Django Admin Screenshots: Champion_Placement Table , Match_Placement Table Query: manage.py shell from stats.models import * Champion_Placement.objects.all('placement').values() <QuerySet [{'placement': 10}, {'placement': 10}, {'placement': 10}, {'placement': 10}, {'placement': 10}, {'placement': 10}, {'placement': 10}, {'placement': 10}, {'placement': 10}, {'placement': 11}, {'placement': 11}, {'placement': 11}, {'placement': 11}, {'placement': 11}, {'placement': 11}, {'placement': 11}, {'placement': 11}, {'placement': 12}, {'placement': 12}, {'placement': 12}, '...(remaining elements truncated)...']> Models: from django.db import models class Summoner(models.Model): puuid = models.CharField(max_length=100) name = models.CharField(max_length=30, null=True) def __str__(self): return f'{self.name} - {self.puuid}' class Match_Placement(models.Model): match_id = models.CharField(max_length=100) placement = models.PositiveSmallIntegerField() puuid = models.ForeignKey(Summoner, on_delete=models.CASCADE) def __str__(self): return f'{self.match_id} - {self.placement}' class Champion(models.Model): champion_id = models.CharField(max_length=40) name = models.CharField(max_length=30) cost = models.PositiveSmallIntegerField() def __str__(self): return f'{self.name}' class Item(models.Model): item_id = models.PositiveSmallIntegerField() name = models.CharField(max_length=40) def __str__(self): return f'{self.name}' class Champion_Placement(models.Model): match_id = models.ForeignKey(Match_Placement, related_name='%(class)s_match_id',on_delete=models.CASCADE) placement = models.ForeignKey(Match_Placement, related_name='%(class)s_placement', on_delete=models.CASCADE) champion_id = models.ForeignKey(Champion, related_name='%(class)s_champion_id', on_delete=models.CASCADE) champion_level = models.PositiveSmallIntegerField() item_1 = models.ForeignKey(Item, … -
How can you make a collapsible menu in Django?
I'm trying to build an admin dashboard in Django and I've came across a problem. Here would be the HTML code: I want that when the user clicks "Email Searcher", more values appear. Those values are called "Butons" and "Cards". But I don't know how someone can make this happen in Django. <li class="nav-item"> <a class="nav-link collapsed" href="{% url 'emailfinder' %}" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo"> <i class="fas fa-fw fa-cog"></i> <span>Email Searcher</span> </a> <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> <h6 class="collapse-header">Custom Components:</h6> <a class="collapse-item" href="{% url 'example' %}">Buttons</a> <a class="collapse-item" href="cards.html">Cards</a> </div> </div> </li> any help would really appreciate it! -
Django - Add custom fields to records
Suppose we have a Mode Table with common fields (id, name, date_creation) class Table(models.Model): id = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=128, blank=True, null=True) date_creation = models.DateTimeField(blank=True, null=True) Some Tables must have a "Wheels" attribute (eg: wheels="plastic"), while other tables do not require this attribute and require something else. eg : Table 1: id = ..., name = ..., date_creation = ..., wheels = "plastic" Table 2: id = ..., name = ..., date_creation = ..., feet = "wood" How can i manage this extrafields in Django in order to deserve them in Django Rest Framework? -
Django get specific QuerySet with GET ajax Call on button click
i have a problem and i dont know if im using the good way to solve it , but their is the problem , i have a client list that i show on the client page , by getting all client with a simple clients = client.objects.all() so all client can have a lot of sessions, and session have a lot of clients, its like a ManytoMany relation, so what im trynna do its to show the assigned session of client one by one by clicking on a button (the button open a boostrap modal ) , so i tried to send the id of the the chosen client on click and send it into a django view with ajax GET method, and take this ID directly to find all sessions related with this client and return the query to this page , so the ajax is working correctly and i can send the id , but its like the view its not sending anything . so their is my code hope you can help me : Html (the div im inserting on the forloop client) : <div class="list-group list-group-me"> <ul class="list-group list-group-horizontal"> <li class="list-group-item">{{ client.name }}</li> <li class="list-group-item">{{ client.email … -
Django Cookie consent
I am looking for a decent documentation and ideally also a full example on how to use the cookie-consent app in django. I found this app here: github code on cookie-consent but I cannot imagine how to use it. And the documentation provided does not help much... as I do not understand what to do to implement. regards Marina -
In django if I have more than one database , how do I tell django to create which model-table in which database?
For example I have these two databases. Now while creating a model class, how do I tell django to initiate that model table in the 'movie' database and not in the 'default' one. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'projectInfo', 'USER': 'root', 'PASSWORD': '123@abc', }, 'movie': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'movieDB', 'USER': 'root', 'PASSWORD': '123@abc', } } -
Gmail sending with attachment in Django
I am trying to send Gmail with attachments also in Django. here my views.py: def index(request): if request.method != 'POST': form = EmailForm() context = {'email_form': form} return render(request, 'app/index.html', context) form = EmailForm(request.POST, request.FILES) if form.is_valid(): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] email = form.cleaned_data['email'] attach = request.FILES['attach'] try: mail = EmailMessage(subject, message, settings.EMAIL_HOST_USER, [email]) mail.attach_file(attach.name, attach.read(), attach.content_type) mail.send() context = {'message': 'email sended'} print("email sended") return render(request, 'app/email_template.html', context) except: context = {'message': 'Either the attachment is too big or corrupt'} print("Either the attachment is too big or corrupt") return render(request, 'app/index.html', context) context = {'message': 'Unable to send email. Please try again later'} return render(request, 'app/index.html', context) forms.py: class EmailForm(forms.Form): email = forms.EmailField() subject = forms.CharField(max_length=100) attach = forms.Field(widget = forms.FileInput) message = forms.CharField(widget = forms.Textarea) template: <div class="container-fluid"> <div class="col-xl-4"> <h1>Welcome in django's world</h1> {{message}} <form method="POST" action ="." enctype="multipart/form-data"> {% csrf_token %} <br></br> {{email_form.as_p}} <label>&nbsp;</label><label>&nbsp;</label><label>&nbsp;</label> <input type ="submit" name = "send" value = "Send"/> </form> </div> </div> Now each and every time I tried to sent mail, it shows Either the attachment is too big or corrupt, that means it goes by the except: block, instade of try block. Now how can I solve this … -
Django: After updating a post, how can i make the "updated" success message temporary, till I refresh the page. Cause now it stays after refresh
Django: Hi everyone, After updating a post, how do i redirect success message to full details page TEMPORARILY. because for my code now, after i update, i can see the updated message but even after refreshing, the updated success message remains there. kindly advise thank you! views.py def edit_blog_view(request, slug): context = {} blog_post = get_object_or_404(BlogPost, slug=slug) if request.POST: form = UpdateBlogPostForm(request.POST or None, request.FILES or None, instance=blog_post) if form.is_valid(): obj = form.save(commit=False) obj.save() return redirect('HomeFeed:detail', slug=slug) form = UpdateBlogPostForm( initial = { "brief_description": blog_post.brief_description, "image": blog_post.image, "body": blog_post.body, } ) context['form'] = form return render(request, 'HomeFeed/edit_blog.html', context) def detail_blog_view(request, slug): context = {} blog_post = get_object_or_404(BlogPost, slug=slug) context['success_message'] = "Updated" context['blog_post'] = blog_post return render(request, 'HomeFeed/detail_blog.html', context) detail_blog.html {% if success_message %} <div class="alert alert-success" role="alert"><h3 style="text-align: center;">{{success_message}}</h3></div> {% endif %} -
getting total number of records saved in django bulk_create
is there any way to get the number of total records inserted in Django model using bulk_create?? Entry.objects.bulk_create([ ... Entry(headline="Django 2.0 Released"), ... Entry(headline="Django 2.1 Announced"), ... Entry(headline="Breaking: Django is awesome") ... ]) In the above example, 3 records are inserted into the database. How can I get the total number of records using bulk_create?? -
template not showing the message
i was using Django Login system and it has a message error when i do run the template of the login and i do the mistake it doesn't give me and error login.html: <body> <div class="container"> <h1>Login</h1> <form action="" method="post"> {% csrf_token %} <div class="form-floating mb-3"> <input type="text" class="form-control" id="floatingInput" placeholder="name@example.com" name="username"> <label for="floatingInput">Username</label> </div> <div class="form-floating"> <input type="password" class="form-control" id="floatingPassword" placeholder="Password" name="password"> <label for="floatingPassword">Password</label> </div> {% for message in messages %} <h4 style="color: red;">{{message}}</h4> {% endfor %} <button type="submit" class="btn btn-dark mt-2">Log in</button> <a href="{% url 'register' %}" class="btn btn-dark mt-2 ml-3">Register</a> </form> </div> views.py: def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') if username and password: user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request, 'Username or Password is Incorrect') else: messages.error(request, 'Fill out all the Fields Please') return render(request, 'register/login.html', {}) -
How to fix UnboundLocalError at /accounts/register
I made a registration from for my django app.But when I click on the submit button I'm getting this error: local variable 'first_name' referenced before assignment Request Method: POST Request URL: http://127.0.0.1:8000/accounts/register Django Version: 3.1.4 Exception Type: UnboundLocalError Exception Value: local variable 'first_name' referenced before assignment Exception Location: E:\django\Hello_world\accounts\views.py, line 8, in register Python Executable: C:\Users\Asus\Envs\test\Scripts\python.exe Python Version: 3.9.0 Python Path: ['E:\django\Hello_world', 'c:\users\asus\appdata\local\programs\python\python39\python39.zip', 'c:\users\asus\appdata\local\programs\python\python39\DLLs', 'c:\users\asus\appdata\local\programs\python\python39\lib', 'c:\users\asus\appdata\local\programs\python\python39', 'C:\Users\Asus\Envs\test', 'C:\Users\Asus\Envs\test\lib\site-packages'] My code is views.py def register(request): if request.method == 'POST': first_name = request.POST[first_name] last_name = request.POST[last_name] username = request.POST[username] email = request.POST[email] password1 = request.POST[password1] password2 = request.POST[password2] user = User.objects.create_user(username=username, email=email, password=password1, first_name=first_name, last_name=last_name) user.save(); print('user created successfully') return redirect('/') else: return render(request, 'register.html') and the html file is: register.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Registration</title> </head> <body> <form action="register" method="post"> {% csrf_token %} <input type="text" name = 'first_name' placeholder="First Name"><br> <input type="text" name = 'last_name' placeholder="Last Name"><br> <input type="text" name = 'username' placeholder="Username"><br> <input type="email" name = 'email' placeholder="E-mail"><br> <input type="password" name = 'password1' placeholder="Password"><br> <input type="password" name = 'password2' placeholder="Confirm Password"><br> <input type="submit"> </form> </body> </html> -
django ManyToMany create object
i have two model with ManyToMany relations.. class foo(models.Model): .......... class bar(models.Model): foo = models.ManyToMany(foo) i use ModelForm for creating bar.. i wanna access new bar object (after save). if form.is_valid(): new_obj = form.save() i can access before save with : if form.is_valid(): new_obj = form.save(commit=False) but i can access it after save...what can i do? -
Check if user's email is verified in Firebase
I am currently making a login page with Django and Firebase, where after the user has been created, a link for verifying the email will be sent. I tried to add a feature where if the user has not verified the email, he/she is not able to log into the web application. Currently this is what i tried in my views.py (using pyrebase): import pyrebase config={my firebase configuration} firebase=pyrebase.initialize_app(config) db=firebase.database() auth=firebase.auth() def postsign(request): email=request.POST.get('email') passw=request.POST.get('pass') try: user=auth.sign_in_with_email_and_password(email,passw) usercheck = auth2.get_user(user['idToken'],email_verified) if usercheck == False: message="Please verify your email!" return render(request,"template.html", {"msgg":message}) except: message="Invalid credentials. Try again." return render(request,"login.html", {"msg":message}) I tried looking through the documentation, however, I only found a code for javascript, like in this post, and this link which is kind of what I am trying to achieve https://firebase.googleblog.com/2017/02/email-verification-in-firebase-auth.html -
how to use rest-framework simple JWT package for custom user model?
I have created a custom user model in Django. Now I'm authenticating with the below code. class Login(APIView): def post(self,request): email = request.POST['email'] password = request.POST['password'] user = authenticate(request, email= email,password=password) print(request.user) if(user is not None): print("Logged In") return Response("Hello") But from the official documentation I can't find how to achieve this is usecase. They just use TokenVerifyView.as_view() in urls.py file. How to use JWT authentication with this custom user model. -
how to create billing application in Django
I have planned to create billing application using Django. I need to store order in database, user's order as separate customer profile. I don't want to create each customer as user. I just want to store customer order details and print out the bill. I don't know how to create model and I cannot think the logic. Help me. -
How to perform code navigation in Django using docker
I could not find the code definition using Ctrl + click when I use Docker + Django in my project, since source code are now in container. How could I configure my VScode to enable code navigation? I am using django-cookiecutter with use-docker configuration. -
Django Views, having 2 redirects in 1 view
Is it possible to have 2 redirect() in the same django view. so when the like button is in the home page, i want it to redirect back to home page, if like button is in detail page, i want to redirect back to detail page? For instance: def LikeView(request, slug): context = {} post = get_object_or_404(BlogPost, slug=slug) post.likes.add(request.user) if in homepage: return redirect('HomeFeed:detail', slug=slug) else: return redirect('HomeFeed:main') -
Django Change Variable From DataBase on Referencing
I'm currently learning Django and I wanted to start off with a really simple blog app. I have a model for my post: class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) body = models.TextField() Then I'm referencing it on my home page template: {% extends 'base.html' %} {% block content %} {% for post in object_list %} <div class="post-entry"> <h2><a href="{% url 'post_detail' post.pk %}">{{post.title}}</a></h2> <p>{{post.body}}</p> </div> {% endfor %} {% endblock content %} I would like to make post.body to be only first 50 or so characters but post.body[:50] returns sytnax error. How could I do that?