Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Download file specfic file
I have generated the file and saved in the following directory: project/media/ following code is setup, but not able to download the file from the media. Not able to download, Can you help, thank you Files are generated and upload to MEDIA folder, Inside the folder there are multiple files. VIEW.py file_list = ['file1','file2','file3'] def download(request): file_path = os.path.join(settings.MEDIA_ROOT, '/') response = "" if os.path.exists(file_path): for file in file_list: if 'data1' in request.POST and 'file1' in file: file_wrapper = FileWrapper(file(file_path,'rb')) file_mimetype = mimetypes.guess_type(file_path) response = HttpResponse(file_wrapper, content_type=file_mimetype ) response['X-Sendfile'] = file_path response['Content-Length'] = os.stat(file_path).st_size response['Content-Disposition'] = 'attachment; filename=%s/' % smart_str(file) return response HTML <form method="POST" id="data1"> {% csrf_token %} ... </form> <button id="data1" type="submit" name="download" class="card-link">Download</a> URL.py urlpatterns = [ path('download', views.download, name='download'),] -
django.db.utils.ProgrammingError: multiple default values specified for column "id" of table
I am 'Dockerizing' my Django project and I am facing the following issue when applying migrations on my container: django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "web_accountant" This is my model: from django.contrib.auth.models import User class Accountant(User): organization = models.ForeignKey(Organization, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now=True) I tried adding id = models.BigIntegerField(primary_key = True) as suggested in this post with no success. I also tried extending the Django User model another way (one to one field) but the error persists. What am I doing wrong here? -
ProgrammingError: relation " " does not exist
I am creating a web app using Django 2.2 and it is working in production on heroku with a couple of models already in place. Today I added in a third model, and I can still load the site in production but when I try to access a url that uses the third model I get the error as per the title. I have run python manage.py makemigrations and python manage.py migrate. The app also works perfectly in local host server, so it must have someting to do with the database on heroku? I'm using sqlite 3. error ProgrammingError at /calculus_tool/ relation "calctool_function" does not exist LINE 1: ...nction"."id", "calctool_function"."equation" FROM "calctool_... ^ Request Method: GET Request URL: ---REMOVED---(exists on my error page) Django Version: 2.2.3 Exception Type: ProgrammingError Exception Value: relation "calctool_function" does not exist LINE 1: ...nction"."id", "calctool_function"."equation" FROM "calctool_... ^ Exception Location: /app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py in _execute, line 84 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.8 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages', '..'] Server time: Fri, 16 Aug 2019 22:03:23 +0000 Views from django.shortcuts import render,redirect from django.http import HttpResponse # we can set post formats in the models directory from .models import Function # import post views … -
Model class django.contrib.sessions.models.Session doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
when I try to log-in Django admin panel using my superuser id & pass a runtime-error appears"Model class django.contrib.sessions.models.Session doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS." What to do ? I have tried adding 'django.contrib.sites', in INSTALLED_APPS & SITE_ID = 1 as shown in some solutions but it didn't work. my settings.py looks like this INSTALLED_APPS = [ 'newsfeed', 'user_profile', 'django.contrib.sites', 'Alumni_Portal.apps.AlumniPortalConfig', 'django.contrib.admin', 'django.contrib.auth', #'django.contrib.sites', 'django_extensions', 'django.contrib.contenttypes', #'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] SITE_ID = 1 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', ] ROOT_URLCONF = 'NSU_Alumni_Portal.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ``` -
Clean database in production
I successfully deployed my website on Linode on a Ubuntu server. I am using Postgres for database. I can perform all the actions correctly. However, I would like to clean my database (deleting all the users, posts, files, etc. that I created for my "in production" testing). I generally use: python manage.py flush when I want to clean my database of all of its elements (not tables) in development. Can I use the same command in production using the bash on my Ubuntu server? Or is there another way? -
How do I write a Django query with "icontains" and another condition?
I'm using Django and Python 3.7. I want to write a query that checks if the "created_by" column is not null and scans theh "title" field to see if it includes various words. I tried this def get_articles_with_words_in_titles(self, long_words): qset = Article.objects.filter(created_on__is_null=False, reduce(operator.or_, (Q(title__icontains=x) for x in long_words))) result = set(list(qset)) return result but I'm getting an error Positional argument after keyword argument Something about the way I have written my multiple conditions. What's the right way to write the conditions? -
How do I write a Django query that finds words in a Postgres column?
I'm using Django and Python 3.7. How do I scan for words in a Django query? A word is a string surrounded by whitespace (or the beginning or end of a line). I have this ... def get_articles_with_words_in_titles(self, long_words): qset = Article.objects.filter(reduce(operator.or_, (Q(title__icontains=x) for x in long_words))) result = set(list(qset)) but if "long_words" contains things like ["about", "still"], it will match Articles whose titles have things like "whereabouts" or "stillborn". Any idea how to modify my query to incorporate word boundaries? -
Questionnaire modeling
I am making a questionnaire app and am looking for a way to best represent a user answer. So far after looking at a bunch of survey apps online this is the general modeling I have come up with: A questionnaire is a collection of questions A questionnaire run associates a questionnaire with a user with a collection of answers taken at a certain time A question is a label, type and possible options An answer is a label, value and possible score, associated with a question, indicating whether it was defined by the user (to be used as an option for multiple choice question types or to store a user's text input answer) A run_answer associates a questionnaire_run and question with all the answers for that question and most importantly it associates an answer group which is needed for array/matrix type questions where the user can possibly add another of a particular type of question such as: "Add another medication" where every row added prompts the user to answer a series of questions related to the selected medication. So: which medication do you take?, how often is it taken?, How does it help?, etc... This way I know "How … -
Customizing user model and forms in django
I'm trying to set up a custom user using AbstractUser with a couple more added fields, but when I check the add user form in the site admin, the form fields appear in different order (password, groups and user permissions first, then the username, etc.) In my settings I have registered the AUTH_USER_MODEL to my custom User class. I have a user class with a cople of test fields, when I run it the fields appear in the order specified above. Then I created a CustomUserCreationForm and a CustomUserAdmin to try and order the fields, but then it only ended up showing only user and password. models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) forms.py from django.contrib.auth.forms import UserCreationForm from .models import User class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = User fields = ('username', 'email', 'password', 'bio', 'location', 'birth_date') admin.py from django.contrib import admin from .models import User from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm admin.site.register(User) #This one shows all the fields scrambled #admin.site.register(User, CustomUserAdmin) #This one only shows 3 fields on the creation (user, … -
dynamically place file in s3 when creating a new Model in Django
When I create a new model "Truck" in Django one of my fields is a FileField which saves files to S3. I want to place this file in a folder that matches my model instance. When I save a new instance of Truck, for instance "Red Truck" I want to upload the file to a folder in S3 called "Red Truck". This is for keeping documentation neat at my company. from django.db import models from django.db.models.signals import pre_save from django.dispatch import receiver from django.template.defaultfilters import slugify class Truck(models.Model): @staticmethod def pre_save(sender,instance,**kwargs): s3_truck_name = self.truck_number truck_number = models.CharField(max_length=20) vin = models.CharField(max_length=17) registration = models.FileField(upload_to=f'trucks/{s3_truck_name}') cab_card = models.FileField(upload_to=f'trucks/{s3_truck_name}') title = models.FileField(upload_to=f'trucks/{s3_truck_name}') def __str__(self): return f'Truck: {self.truck_number}' pre_save.connect(Truck.pre_save, Truck) NameError: name 's3_truck_name' is not defined -
Context manager to assert no database queries are issued in a block
How can I write a context manager that, in test/dev, asserts that there are no database queries in its block? The goal here is to force usage of select_related/prefetch related, and make it an error to forget to do so. Eg, given these models: class SomeSingleThing(models.Model): somefield = models.IntegerField() someotherfield = models.CharField(max_length=42) class SomeManyThing(models.Model): parent = models.ForeignKey(SomeSingleThing) This should raise an exception, because select_related is missing, and so a query gets performed inside the forbidden zone: obj = SomeSingleThing.objects.get(pk=1) with forbid_queries(): val = obj.parent.somefield # => exception And this should not, because we selected everything we needed: obj = SomeSingleThing.objects.select_related('parent').get(pk=1) with forbid_queries(): val = obj.parent.somefield # no exception -
How to get the Datetime when a task is marked as done in Django?
I'm developing a maintenance app, I can add tasks and get the exact time when it was created by implementing this: created_date = models.DateTimeField(db_column='Date', auto_now_add=True) # Field name made lowercase. I have a field called done: done = models.BooleanField(db_column='Done', default=False) # Field name made lowercase. Now what I need is to, when I set the done to 'True' it gives me the date and time at that moment, how can I achieve this? Thanks -
Django: filter by Date and time
I want to filter the queryset by date and time... I want to return all queryset that grater than or equal todays dateTime I try to do this and nothings happening self.request.user.date_created.filter(date_time__date__gt=datetime.datetime.now()) -
Getting manager of manager of an employee using django-auth-ldap
i need some help if someone run into the same problem i am having right now, as i have been asked to add support a login using Active Directory, i have managed to succeed the login process and the models creations of users, and now i want to populate some details from AD into the app database, i want to get the manager of manager of an employee, as i have been searching i found that the team lead N+1 field is named "manager" on ad so i have queried this using this command AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "Name", "email": "mail", "employee_manager": "manager", "employee_office": "physicalDeliveryOfficeName", "employee_cost_center": "extensionAttribute8" } The problem here is i got this in my database CN=TeamLeadName,OU=Users,OU=Tunis,OU=Care,OU=Corporate,DC=domain,DC=net so know i don't have any idea how to get only the name of the team lead and not the rest and from there how i can get the team of the team lead or in other word the initial employee manager. Any help will be so much appreciated. -
Django STATIC_URL on requests
I have this Django project (https://github.com/chakki-works/doccano) that I'm trying to deploy using Apache + mod_wsgi. I set up my .conf file to work as a Daemon proccess where application is served under an alias (/doccano) path: Alias /media/ /var/www/doccano/media/ Alias /static/ /var/www/doccano/app/staticfiles/ WSGIDaemonProcess doccano user=apache group=apache python-home=/var/www/doccano/env WSGIProcessGroup doccano WSGIApplicationGroup %{GLOBAL} WSGIScriptAlias /doccano /var/www/doccano/app/app/wsgi.py The application was doing fine while static files were not being served as I mapped /doccano alias: The Alias /static/ /var/www/doccano/app/staticfiles/ fixed static files problem. But I still want to serve other applications in this server, so mapping /static/ may not be a good idea. So I want to know what is the best approach for this situation. I was trying to add /doccano/ at the beginning of the static requests url setting STATIC_URL=/doccano/static/ but I think this property is not for doing this type of setting. -
http to https django project in nginx and port masking
I have server running in ngnix with host name https://mywebiste.com i have installed django project in folder(/home/mine/django_project/miniweb) and running in port 8090 by python manage.py runserver 0.0.0.0:8090 my service is working with http://mywebiste.com:8090 In my settings.py file i have added SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') How do i make it as https://mywebiste.com/miniweb i have 2 files ssl and default in /etc/ngnix/sites-enabled(i have proper ssl certificate and key file) and /etc/ngnix i have folders conf.g and other files. gone through few post and materials. added below code in ssl file and even tried in default file also but its not working. server { listen 80; server_name mywebiste.com:8090; rewrite ^ https://mywebiste.com/miniweb$request_uri? permanent; } server { listen 443; ssl on; ssl_certificate /etc/nginx/ssl/xxxxxxxxx.pem; ssl_certificate_key /etc/nginx/ssl/xxxxxxxxx.key; server_name mywebiste.com:8090; location / { uwsgi_pass mywebiste:8090; include uwsgi_params; } } Please i am very new to this. can anyone guide what to do here please. -
Django. Como consultar dos tablas en un mismo formulario?
Estoy haciendo una pequeña app para el control de escrutinio de las elecciones en el cual cargo las mesas donde se van a votas y los partidos politicos participantes. Para cargar la votacion necesito seleccionar la mesa y que me muestre la lista de los partidos politicos con el numero de lista y el nombre del partido. Estoy utilizando Dajngo 2.2 para el desarrollo de la app web. el archivo models.py de la app mesa es: class Mesa(models.Model): num = models.IntegerField(primary_key=True) escuela = models.CharField(max_length=100) el archivo models.py de la app partido es: class Partido(models.Model): lista = models.CharField(max_length=5, primary_key=True) nombre = models.CharField(max_length=100) pres = models.BooleanField() dip = models.BooleanField() Como puedo hacer para que me muestre lo que necesito? Muchas gracias!!! -
Django - split view.py to small files
I have big views.py where I have class based views and def views. It is possible to split it somehow to seal small files, so, for example, in one file I have only class based views, and in other file - functions -
submitting a form with multiple different buttons
I am trying to make a form that has three different submit buttons or inputs. I read that to do that I have to provide a name and a value attribute to the button. I already tried the button tag and input tag. But when I try to submit them and then print the POST request from within Django. nothing is printed. Only the csrf token is included with the POST request. This is the code I am trying. It only works when there is an input tag other than the submit type. but then I can't seperate them because any button will post everything in the form. THanks! <input type="submit" name="first_choice" value="first" class="btn btn-danger" > <input type="submit" name="first_choice" value="second" class="btn btn-info" > <input type="submit" name="first_choice" value="third" class="btn btn-success" > -
having the full field object instead of it's ID in django model
with these two models TblPhoto class TblPhoto(models.Model): #path = models.CharField(max_length=256) type = models.ForeignKey('TblPhotoTypes', models.DO_NOTHING, blank=True, null=True) path = models.ImageField(upload_to='images') def __str__(self): return str(self.id) class Meta: managed = False db_table = 'tbl_photo' verbose_name = "Photo" verbose_name_plural = "Photos" and TblCustomer class TblCustomer(models.Model): name = models.CharField(max_length=32) email = models.CharField(max_length=32) password = models.CharField(max_length=32) token = models.CharField(max_length=64, blank=True, null=True) firebase_token = models.CharField(max_length=64, blank=True, null=True) registration_date = models.IntegerField(blank=True, null=True) last_login_date = models.IntegerField(blank=True, null=True) about = models.TextField(max_length=128, blank=True, null=True) active = models.BooleanField(blank=True, null=True) photo = models.ForeignKey(TblPhoto, models.DO_NOTHING) def __str__(self): return str(self.id)+' : '+self.name class Meta: managed = False db_table = 'tbl_customer' verbose_name = "Customer" verbose_name_plural = "Customers" the api response is... { "response_status": { "code": 200, "internalMessage": "", "message": "" }, "user": { "id": 1, "name": "deya", "email": "3denator@gmail.com", "password": "e10adc3949ba59abbe56e057f20f883e", "token": null, "firebase_token": null, "registration_date": null, "last_login_date": null, "about": "hello, i'm Deya !", "active": true, "photo_id": 4 } } notice the field photo_id, how can I alter the TblCustomer model to show the photo object instead of the photo id? Disclaimer : I can do this easily out of the model, but I want it to be in the model class. -
Nested get or create functionality - DRF
There have been some posts about nested create functionalities however none seem to have helped me out. You can see here what my json post request looks like: { "games": [ { "company": { "name": "Google", "website": "https://google.com", "trustedpilot": "5" }, "genres": [], "formats": [], "platforms": [], "title": "Call of duty modern warfare", "cover": "https::cover.jpg", "link": "https://google.com", "prev_price": "60.00", "price": "40.00" } ], "company": { "name": "Google", "website": "https://google.com", "trustedpilot": "5" }, "name": "Bundle name", "prev_price": "50.00", "price": "20.00" } The game serializer seems the work fine when creating a single game: class GameSerializer(serializers.HyperlinkedModelSerializer): company = CompanySerializer(many=False) genres = GenreSerializer(many=True) formats = FormatSerializer(many=True) platforms = PlatformSerializer(many=True) class Meta: model = Game fields = '__all__' def create(self, validated_data): # Many to one company_data = validated_data.pop('company') # Many to Many genres_data = validated_data.pop('genres') formats_data = validated_data.pop('formats') platforms_data = validated_data.pop('platforms') # Company company, created = Company.objects.get_or_create(**company_data) # Get the game or created a new one if it doesn't exist yet game, created = Game.objects.get_or_create(**validated_data, company=company) # Platform for platform_data in platforms_data: platform, create = Platform.objects.get_or_create(**platform_data) game.platforms.add(platform) # Format for format_data in formats_data: format, create = Format.objects.get_or_create(**format_data) game.formats.add(format) # Genre for genre_data in genres_data: genre, create = Genre.objects.get_or_create(**genre_data) game.genres.add(genre) return game This is the … -
Passing List as Parameter in Python Requests
I generate a list of IDs, x = [1,2,3] from a set of records pulled from an API request. I then take this list and pass it as a parameter in a second API request which returns a set of records, y = [1,2] which are related to the first by foreign key. The problem I am having is that I need to return or assign a value for each ID in the list, as not every ID in the list has a corresponding record. Therefore, my two lists differ in size when I need them to be 1:1 for when I iterate through the data. How can I return some default value for when the query is false or how can I assign a value for when there is no corresponding record for a given ID? So as, x = [1,2,3] and y = 1,2,3] or x == y. Please let me know if any further information is needed. views.py def do_something(self, request): try: r = requests.get( self.URL + 'domain/endpoint in (' + request + ')', headers=self.Header) r.raise_for_status() except: print(r.text) raise return r.json() y = obj.do_something(x) -
Ubuntu server with Postgres - django.db.utils.OperationalError: fe_sendauth: no password supplied
I am deploying my Django website using Linode (using ubuntu for the server). I manage to create a virtual environment on my Linode server and push my application into it. Now, I want to test if it works, so I run on my server (not local machine): python manage.py runserver 0.0.0.0:8000 However, I get the error: django.db.utils.OperationalError: fe_sendauth: no password supplied On my localmachine, I used postgres: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'cocdb', 'USER': 'name', 'PASSWORD': '', # Yes, there is NO password 'HOST': 'localhost', 'PORT': '', } } I think the error is due to the fact that I did not create the postgres database on my Linode server. Is it correct? In order to do so, I plan to follow this guide: https://www.linode.com/docs/databases/postgresql/how-to-install-postgresql-on-ubuntu-16-04/ Access my linux server from Bash and activate my virtual enviroment sudo passwd postgres su - postgres psql -d template1 -c "ALTER USER postgres WITH PASSWORD 'newpassword';" I do not understand what 'template1' refers to createdb cocdb psql cocdb I am not sure if this is correct. What else should I do? a) Change the DATABASES in settings.py? If yes, how? b) My postgres USER in my localmachine is called name … -
How to view OpenCv in Django's Screen
Im planning to create a Web app system where i'm going to detect the vehicle's license plate no. using django and openv. The problem is, how to use django to livestream OpenCv? -
Many to Many in two directions
I have a friend that requested something that I was thinking would be simple and quick. It never turns out that way. Quick disclaimer, model design is a krux of mine. I often spend too long perfecting it only to have to rework it several times. Anyway, here is the current state of my model. For everything, it works, except when creating 'raids'. from django.db import models # Create your models here. class PlayerRole(models.Model): """ PlayerRole Model """ role = models.CharField(max_length=20) # this function will be invoked when this model object is foreign key of other model(for example Employee model.). def __str__(self): return self.role # this is a inner class which is used to define unique index columns. You can specify multiple columns in a list or tuple. class Meta: unique_together = ['role'] class PlayerClass(models.Model): """ PlayerClass Model """ name = models.CharField(max_length=100) color = models.CharField(max_length=6) # this function will be invoked when this model object is foreign key of other model(for example Employee model.). def __str__(self): return self.name # this is a inner class which is used to define unique index columns. You can specify multiple columns in a list or tuple. class Meta: unique_together = ['name'] class Player(models.Model): """ …