Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it okay to listen same queue in multiple celery pods using redis as a brocker?
I am trying to scale my Django application that uses Celery for background tasks. Assume that I have one main queue and one celery instance listening to it. What could actually happen if I add another celery instance that listens to the same queue? Is there a way two workers will execute same task twice? Note: Using different queues for each celery instance is not an option for me. Thanks in advance! -
How to align bokeh rectangles?
In django I'm drawing a boxplot using bokeh and the image has a left an right margin which I cannot remove as shown in the picture. The green rectangle should be left aligned without having the white space. Here my code: def get_boxplot_chart_pdf(data, student_score): if len(data) == 0: return None df = pd.DataFrame({'scores': data}) cats = ['scores'] mean = df.quantile(0.5) q1 = df.quantile(0.25) q3 = df.quantile(0.75) upper = [max(data)] lower = [min(data)] # create figure and set all borders to 0px p = figure(y_range=cats, toolbar_location=None, plot_width=285, plot_height=27) p.min_border = 0 p.margin = (0, 0, 0, 0) # Stems p.segment(upper, cats, q3, cats, color="black") p.segment(lower, cats, q1, cats, color="black") # Boxes p.hbar(y=0.5, right=q1, left=mean, height=0.5, fill_color=None, line_color="black") p.hbar(y=0.5, right=mean, left=q3, height=0.5, fill_color=None, line_color="black") # whiskers (almost-0 height rects simpler than segments) p.rect(lower, cats, 0.01, 0.2, color="black") p.rect(upper, cats, 0.01, 0.2, color="black") # student score fill_color = "Green" if student_score >= 30 else "Red" p.rect(x=student_score / 2, y=0.5, height=1, width=student_score, fill_color=fill_color, line_color=None, fill_alpha=0.3) p.xgrid.grid_line_color = None return remove_chart_chrome(p) def remove_chart_chrome(chart): chart.axis.visible = False chart.grid.visible = False chart.outline_line_color = None chart.min_border = 0 return chart Thank you for any help ;) -
Android Studio: Create Login Screen in Existing Android Studio Project as First Screen
I purchased a source code from codecanyon and now i want to add login screen at the first page of the app so that when someone opens app for first time they have to login through user id and password given by us. I'm new in android studio and have only basic knowledge. So, please help me. -
Python pytesseract incorrect data extraction from image
I used the below code in Python to extract text from image, def read_image_data(request): import cv2 import pytesseract pytesseract.pytesseract.tesseract_cmd = "C:/Program Files/Tesseract-OCR/tesseract.exe" img = cv2.imread("image_path") height, width = img.shape[0:2] startCol = 345 # x1 Left startRow = 107 # y1 Top endCol = 389 # x2 Right endRow = 135 # y2 Bottom croppedImage = img[startRow:endRow, startCol:endCol] text = pytesseract.image_to_string(croppedImage) gray = cv2.cvtColor(croppedImage, cv2.COLOR_BGR2GRAY) ret, threshold = cv2.threshold(gray, 55, 255, cv2.THRESH_BINARY) print(pytesseract.image_to_string(threshold)) print(text) But the output is incorrect. The input file is ± 0.1 % and the output received is 201% instead of ± 0.1 %. The input file is ± 50 ppm/K and the output received is +50 ppmik instead of ± 50 ppm/K The input file is 10 to 100 k and the output received is 1010332ka. instead of 10 to 100 k What are the required code changes to retrieve the right Characters from the image? -
How to insert JavaScript variable into template tag variable in Django?
I have the following code in my templatetag: def getbyid_property(pk): property_detail=Properties.objects.get(id=pk) html_data='<div class="property_item heading_space"><div class="image">......</div></div>' return html_data and in my template, I have the following code: var getPointData = function (index) { var property_id='{{ 'index'|getbyidproperty|safe }}'; ....} Here, index is JavaScript variable and {{ 'index'|getbyidproperty|safe }} is python(django) variable. When I run this code, it is rising the following error message Field 'id' expected a number but got 'index'. index JavaScript variable returns integer value. And it is not inserting this integer value instead it is inserting index word. if I place some integer value instead of index for example 28 {{ 28|getbyidproperty|safe }}, this code works without any issue. My question is how can I insert JavaScript variable into python variable? Is it possible to it in a way that I did above? If no, how can I do it? -
ruby devise encrypted password decrypt in django
First my database was connected to ruby.Ruby devise uses Bcrypt password by default to hash passwords. I am building same app in django but also want that old users can login using django app that is only possible if django can decrypt ruby hashed password stored in mysql database. By default django password hashing looks something like this: pbkdf2_sha256$180000$cZxgIsN0sthv$XnAOHJiWIX1E1/p4livZCcmf6DmmKi2FZPrKbDZIpfM= When i changed default password haser in django to Bycrypt algorithm passwords are stored something like this: bcrypt_sha256$$2b$12$MUA0prRIYOnu63HAFP9tP.RsNVyO.ApAv.zTJX5GOBb2eBQ.8hz.W IN database ruby passwords are stored something like this: $2a$12$tBfIVsgQvDSM8WOu9SDpGupSaFbHXJbAT8lOtkvYCMO5NrOVjy9Y2 Inorder to decrypt ruby written passwords i tried adding "bcrypt_sha256$" and "bcrypt$" before ruby passwords to make it django bcrypt format but it does not work. -
bootstrap card in a for loop - tabs only work on the first card - django
I am trying to get repeating cards with tabs within my for loop but the tabs only seem to work on the first card and none of the below e.g I have two tabs - on card 1: tab 1 opens tab 1 and tab 2 opens tab2 but on card 2 tab 2 opens tab 2 on card 1: Cards example Is there a way to make the second tab repeat down the for loop? HTML: {% for project in projects %} <div class="card"> <div class="card-header"> <ul class="nav nav-tabs card-header-tabs"> <li class="nav-item"> <a class="nav-link active" href="#details" role="tab" data-toggle="tab">Details</a> </li> <li class="nav-item"> <a class="nav-link" href="#stats" role="tab" data-toggle="tab">Stats</a> </li> </ul> </div> <div class="tab-content"> <div role="tabpanel" class="tab-pane active" id="details"> <div class="card-header"> <div class="row"> <div class="col-md-2"><strong>Project</strong></div> <div class="col-md-2"><strong>Distributor</strong></div> <div class="col-md-2"><strong>Licensee</strong></div> <div class="col-md-2"><strong>Budget</strong></div> <div class="col-md-2"><strong>Release Date</strong></div> <div class="justify-content-center col-md-1"><strong>View</strong></div> <div class="justify-content-center col-md-1"><strong>Edit</strong></div> </div> </div> <div class="card-body"> <div class="row"> <div class="col-md-2">{{project.production_title}}</div> <div class="col-md-2">{{project.distributor}}</td></div> <div class="col-md-2">{{project.licencee}}</td></div> <div class="col-md-2">{{project.currency}} {{project.budget}}</td></div> <div class="col-md-2">{{project.release_date}}</td></div> <div class="justify-content-center col-md-1"><a href="{% url 'tracks' project.pk %}" class="btn btn-dark btn-sm" role="button">Tracks</a></div></td> <div class="justify-content-center col-md-1"><a href="{% url 'update_project' project.pk %}" class="btn btn-dark btn-sm" role="button">Edit</a></div></td> </div> </div> </div> <div role="tabpanel" class="tab-pane" id="stats">Test </div> </div> </div> <br> {% endfor %} -
How to create a custom authenticate in Django?
I want to create an aunthentication django views, but I have my own custom User model. I am not using django default user model. So I need my custom authenticate model and import in anywhere I want. -
When i turn off the DEBUG mode in settings.py it returns a bad request(400)
I see this when i turn off Debug mode DEBUG = False ALLOWED_HOSTS = [ 'localhost:8000', ] How am i going to fix this? -
Sentry mark some exceptions as warnings
I have a lot of errors when user tries to access some resource and get 403 exception because of forbidden IP. Is it possible to find them by regular expression by their message and send them to sentry as warnings? -
Transformer model deployment
I am trying to deploy a transformer model for question answering within a website using django framework. As I test it locally the model responds quickly giving back the answers. Currently, I have deployed it in digital ocean server and tested the website across three different users. The model only runs for few instances and then stops giving back answers. I receive a websocket disconnect error. The server droplet has 8gb of ram, 8vCPUs and 32gb of disk. What might be the problem? I am kindly asking for your help -
Is the a way to make ALLOWED_HOSTS accept new domains dinamically in Django?
I wan't to let users to connect their domains to my site. For example, a user has bought example.com (the domain) and wants that when someone types example.com in the browser, what the browser shows is my app. I have everything configured and working except for the ALLOWED_HOSTS setting. If I add manually the domain to my ALLOWED_HOSTS it works. But, in production server, users will be creating this connections at anytime, I can't be adding this lines manually and restarting the server. Is there a different way of achievings this without making ALLOWED_HOSTS = ['*',] If there is no other way, I'm not sure wich is the safest way to check request.get_host() in a middleware. If someone could guide me, I'd be eternally thankfull. I hope I explained myself good enough. -
why my app is not loading in browser in GKE
I have my deployment script running with no errors. I have the service running with no errors. But when I load the external IP in the browser, it loads forever with the message: Here is my docker file: # pull official base image FROM python:3.8 EXPOSE 8080 # Install GDAL dependencies #RUN apt-get update && apt-get install --yes libgdal-dev #apt-get install binutils libproj-dev gdal-bin RUN apt-get update && apt-get install --reinstall -y \ binutils \ libproj-dev \ libmemcached11 \ libmemcachedutil2 \ libmemcached-dev \ libz-dev # Copy the application's requirements.txt and run pip to install all # dependencies into the virtualenv. ADD requirements.txt /app/requirements.txt RUN pip install -r /app/requirements.txt # Add the application source code. ADD . . CMD exec gunicorn --bind :8080 --workers 1 --threads 8 main:app --timeout 0 --preload Here is my deployment script: # [START kubernetes_deployment] apiVersion: apps/v1 kind: Deployment metadata: name: web labels: app: web spec: replicas: 3 selector: matchLabels: app: web template: metadata: labels: app: web spec: containers: - name: web-app # Replace with your project ID or use `make template` image: gcr.io/app-kor/app-kubernetes:v0.0.1 # This setting makes nodes pull the docker image every time before # starting the pod. This is useful when debugging, but should … -
Dynamically find model objects in Django and update page with its data
I am stuck with a thing that I want to implement on my Django website. I want to have several inputs on a page where the user can select IDs of the objects from the database, and after they click on a button, the info about those objects need to be shown on the same page underneath. How do I do that properly with Django views and Model objects? Can I have multiple views or nested views in Django on a webpage? It wouldn't be much of an issue to send this data to a new page with another view, however, this has to be on the same page. Can anybody show me on a code example how this has to be done? -
Django sites framework with REST API
I have an existing Django project which uses the sites framework to produce data for several websites from the same database. At the moment, it renders the templates using Django templates but I'd like to create a REST API (using django-rest-framework) so that I can create the frontends using another framework, like vue. Before I go down that road, I want to get my head around how I can do this using the sites framework. Is it safe to assume that it's as simple as making sure that the frontend puts the site's domain in the HTTP request and Django will pick it up from there and return the correct data from the database? Or should I be thinking along different lines? -
"This field is required" keeps showing even all the input field is filled
Please help. The signup page keeps showing this field is required error. I'm a beginner. thankyouu models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, username, full_name, password=None): if not email: raise ValueError("Users must have an email adress") if not username: raise ValueError("Users must have a username") if not password: raise ValueError("Users must have a password") if not full_name: raise ValueError("Users must have a name") user = self.model( email=self.normalize_email(email), # return lowercase username=username, full_name=full_name, ) user.set_password(password) # users set password and change password user.full_name = full_name user.save(using=self._db)# using the default database in settings.py return user def create_superuser(self, email, username, full_name, password=None): user = self.create_user( email=self.normalize_email(email), # return lowercase username=username, full_name=full_name, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) # using the default database in settings.py return user class Account(AbstractBaseUser): email = models.EmailField( verbose_name="email", max_length=60, unique=True, ) username = models.CharField(max_length=30, unique=True) full_name = models.CharField(max_length=30, blank=True, null=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) profile_image = models.ImageField(max_length=255, null=True, blank=True, default=default_profile) hide_email = models.BooleanField(default=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username", "full_name"] objects = UserManager() # tie account to … -
Is transaction.on_commit executed as part of transaction?
If there is exception in the callback provided to on_commit does this rollback transaction or not? -
python django long polling waiting
I use Django with Rest Framework. I made a long polling view to return the latest update to other clients. To wait for long polling, I used time.sleep(seconds) function. but this seems it works only for the client who made change. other clients seems stuck in somewhere. Could you advice the right way to wait for long polling in Python Django ? class ChangedItemsPollingView(APIView): permission_classes = [permissions.IsAdminUser] def get(self, request): request_received_time = datetime.datetime.now() ten_seconds_later = request_received_time + datetime.timedelta(seconds=10) while(datetime.datetime.now() < ten_seconds_later): changed_items = Asset.objects.filter(updated_at__gt=request_received_time) if(changed_items): tmpJson = djangoSerializers.serialize('json', changed_items) tmpObj = json.loads(tmpJson) return Response(tmpObj) time.sleep(3) return Response([]) -
py manage.py startapp polls sous eclipse/django
J'ai créer une application avec la commande'' py manage.py startapp polls '' le fichier polls est créer.mais il ne figure pas sur ''ouvrir fichier'' d' eclipse/django ; comment le récupérer. -
Return redirect in returning NoneType instead of REDIRECTING - Python Django [ERROR]
Here I wan't to redirect the if sessions don't exist. But the function authenticate is returning None instead of rediecting to homepage. WHat's the solution... inside authenticate function: def authenticate(request): username = request.session.get('username') password = request.session.get('password') email = request.session.get('email') if username and password: user_data = User.objects.get(username=username, password=password) if user_data.is_active: return {'bool':True, 'ud':user_data} elif not user_data.is_active and username: redirect(f'verify/{username}') else: return False else: request.session.delete() return redirect('/') inside views.py def profile(request, username): auth = authenticate(request) -
Django: How to only display content made by a user to that same user?
I'm learning Django (obviously) and one thing I just noticed about a project I'm building is that initially, Each user could see objects/content made by every other user. For instance, my project is a very basic fantasy football app, I've set it up so that a user can create a team by adding listed players to my team model called "MyTeam" as seen here. class Myteam(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) QB = models.CharField(max_length=80, null=True) QBscore = models.IntegerField(null=True) RB1 = models.CharField(max_length=80, null=True) RB1score = models.IntegerField(null=True) RB2 = models.CharField(max_length=80, null=True) RB2score = models.IntegerField(null=True) WR = models.CharField(max_length=80, null=True) WR1score = models.IntegerField(null=True) WR2 = models.CharField(max_length=80, null=True) WR2score = models.IntegerField(null=True) TE = models.CharField(max_length=80, null=True) TEscore = models.IntegerField(null=True) D = models.CharField(max_length=80, null=True) Dscore = models.IntegerField(null=True) K = models.CharField(max_length=80, null=True) Kscore = models.IntegerField(null=True) I've learned about ForeignKeys for linking specific content to a particular user and the next step I'm trying to figure out is how to get it so that a logged-in user can only see their team and no one else's. I've been searching around here and other places via google, but as a Django noob, it's hard to even verbalize the right question to search for in the first place. I thought I … -
Python : Regex to parse 1w 5d 3h 6m?
I am able to parse days, hours and minute using the following regex, ^(\d+d)?\s*((?:[01]?\d|2[0-3])h)?\s*((?:[0-5]?\d)m) What I needed to support the week too (1w 5d 3h 6m)? -
Django strange behaviour in filter query with distinct
email_manager_obj = EmailManager.objects.filter(<some filter>) batchsize = 10 for count in range(0, email_manager_obj.count(), batchsize): batch = email_manager_obj[count:count + batchsize] for item in batch: item.is_email_sent = True item.number_of_email_sent += 1 EmailManager.objects.bulk_update(batch, ['is_email_sent', 'number_of_email_sent']) time.sleep(1) return True my question is: In email_manager_obj query when i running this program, column = my 'number_of_email_sent' has generating random counting and saves in DB. it supposed to count existing number +1, i dont know why is this happening, is this a bug or i am doing it wrong. Also i have tried with single query (item.save()) to updated individually. still happening same thing. After some time, i found when i use 'email_manager_obj' with distinct("id") email_manager_obj = EmailManager.objects.filter(<some filter>).distinct("id") then it is counting correct integer. (email_manager_obj contains no duplicate items from filter querset ) Strange behaiviour can someone suggest me if its a some kind of bug or my code issue. i am using Django 2.2.10, python 3.6, postgres -
Heroku sessions persist across browsers
I've run into a problem that I simply don't understand. I'm using Django with Heroku and everything works fine when running on localhost. But on Heroku sessions behave unexpectedly. First of all - why is my session synched on the server and not in individual browsers? When I input data from Chrome, I have the same data appear in Edge and in Anonymous new browser windows. I don't want this behaviour. I tried to change the backend session engine to file, cached_db and db, but everything behaves the same. It causes a lot of problems. Data are not transferred properly and I don't know what the problem is. I need to transfer data between two HTML templates. I'm sending the data forward as a dictionary: send_input = { 'artists': context['chosen_artists'], 'songs': input_songs, 'ids': input_ids, } request.session['send_input'] = send_input But something is off and I have no idea what is wrong. You can see it on http://das-music.herokuapp.com/model/checklist/ When you enter an artist, you can choose a song from that artist. Data are then stored in context dictionary because I'm reloading the page. You can choose a different artist and new songs. That's when the first problem happens. Data are not "saved" … -
django-allauth verification email send with example.com:port
I am working with django-allauth. I manage to do everything, however the port is rendered within confirmation email: so it looks like that: http://example.com:8000/accounts/confirm-email/NA:1kcaUA:3NeRmjX502XujDEy_PmwHsV_rW3ioNjOvWcclXFBD5 is there any way to get rid of the port while sending those ? Thanks in advance.