Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multi tables filter calculation
I have two tables: 1 - dates with user id: dateStart, dateEnd,userId 2 - users with allowedAmount: userid,allowedAmount I am trying to perform filter as following - return only the: (dateEnd-dateStart)/allowedAmount I know how i can filter as following qs = qs.filter(dateStart__range=[dateStart, dateEnd]) qs = qs.filter(dateEnd__range=[dateStart, dateEnd]) but i am struggling on filtering by the result of the above requirement using DJANGO's queryset filter any suggestions? -
Is it possible to capture a cache timeout in Django?
I would like to adopt the Django cache system to put an object in cache with let's say a 60 seconds timeout. Every time a cache hit happens such timeout is reset back to 60 seconds. This should work fine but the problem is that I would also like to do something when the timeout occurs. Is that even possibile with cache? -
How can i add upload size limit when upload image in django
i want to change user profile photo; However i don't know how can i add upload size limit views.py def profile_photo_upload(request): if request.method=="POST": form=UploadForm(request.POST, files=request.FILES,instance=request.user.profile) if form.is_valid(): userprofile=form.save(commit=False) userprofile.user=request.user userprofile.save() messages.success(request,"Success") else: form=UploadForm() return render(request,'imageupdate.html',{'form':form}) Also, is my code properly? for safety -
How should a view function to have a get that post data ? How to process user input and save it ? with view to each input processed/preprocessed?
So I'm working on an app where users can upload images and I can process the images using some libraries combined in a function.The basic outline is a view to show the uploaded images and a view for the processed images when the user enter the url/view of the processed image it should show the processed images of a single image. how can i make that possible ? should i make 2 data models one for the uploaded and the other for the processed ? i made a function for defining a user path for the image so as the user can process the image multiple times how can i make a function to define a new name/path to the processed image ? I saw basic code on gearheart where it looks something like this: #forms.py class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField() #views.py def handle_uploaded_file(f): with open('some/file/name.txt', 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file']) return HttpResponseRedirect('/success/url/') else: form = UploadFileForm() return render(request, 'upload.html', {'form': form}) so it should look like this but how to save the processed data in a different field/model to be … -
AuthenticationError at /admin/auth/user/add/
Hello am trying to add another user through the django admin and am getting this error You did not provide an API key, though you did set your Authorization header to "Bearer". Using Bearer auth, your Authorization header should look something like 'Authorization: Bearer YOUR_SECRET_KEY'. See https://stripe.com/docs/api#authentication for details, or we can help at https://support.stripe.com/ I cant figure a way to solve this please help out -
Promotheus - Django : connection refused
(This is my first time using Prometheus and I'm not very good with Docker/Django yet) I'm running a Django project in a docker container, and Prometheus with docker run -p 9090:9090 -v /tmp/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus In my docker-compose.yml I have: ... nginx-proxy: build: context: ./dockerfiles/nginx-proxy/ args: - DOMAIN_NAME=local.my.url ports: - "80:80" depends_on: - api - ... volumes: - ./volumes/nginx-front/log/:/var/log/nginx api: build: context: ./dockerfiles/api/ args: - GUNICORN_WORKERS=20 restart: always volumes: - ./volumes/api/src/:/usr/src/app ... In /tmp/prometheus.yml I have: global: scrape_interval: 15s evaluation_interval: 15s external_labels: monitor: 'iot-rocket-monitor' rule_files: scrape_configs: - job_name: 'prometheus' # metrics_path defaults to '/metrics' # scheme defaults to 'http'. static_configs: - targets: ['localhost:9090'] - job_name: 'api' # metrics_path defaults to '/metrics' # scheme defaults to 'http'. static_configs: - targets: ['api.local.my.url'] The prometheus job seems to work ok (but those aren't the metrics I'm interested in), the api gives the following error from the Promotheus UI: Get http://api.local.my.url:80/metrics: dial tcp 127.0.0.1:80: connect: connection refused However, when I type in http://api.local.my.url:80/metrics in my browser I can see the information correctly. I've tried replacing the URL with my IP address 10.25.2.192 but that doesn't change the result. I don't understand why it can't connect. -
Improve Django database performance by oriding or index?
I'm working on a project in which around 3 million records are saved in a MySQL database. The model is like: class Record(models.Model): rec_type = models.CharField(...) rec_value = models.FloatField(...) rec_prop1 = models.CharField(...) ...other fields... class Meta: ordering = ['rec_value'] A typical query contains a range of target rec_value, a specific rec_type, and sometimes, a specific rec_prop1. The query action is much more frequently used than the adding record action. My query function is written like this: def find_target(value_from,value_to,type=None,prop1=None): search_set = Record.objects.all() if type: #not None search_set = search_set.filter(rec_type=type) if search_set.count == 0: return [] if prop1: #not None search_set = search_set.filter(rec_prop1=type) if search_set.count == 0: return [] search_list = search_list.filter(rec_value__gte=value_from,rec_value__lte=value_to) result_list = [] for rec in search_list.values(...): #only get useful fields result_list.append(some_runtime_calculation_about_rec) return result_list The code works fine but takes around 7s for each query. No indexing is used currently. I want to improve query performance. I have searched the Internet for solutions and learned to use QuerySet.values() and database indexing. The problem is that rec_type field only has 3 possible values(eg. A, B, C), and the most of the records (around 70%) belong to one of them(eg. A). The rec_value field is filtered in every query so I made … -
Connectionerror - Elasticsearch
I am using Amazon elasticsearch service along with postgress. Elasticsearch works well with every Create, Update operations through django admin. But when I tries to delete from django admin I am getting, ConnectionError(<urllib3.connection.HTTPConnection object at 0x7f9371e200f0>: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7f9371e200f0>: Failed to establish a new connection: [Errno 111] Connection refused) I have checked many site but all i got is the syncying command, ./manage.py search_index --populate -f But this is not working. Is there any way which allows me to perform delete through django admin without disabling elasticseach service -
django.db.utils.OperationalError: FATAL: the database system is in recovery mode
I'm trying to spin up a database with the follwing commands on a mac: init_db: docker-compose run web python manage.py migrate docker-compose run web python manage.py creatersakey I'm getting an error: Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/usr/local/lib/python3.6/dist-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.6/dist-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.6/dist-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: the database system is in recovery mode The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/django/core/management/commands/migrate.py", line 87, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File … -
Testing if logged-in users see unpublished questions
I am writing tests for the django polls app tutorial. I want to write a test which which logs in a user, creates an instance of the question model with a publish date in the future, and ensures that this logged in user can see this question. I've tried using self.assertContains('Please review these unpublished questions: ') in the test method because my template looks like this: {% if user.is_authenticated %} <p>Hello, {{ user.username }}. Please review these unpublished questions: </p> {% if unpublished_question_list %} etc but even though self.assertEqual(response.context["user"], user) passes testing after self.client.login(username=my_admin.username, password=password) my template doesn't seem to be rendering properly to the test client. Some help would be much appreciated! AssertionError: False is not true : Couldn't find 'Please review these unpublished questions: ' in response -
HTMLCalendar in Django app: missing arguments
I am trying to replicate this Link in my Django app Views.py from calendar import HTMLCalendar from datetime import date from itertools import groupby from django.utils.html import conditional_escape as esc from django.shortcuts import render_to_response from django.utils.safestring import mark_safe class WorkoutCalendar(HTMLCalendar): def __init__(self, workouts): super(WorkoutCalendar, self).__init__() self.workouts = self.group_by_day(workouts) def formatday(self, day, weekday): if day != 0: cssclass = self.cssclasses[weekday] if date.today() == date(self.year, self.month, day): cssclass += ' today' if day in self.workouts: cssclass += ' filled' body = ['<ul>'] for workout in self.workouts[day]: body.append('<li>') body.append('<a href="%s">' % workout.get_absolute_url()) body.append(esc(workout.title)) body.append('</a></li>') body.append('</ul>') return self.day_cell(cssclass, '%d %s' % (day, ''.join(body))) return self.day_cell(cssclass, day) return self.day_cell('noday', '&nbsp;') def formatmonth(self, year, month): self.year, self.month = year, month return super(WorkoutCalendar, self).formatmonth(year, month) def group_by_day(self, workouts): field = lambda workout: workout.performed_at.day return dict( [(day, list(items)) for day, items in groupby(workouts, field)] ) def day_cell(self, cssclass, body): return '<td class="%s">%s</td>' % (cssclass, body) def calendar(request, year, month): my_workouts = Quiz.objects.orderby('scheduled_date').filter(owner_id=request.user.pk, my_date__year=year, my_date__month=month).annotate(c=Sum('weight')).values('c') print("my_workouts", my_workouts) cal = WorkoutCalendar(my_workouts).formatmonth(year, month) return render_to_response('classroom/teachers/graph_tot_trucks.html', {'calendar': mark_safe(cal),}) Urls.py path('abc/', teachers.calendar, name='cal'), foo.html <head> {{calendar}} </head> When I run this it results in calendar() missing 2 required positional arguments: 'year' and 'month' What is it that I am doing differently than the … -
How to use jinja tag inside jinja tag
this is my code {% if {{post.author.profile.image.url}} is None %}.When i run this code i get:Could not parse the remainder: '{{post.author.profile.image.url}}' from '{{post.author.profile.image.url}}' How to solve this?And how to use a jinja tag inside jinja tag -
pandas: How to get first positive number?
I have a pandas dataframe like: name a b c jack -10 -6 -10 bill -6 -3 -5 ray -3 -12 -9 pew 4 -23 -2 shaun 12 3 2 mitch 3 5 2 How can i make a new dataframe which takes the first positive value from each respective columns(a,b,c) and divides all the values in that column with that selected first positive value of that column and store the result of division in place of all the values. The output should look like this name a b c jack -10/4 -6/3 -10/2 bill -6/4 -3/3 -5/2 ray -3/4 -12/3 -9/2 pew 4/4 -23/3 -2/2 shaun 12/4 3/3 2/2 mitch 3/4 5/3 6/2 -
Extract data from ORM and group by Date
I have a function which data like this : my_workouts = Workouts.objects.order_by('my_date').filter( my_date__year=year, my_date__month=month) I want to do the same with another model where I want to group the weight by date: Models.py class Quiz(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='quizzes') scheduled_date = models.DateTimeField(max_length=255, default=0) weight = models.IntegerField(default=0) What I tried: data = Quiz.objects.orderby('scheduled_date'). filter(owner_id=request.user.pk,my_date__year=year, my_date__month=month). annotate(c=Sum('weight')).values('c') But this is not working, Please Help! -
How can I save my object in an other table?
I have this code : entryA = myTable1.objects.all().first() entryB = copy.deepcopy(entryA) But the problem is I would want to save entryB but if I do entryB.save() I will have a new entry in myTable1 whereas I want to have a new entry in myTable2 which contains the same fields. Could you help me please ? Thank you -
django join multiple tables via select_related()
I have three tables users, blocks, cars class User(models.Model): user_id = models.BigIntegerField(primary_key=True) is_out = models.CharField(default='N') birthday = models.DateTimeField() class Cars(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE, db_column='user_id', related_name='cars') title = models.CharField() sold_out = models.CharField(default='N') class Blocks(models.Model): user_id = models.BigIntegerField() target_user_id = models.ForeignKey(User, on_delete=models.CASCADE, db_column='target_user_id', related_name='blocks') I want to extract cars that is satisfied below condition. Cars that from user who is not is_out='N' Cars that doesn't sold out. (sold_out='N') Cars of users that does not exist in the target_user_id column of the blocks table related user_id=10000 To get cars that matched above condition, I wrote the query like this. blocks = Blocks.objects.filter(user_id=10000).values_list('target_user_id', flat=True) Cars.objects.filter(sold_out='N').select_related('user_id').filter(user_id__is_out='N').exclude(user_id__in=blocks) But as you know that, if blocks grows up, maybe there is performance issue occured. Question Is there any way to join blocks? Above query is best case? Any defect on my schema? Thanks. -
What tech stack to choose to download 9000 images in a webpage?
I have a website that will need to download 9000 photos, about 36,9 MB right after loading. I have a progress bar, so it is user friendly but I want this to be as fast as possible. I'm choosing between Python + Django and Java + Spring. I'm also choosing hosting and my choices are Heroku or Netlify. Which one of these are the best for what I want to achieve? The website will be exclusively used in Europe, Portugal. Thank you! -
How to store image in a variable in python?
How to store image in a variable in python.If i get answer with explanation it would be better.I tried searching in stackoverflow and google but didn't get? -
PythonAnywhere cannot get site to redirect without www
Whenever I try to access my pythonanywhere django site without "www." in front it redirects to the pythonanywhere "COMING SOON! This is going to be another great website hosted by PythonAnywhere." landing page. ALLOWED_HOSTS = [u'webapp-******.pythonanywhere.com', u'******.pythonanywhere.com', u'******.co.uk', u'www.******.co.uk'] Anyone encountered and solved this before? -
how do i install django in ubuntu 18.04
I am installing Django using pip command but its showing error the command used: pip install django showing error: ERROR: Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/pytz' Consider using the --user option or check the permissions. -
Unable to deploy django project on apache with virtualenv and mod_wsgi
I'm trying to run django project with mod_wsgi and apache.I have installed virtual environment and I included bps.conf file in /etc/apache2/sites-available. I couldnot run the project on browser. bps.conf image -
How to fix str object has no attribute '_meta'
I am migrating my model in Django project but error is being generated.Below is the code. What should be corrections in my code to solve this Models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #addtional portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(blank=True,upload_to="profile_pics") def __str__(self): return (self.user.username) Forms.py from django import forms from django.contrib.auth.models import User from basic_app.models import UserProfileInfo class UserForm(forms.ModelForm): password = User.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ['username','email', 'password'] class UserProfileInfo(forms.ModelForm): class Meta(): model = UserProfileInfo fields=['portfolio_site','profile_pic'] Admin.py from django.contrib import admin from basic_app.models import UserProfileInfo # Register your models here. admin.site.register('UserProfileInfo') I am getting Attribute Error: 'str' object has no attribute '_meta' -
the way to build forget_password api and save verification code
i try build api get_password this api send verification code to email and api save verification code in session, another way is save verification code on database not sessions, so what is the best way to do this ? -
How to access functions from ModelAdmin in template?
Lets assume a ConactAdmin for showing a ConactModel: class ContactAdmin(admin.ModelAdmin): change_form_template = "admin/contact_change.html" def my_custom_fnc(): return "Test" Now I want to access my_custom_fnc() in an view html my contact_change template like <p>{{my_custom_fnc()}}</p> Is there a list of properties which I can access in my own template? I couldn't find it in the documentation. -
Django: module not found while running in Docker container
I'm running a Django project in a Docker container, and I want to add a module (specifically, django-prometheus) I ran: pip install django-prometheus and docker run -p 9090:9090 prom/prometheus successfully, and I made the necessary alterations to my settings.py and urls.py files, as specified in the README I then rebuilt the project and restarted it, but it is giving me the error ModuleNotFoundError: No module named 'django_prometheus' (full error report: Traceback (most recent call last): api_1 | File "/usr/local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker api_1 | worker.init_process() api_1 | File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 129, in init_process api_1 | self.load_wsgi() api_1 | File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi api_1 | self.wsgi = self.app.wsgi() api_1 | File "/usr/local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi api_1 | self.callable = self.load() api_1 | File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load api_1 | return self.load_wsgiapp() api_1 | File "/usr/local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp api_1 | return util.import_app(self.app_uri) api_1 | File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app api_1 | __import__(module) api_1 | File "/usr/src/app/project/wsgi.py", line 16, in <module> api_1 | application = get_wsgi_application() api_1 | File "/usr/local/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application api_1 | django.setup(set_prefix=False) api_1 | File "/usr/local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup api_1 | apps.populate(settings.INSTALLED_APPS) api_1 | File "/usr/local/lib/python3.7/site-packages/django/apps/registry.py", line 89, in …