Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
compatability of postgres and ms sql in django orm
guys. Our team have an issue, we are developing our django app on linux server with postgres, but in production we will need to use windows and MS SQL (don't say that bad idea, I know already. but we don't have other choice). Should we expect big problems when we transfer that app to windows and MsSQL stack ? Please write about your experience in such tasks if you did smth like that. -
Converting SQL to Django ORM query ("IF" statement inside of a "Window" inside of a "Lead" function)
I am trying to get the date of the next customer that started using a service and append that date to the previous customer. I was trying to wrap my head around how F() and Q() along with SQL-like functions work in Django, but couldn't wrap my head around how to convert the following SQL statement into valid Django code: SELECT *, LEAD( IF(actual_start IS NOT NULL, actual_start, planned_start) , 1) OVER( PARTITION BY customer ORDER BY actual_start, planned_start ) AS next_starting_time FROM builds_build; I tried mashing together some things that I saw: window = { "partition_by": [F('customer')], 'order_by': [F('actual_start'),F('planned_start')] } records = Record.objects.annotate( next_customer = Window( expression = Lead(F('actual_start') if F('actual_start') else F('planned_start'), **window) ) ) but, looking at the query, the conditional part of the LEAD expression was not taken into account (this is what the Django generated SQL looks like): SELECT *, LEAD(actual_start, 1) OVER( PARTITION BY customer ORDER BY actual_start, planned_start ) AS next_starting_time FROM builds_build; however, it is completely removing the intended "IF" statement. Any tips and thoughts would be highly appreciated -
Django auto_now_add adding default server time value
When i am creating a new Log object i want a created_at value with 'auto_now_add' but when i am creating it always saves with a default time. For example a log created at 2020-09-16 18:03 but when i check it it shows 2020-09-16 18:03. My models.py: class Log(models.Model): status = models.CharField(max_length=10) time_stamp = models.DateTimeField(auto_now_add=True) device = models.ForeignKey(Device, on_delete=models.CASCADE) My settings.py: TIME_ZONE = 'Europe/Istanbul' DATETIME_FORMAT = 'Y-m-d H:m' USE_I18N = True USE_L10N = False USE_TZ = False -
Altering filepath after deployment to Heroku
My app is for students who provide their ID CNIC to get their certificates. A function download in views.py needs to access an image (which is a blank certificate) modify it by adding name and graduation date associated with cnic save it as pdf make it available for download All works in development on localhost but when deployed to Heroku, the filepath to the image does not exist, which makes sense because the app is not local anymore - it accessible to anyone. The question is, how do we find the new path to access Certificate_0001.jpg which was initially stored in certificates\static\certificates Views.py def download (request, date, name): x = date.split(" ") date = f"29 {x[3]} {x[4]}" try: image = Image.open("certificates\static\certificates\Certificate_0001.jpg") except: return HttpResponse ("image did not load") font_type = ImageFont.truetype('arial.ttf', 70) font_type_2 = ImageFont.truetype('arial.ttf', 35) draw = ImageDraw.Draw(image) draw.text(xy=(600, 740), text=name, fill=(0,102,0), font=font_type) draw.text (xy=(330, 1230), text=date, fill=(0,102,0), font=font_type_2) try: image.save(f'certificates\static\certificates\{name}.pdf', "PDF", resolution=100.0) except: return HttpResponse("pdf did not save") try: with open(f'certificates\static\certificates\{name}.pdf', 'rb') as pdf: response = HttpResponse(pdf.read(), content_type='application/pdf') response['Content-Disposition'] = f'inline;filename=NFDP-{name}.pdf' return response except: return HttpResponse("pdf did not load") Settings.py import os import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware' … -
Why am I getting the "object has no attribute" exception in Django Rest Framework?
I hope someone can help me with this problem. I am getting the following exception: Got AttributeError when attempting to get a value for field identity_document on serializer NaturalProfileSerializer. The serializer field might be named incorrectly and not match any attribute or key on the NaturalProfileModel instance. Original exception text was: 'NaturalProfileModel' object has no attribute 'identity_document'. This is my code: models.py class IDTypeModel(models.Model): id_type_desc = models.CharField( null = False, blank = False, max_length = 50 ) class IDModel(models.Model): user_profile = models.ForeignKey( "NaturalProfileModel", on_delete = models.CASCADE, verbose_name = "Perfil de usuario" ) id_type = models.ForeignKey( "IDTypeModel", on_delete = models.CASCADE ) id_number = models.CharField( max_length = 15, null = False, blank = False ) class NaturalProfileModel(models.Model): user = models.OneToOneField( get_user_model(), on_delete = models.CASCADE ) first_name = models.CharField( max_length = 50, null = False, blank = False ) last_name = models.CharField( max_length = 50, null = False, blank = False ) serializers.py class IDSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='natural_profile_id-detail' ) class Meta(): model = IDModel fields = [ 'url', 'id_type', 'id_number', ] class NaturalProfileSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='natural_profile-detail' ) identity_document = IDSerializer(required = True, many = True) class Meta(): model = NaturalProfileModel fields = [ 'url', 'user', 'first_name', 'last_name', 'identity_document', ] def create(self, … -
Custom input field in django admin form
I want to display an extra input field in the model change view in django admin. I am overriding the get_from method in ModelAdmin to get the Form class # Customize field labels on lesson detail page here def get_form(self, request, obj=None, change=False, **kwargs): form = super().get_form(request, obj, **kwargs) from django import forms class Form2(form): extra_field_1 = forms.BooleanField() extra_field_2 = forms.DateTimeField() def save(*args, **kwargs): # custom logic to handle the extra input field value Form2.Meta.fields += ['extra_field_1', 'extra_field_2'] return Form2 but these new fields are now getting rendered in the change view page. Am I missing something here ? I tried adding extra field with an example ModelForm and it works not sure why its not working here -
Django - how to make my code infinitely working on backend
I'm trying to crawl the powerball data (each 3 and 8 minute, the data comes out. It is just like a normal lottery game) and show to my website. New numbers come out at each 3 and 8 minute. The code at the bottom checks the time every second. For example, at 2 pm 23 minute the timer will return True and it starts with login . After login, it starts to scrap the new data from the site. After 5minutes when the time becomes 28minute, it will start again with scraping, because it have been already logged in. what i want is, for the first time starting the program, it will scrap all the data before (only today's data) and add the data to the database. And each 3 and 8 minute, it will get the new data from the website and add it to the database. And when I get to the website, I'm watching the database data which is updated each 5minutes not by crawling each time I get to the site. Can anybody give me an idea or examples for this ? (I want to run the code at the backend with no disturbution and update … -
"yaml.scanner.ScannerError: mapping values are not allowed here in ".\docker-compose.yml", line 9, column 11"
I was executing Django app using docker I facing this above error I hope anyone could help docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 - .:/app ports: - "8000:8000" -
Update Object not Duplicate in views.py django
this is my code def createstock(request): stock = Stock() stock.title = 'AAPL' stock.div_ammount = '1' stock.save() return render(request, 'stocks/index.html') Whenever i call this this via URL. It creates the row in the database table. But i want to check that if stock.title = 'AAPL' this title is already in database then dont create object, only update its values. These values will be dynamic in future. But now its hardcore values. -
Diffrent Hosts wanna send cookie
When a user logged-in, a JWT is stored in the cookie. The cookie's domain is example.com. From now on, any request to example.com will be sent with cookies. However, cookies are not sent when I send a request to example.com:8000. So I tried the following. class ObtainJWTView(JSONWebTokenAPIView): serializer_class = JSONWebTokenSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): token = serializer.object.get('token') response = Response(token) if settings.JWT_AUTH_COOKIE: expiration = (datetime.utcnow() + settings.JWT_EXPIRATION_DELTA) response.set_cookie(settings.JWT_AUTH_COOKIE, token, domain=['example.com', 'example.com:8000'], expires=expiration, httponly=True, secure=True) return response return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Now I can't even save a token in the cookie anymore. How can I solve this problem? -
How to save python compatible audio file from JavaScript blob
I am trying to save an audio blob to the backend. Here is an audio blob const blob = new Blob(chunks, { 'type' : 'audio/wav; codecs=0' }); Here is the upload function function uploadAudio( blob ) { var reader = new FileReader(); reader.onload = function(event){ var fd = {}; fd["data"] = event.target.result; $.ajax({ // contentType:"application/x-www-form-urlencoded; charset=UTF-8", type: 'POST', url: 'testing/', data: fd, dataType: 'text' }).done(function(data) { console.log(data); document.getElementById("response").innerHTML=data; // alert(data); }); }; Here is the function to save the file. def upload_audio(request): print('upload_audio') if request.is_ajax(): req=request.POST.get('data') d=req.split(",")[1] print("Yes, AJAX!") #print(request.body) f = open('./file.wav', 'wb') f.write(base64.b64decode(d)) #f.write(request.body) f.close() return HttpResponse('audio received') When I try to read it in python for converting to text. I got following error ValueError: Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format I tried to convert the file import ffmpeg stream = ffmpeg.input('file.wav') stream = ffmpeg.output(stream, 'filen.wav') ffmpeg.run(stream) I got following error Traceback (most recent call last): File "script.py", line 8, in <module> ffmpeg.run(stream) File "C:\Anaconda3\envs\VA\lib\site-packages\ffmpeg\_run.py", line 320, in run overwrite_output=overwrite_output, File "C:\Anaconda3\envs\VA\lib\site-packages\ffmpeg\_run.py", line 285, in run_async args, stdin=stdin_stream, stdout=stdout_stream, stderr=stderr_stream File "C:\Anaconda3\envs\VA\lib\subprocess.py", line 729, in __init__ restore_signals, start_new_session) File "C:\Anaconda3\envs\VA\lib\subprocess.py", line 1017, … -
django issue in html as images are loading as zoom images
I am facing a weird problem, till yesterday the page was loading properly but after 2 days. the page is loading with images being zoomed.. (i.e. actual image size ) unable to figure out. main.html <!DOCTYPE html> {% load static %} <html> <head> <title>Ecom</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1" /> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> <script type="text/javascript"> var user = '{{request.user}}' function getToken(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getToken('csrftoken'); function getCookie(name) { var cookieArr = document.cookie.split(";"); for (var i = 0; i < cookieArr.length; i++) { var cookiePair = cookieArr[i].split("="); console.log('cookiePair:',cookiePair); if(name==cookiePair[0].trim()) { return decodeURIComponent(cookiePair[1]); } } return null; } var cart = JSON.parse(getCookie('cart')) if(cart == undefined) { cart = {} console.log('Cart was created'); document.cookie = 'cart=' + JSON.stringify(cart) +";domain=;path=/" } console.log('Cart:',cart); </script> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a … -
List of all database as well as tables available in sqlite3
I am trying to get the list of all the databases that I have in sqlite3. Here I am trying only to print all the databases name available to me and once clicked on a particular database, I will print all the tables available under that particular database. Here is my views code snippet: def analyzer(request): serv = sqlite3.connect(host = "localhost", user = "root", passwd = "abcdefg") c = serv.cursor() c.execute("SHOW DATABASES") l = c.fetchall() print (l) # l = [ i[0] for i in l ] # print (l) return render(request, 'analyzer.html') -
the KeyError: 1 problem , whats the problem?
in this code : for item in orderOFsssReserve: fforderOFsssReservefff=[] for item0 in orderDoubles1: if(item.studentidof== item0.userid): orders_student[j].setdefault(j, []).append(item0) break in the line of code : orders_student[j].setdefault(j, []).append(item0) i have this error : KeyError: 1 help me please -
Multiple requirements.txt files for django (production vs development)
I'm currently rewriting a few things and wanted to narrow down our requirements we use in production. We are primarily building Django projects/applications. Right now we use just one requirements.txt file in the project root that includes all installed libraries needed for both development and production. This requirements.txt file includes things like: pytest pytest-cov pytest-django flake8 factory-boy selenium Those things are never utilized on a production box... so it doesn't make sense to be installing them on production boxes. What is the best way to manage multiple requirements.txt files? Is it easiest to just rename them? production-requirements.txt development-requirements.txt Then just pip install production-requirements.txt on the production box? Are there other options? It seems trying to manage multiple .txt files would get old after a while when updating libraries and such. I've seen mention of Poetry - but that seems a bit like overkill for such a small use case such as this - or maybe it's just right thing? Trying to streamline things a little and reduce the amount of additional libraries we are loading in production where we don't need them vs. dev where we need them. Any/all help is welcome. -
Django - Creating & searching a custom user model
I have created my own custom user model, to override the built in one. # models.py class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email Originally, when I wanted to search the database, i would import from django.contrib.auth.models import User, and then do.. # create new user new_user = User() # Search existing users Users.objects.find() My question is, in a world where im now using my own custome user model, how do I do the equivalent? Do i have to from model import CustomUser and then use that instead? Thanks, -
How to safely redirect to HTTPS on Django app not behind a proxy?
essentially, I want to turn SECURE_SSL_REDIRECT to true. but reading through the django docs, I get the impression this can compromise the projects security if it's not behind a proxy. am I understanding that correctly, and if so, how should I go about doing http->https redirects when not behind a proxy? thanks! -
What frameworks should I choose for app development?
I’m currently learning Django and from what I understand Django is a backend language. The thing I can’t understand is that Django offers template rendering which in fact would be the front end part. Am I wrong here? Is there a way to use Django along with a frontend such as React or Vue? Also, what backend language would you recommend? I’ve read a lot about Java Spring and Ruby on Rails and am thinking of transferring to one of them. -
Update An Attribute in A Model (Table) Depending on the Previous Value of the Attribute Django
I have an attribute amount in some model Stock. If I want to set all the value of amount to 10 for all the rows, I will simply run: Stock.objects.update(amount=10) However, I want to update all the amounts in such way that 1 is added to all the amounts. So, something like this: Stock.objects.update(amount=amount + 1) which is not possible, off course. But, I need something like this. -
in my code i have the KeyError: 1 problem , whats the problem?
for item in orderOFsssReserve: fforderOFsssReservefff=[] for item0 in orderDoubles1: if(item.studentidof== item0.userid): orders_student[j].setdefault(j, []).append(item0) break im my code i have this error : KeyError: 1 help me please -
ProgrammingError at / relation "posts_post" does not exist LINE 1: ...evious_post_id", "posts_post"."next_post_id" FROM "posts_pos
I'm Sorry to ask again, but i haven't gotten any solutions. my django blog works fine locally but after deploying to heroku, i started having an error. the error states "ProgrammingError at / relation "posts_post" does not exist LINE 1: ...evious_post_id", "posts_post"."next_post_id" FROM "posts_pos..." please what can I do to resolve this? -
Cannot access my AWS Lightsail Django application from public IP
I am trying to host my Django application from my aws lightsail public IP. I have deployed my application to folder: /opt/bitnami/projects/spirit/spirit. and defined and activated the virtual host at /etc/apache2/sites-available/spirit-vhosts.conf. My spirit-vhosts.conf file is: <IfDefine !IS_spirit_LOADED> Define IS_spirit_LOADED WSGIDaemonProcess sample python-home=/opt/bitnami/python python-path=/opt/bitnami/projects/spirit processes=2 threads=1 5 </IfDefine> <VirtualHost 127.0.0.1:80 _default_:80> ServerAlias * WSGIProcessGroup spirit Alias /robots.txt /opt/bitnami/projects/spirit/static/robots.txt Alias /favicon.ico /opt/bitnami/projects/spirit/static/favicon.ico Alias /static/ /opt/bitnami/projects/spirit/static/ <Directory /opt/bitnami/projects/spirit/static> Require all granted </Directory> Alias /media/ /opt/bitnami/projects/spirit/media/ <Directory /opt/bitnami/projects/spirit/media> Require all granted </Directory> WSGIScriptAlias / /opt/bitnami/projects/spirit/spirit/wsgi.py <Directory /opt/bitnami/projects/spirit/spirit> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> However, i cannot access my website from public IP. I have also added port 8000 as custom TCP in my aws lightsail network rules. When i perform sudo wget 127.0.0.1:80 i do get the correct response in an html file. What am i missing? -
reset_value does not reset the value on reaching upper limit on get_next_value
The steps are as follows: from sequences import get_next_value, get_last_value get_next_value('nu', initial_value=0, reset_value=1000) l = [get_next_value('nu') for i in range(1001)] Can one help what is wrong here? The requirement is to generate a sequence of numbers and set the counter to the initial value after it reaches an upper limit. The library used is django-sequences -
Django does not retrieve static files
I need to work with Sql Server so I am using Django==2.1. However, I am encountering a problem with the static files. I have read previous posts but none of them seem to work in my case. Project Structure - A: Management Dashboard -- B: Main App ----- C: migrations ----- C: static ----- C: admin.py ----- C: apps.py . . ----- C: views.py -- B: Management Dashboard ----- C: settings.py ----- C: urls.py ----- C: wsgi.py -- B: templates -- B: db.sqlite3 -- B: manage.py My settings.py file looks like: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'MainApp.apps.MainappConfig', 'ManagementDashboard', ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' My base.html file looks like this: {% load static %} <html ln="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Management Dashboard</title> <!-- Bootstrap CSS CDN --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous"> <!-- Our Custom CSS --> <link rel="stylesheet" href="{% static 'css/style.css' %}" /> </head> <body> <div class="wrapper"> <!-- Sidebar --> <nav id="sidebar"> <div class="sidebar-header"> <h3>AVS</h3> </div> <ul class="list-unstyled components"> <p>Management Dashboard</p> <li class="active"> <a href="#homeSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle"><i class="fa fa-home" aria-hidden="true"></i> Home</a> <ul class="collapse list-unstyled" id="homeSubmenu"> <li> <a href="#">Home 1</a> </li> <li> <a href="#">Home 2</a> </li> <li> … -
Python function does not recognize argument
I'm trying to DRY my unittest code by aggregating some common object creation in a super class that inherits from Django TestCase class. Currently the object creation is in a child class directly inherited from TestCase. Currently: class ExperimentQuestionnaireTest(ExperimentTestCase): def setUp(self): super(ExperimentQuestionnaireTest, self).setUp() exec(open('add_initial_data.py').read()) self.user, self.user_passwd = create_user(Group.objects.all()) The script in add_initial_data.py creates the Group objects. To be: class ExperimentTestCase(TestCase): def setUp(self): super(ExperimentTestCase, self).setUp() exec(open('add_initial_data.py').read()) self.user, self.user_passwd = create_user(Group.objects.all()) class ExperimentQuestionnaireTest(ExperimentTestCase): def setUp(self): super(ExperimentQuestionnaireTest, self).setUp() The create_user function is in a separate file and in both cases it's called normally. But in the second case the argument Group.objects.all(), that is a QuerySet, is not passed to the create_user function. def create_user(groups=Group.objects.none(), username=None, force_password_change=False): # code goes here When calling create_user after the changes in To be section groups is getting the default parameter instead of the Group.objects.all() queryset. I didn't understand why this is happening. What I'm missing?