Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get a distinct value from Django queryset USING MYSQL
Does Someone knows how to get a distinct value in Django querySet? I'm using Mysql db and I couldn't find a solution yet. The table is: ID WORK_YMD LINE_NM MODEL_CODE MAG_NO PRODC_MAGT_NO 118002 20191015 PBA-21F BN94-14806W A656MAF00001 BR10BN9414806WA656MAE4035 118003 20191015 PBA-21F BN94-14806W A656MAF00001 BR10BN9414806WA656MAE4027 118004 20191015 PBA-21F BN94-14806W A656MAF00001 BR10BN9414806WA656MAE4039 118005 20191015 PBA-21F BN94-14806W A656MAF00001 BR10BN9414806WA656MAE4037 118006 20191015 PBA-21F BN94-14806W A656MAF00001 BR10BN9414806WA656MAE4038 I want to get the model_code considering a Filter mag_no = "My Variable" Ex:A656MAF00001 I tried something like this, but didn't work. Magazine.objects.filter(mag_no='A656MAF00001').get('model_code').distinct().order_by() The error is: "Too many values to unpack" -
Django Redis connection error in heroku: Error 110 while writing to socket. Connection timed out
I'm using Redis for caching in my Django project which is hosted on Heroku. During Redis connection, on random times I got the below error message Error 110 while writing to socket. Connection timed out. I'm using the below packages with versions python-3.6.8 Django-2.2.2 redis-3.2.1 celery-4.3.0 Also, I'm access Redis using worker ( celery sometimes). Can someone please suggest me to get rid of this problem or any other countermeasure to handle this problem. Thanks in advance... -
exception __str__ returned non-string (type bytes) in django
Trying to execute following methods where i get exception like exception __str__ returned non-string (type bytes). def __unicode__(self): return u"{}{:02d}:{:02d}:{:05.2f}".format( '-' if self.sign == -1 else '', self._deghour, self.minute, self.second) def __str__(self): return unicode(self).encode('utf-8') def __repr__(self): return u"RADecBase('{0}')".format(self) -
Model seems overdone for single boolean value (switch on/off)
I would like admin to be able to switch a certain feature on/off on the website. It seems overdone to build an entire model for this. Any suggestions? -
How could upload to my google drive by PyDrive in digitalocean server
right now i'm using email for attaching a file every week automatically, but as google not accepting files greater then 25MB i'm going to replace email attachment with google drive store as much as more scalable. I found this lib called PyDrive and I already follow mentioned steps in the documentation for configuration either in code and google account , but the issue is still google every time asking me for permission, is there any way for passing this process by code without asking for permission or any visual stuff because i'm going to upload files to digitalocean and there is no way for select an account or press allow without any visual access ? in other hand is there any way to configure it for digitalocean server ? BTW, the I'm uploading files to my own google drive not for customers here is quickstart.py : from pydrive.auth import GoogleAuth gauth = GoogleAuth() gauth.LocalWebserverAuth() # Creates local webserver and auto handles authentication. this is code (for testing) from pydrive.drive import GoogleDrive from quickstart import gauth drive = GoogleDrive(gauth) file1 = drive.CreateFile({'title': 'Hello_me.txt'}) # Create GoogleDriveFile instance with title 'Hello.txt'. file1.SetContentString('Hello World! me again') # Set content of the file from … -
How create env on heroku and install requirements?
I want to create a virtual environment for adding a custom language.I have a project that without a virtual environment, how to add a virtual environment -
why field name getting 'none' in django templates
I created templates page and retrieving data from the model for one field I am getting none and displays Class name of the model, template code: {% for abc in events %} <div> <h2><a href="">{{ abc.event_title }}</a></h2> <p>published: {{ abc.event_release_date }}</p> <p>{{ abc.event_description|linebreaksbr }}</p> <p>{{ abc.event_author}}</p> </div> {% endfor %} View code: def index(request): return render(request, 'polls/home.html', {}) "model class name and function name should not be samm" def Event(request): events=Events.objects.all() return render(request, 'polls/events.html', {'events':events}) -
Filter foreign key date django_filters
Currently my filter works so I can filter on name. However I also want to filter on releases (So display game that has release.date between a certain range) How can I do that? filters.py class ReleaseFilter(django_filters.FilterSet): date = django_filters.DateFromToRangeFilter(field_name='date') class Meta: model = Release fields = ['date'] class GameFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains') releases = ReleaseFilter() class Meta: model = Game fields = ['releases'] models.py class Game(models.Model): name = models.CharField(max_length=255) class Release(models.Model): game = models.ForeignKey(Game, related_name='releases', on_delete=models.CASCADE) date = models.DateField() -
Docker-compose on a django app postgresql connection refuse
i try to dockerize my django app, here my docker-compose.yml: version: '3' networks: mynetwork: driver: bridge services: postgres: restart: always image: postgres:11 ports: - "5432:5432" volumes: - ./data:/var/lib/postgresql/data web: build: . command: python /Code/core/manage.py runserver 0.0.0.0:8000 networks: - mynetwork ports: - "8000:8000" depends_on: - postgres inside my django app, in my settings.py i have this parameters for db connection: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydbname', 'USER': 'mydbuser', 'PASSWORD': 'mydbpassword', 'HOST': '127.0.0.1', 'PORT': '5432', 'OPTIONS': { 'client_encoding': 'UTF8', }, } } well at this point when i run docker-compose build al was done, but when i do: docker-compose up i get this error: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) web_1 | psycopg2.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "127.0.0.1" and accepting web_1 | TCP/IP connections on port 5432? how can i manage my django db connection parameters using my docker postgres image? So many thanks in advance -
not able to save data in django form
I am getting error Cannot assign "'1'": "dropdown.drp1" must be a "basedrop" instance. I am sharing my code. Kindly help. I got some solutions on stack but I did not understand how to implement that in my case. Django error. Cannot assign must be an instance models.py class basedrop(models.Model): name = models.CharField(max_length=50,blank=False,null=False) def __str__(self): return self.name class subdrop(models.Model): name = models.CharField(max_length=100,blank=False,null=False) bsdrop = models.ForeignKey(basedrop,null=False,blank=False,on_delete=models.CASCADE) def __str__(self): return self.name class lastdrop(models.Model): name = models.CharField(max_length=100,blank=False,null=False) sbdrop = models.ForeignKey(subdrop,null=False,blank=False,on_delete=models.CASCADE) def __str__(self): return self.name class dropdown(models.Model): name = models.CharField(max_length=50) drp1 = models.ForeignKey(basedrop,max_length=50,on_delete=models.CASCADE) drp2 = models.ForeignKey(subdrop,max_length=50,on_delete=models.CASCADE) drp3 = models.ForeignKey(lastdrop,max_length=50,on_delete=models.CASCADE) def __str__(self): return self.name views.py def create_drop(request): if request.method == 'POST': form = dropdownForm(request.POST or None) if form.is_valid(): form = dropdown(name=request.POST.get('name'),drp1_Id=int(request.POST.get('drp1')), drp2_Id=int(request.POST.get('drp1')),drp3_Id=int(request.POST.get('drp1'))) form.save() return HttpResponse('<p>this is working</p>') form = dropdownForm() return render(request,'drop.html',{'form':form}) -
Django - Add filter to PartialDate
I have date collected like PartialDate if date is complete, date is in english format ('yyyy-mm-dd') in my template I would like to convert this date into french format but considering the date can be partial if only year is known, I would like to see 2019 if only year and month areknown, I would like to see 10/2019 (convert 2019-10 to 10/2019) and if the date is complete, I would like to see 16/10/2019 (convert 2019-10-16 to 16/10/2019) I tried to add some logic in my template {% if participante.pat_nai_dat|length_is:"4" %} //do something {% elif participante.pat_nai_dat|length_is:"7" %} //do something {% else %} {{ participante.pat_nai_dat|date:"d/m/Y" }} {% endif %} but length_is and date filtesr do not work with PartialDate object I've read Django documentation to for more appropriate filter but did not find any my approach is probably wrong... how can I do this? -
Delete multiple Django objects via ORM [duplicate]
This question already has an answer here: Delete multiple objects in django 1 answer Is it possible to delete many Model instances without iterating over them and calling .delete() on each one? Let's say we have something like this: objects = [o for o in MyObject.objects.filter(...)] objects_to_delete = get_validate_objects(objects) # some of objects from objects And now I want to delete every MyObject in objects_to_delete. Is there any better/smarter way than this?: for o in objects_to_delete: o.delete() -
Sort django rest framework paginated list by date in vue
A list of items needs to be sorted (ASC and DESC) by date on click. This list of items is paginated by Django Rest Framework Pagination. Therefore, the first page of items contains just 15 results. The default sorting is newest date first. Whenever the list is sorted, the current state is sorted by .sort(), through a mutation in Vue. This works, however, just for the current state which only contains the list of items that are in the first page (assuming the user didn't go to next page). This causes the order only to be valid for the results per page, but not for all results. To solve this, I could do an API request to return the results in the correct order, but my question is, is there a smarter way to do this? -
Django error page with DEBUG=True much more detailed than logging
While DEBUG=True in settings.py, any Python error is shown in a page where I can see not only the traceback but also every local variable at the moment of the exception. How can I have such a detailed traceback with local variables in my log files, when DEBUG=False? I've tried this in settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, 'file': { 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'logs', 'django.log'), }, }, 'loggers': { 'django': { 'handlers': ['file', 'console'], 'level': 'DEBUG', }, 'django.template': { 'handlers': ['file', 'console'], 'level': 'INFO', }, 'app': { 'handlers': ['file', 'console'], 'level': 'DEBUG', }, } But the only thing that I get in my log file and in the console are the standard Python traceback's, devoid of any detail. I don't want to know only which line of code caused the error: I also want to know variables values. -
django.db.utils.InterfaceError:('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) )
I have a Django web app with azure sql server,i move the code from one laptop to another and suddenly i got django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') imidatly after starting the web server I have been able to isolate the problem , and realized it coming from the db connection in setting.py , i tried to run simple python quay from the console and it worked I tried all the solutions i saw online with no luck Any ideas? DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'XXXXXX', 'Trusted_Connection':'No', 'HOST' : 'XXXXXXXXXXX', 'DRIVER': '{ODBC Driver 17 for SQL Server}', 'OPTIONS': { 'extra_params': 'APP=Setting.py', }, 'AUTOCOMMIT' : True , 'USER' : 'XXXXXXX', 'PASSWORD' : 'XXXXXXX' }} -
Django apps throw ImportError on Heroku
I'm deploying a Django application to Heroku. This application runs locally, and was built as a structural clone of django-vue-template. The only notable changes being: I have more apps in my project. I do not use a settings package with prod/dev modules, just single module. File structure: The error I get in the build log throws an ImportError on 'users', but its not app-specific, its whatever app is the first Django app in my INSTALLED_APPS. -----> $ python manage.py collectstatic --noinput PYTHONPATH: . BASE_DIR /tmp/build_1803d0c0cef716d3bc64a04ddb7b7ea0/backend Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'users' ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can … -
My application container is not able to my mysql container
After all of web searching and coming up of no answer to this, I thought of asking this question on this platform. I had an application container which i try to connect with mine database container but due to reasons unaware mine application is not able to connect. I am providing all the relevant information required for it. Here is mine docker-compose file version: '2' services: application: &application image: gmasmatrix_application:latest command: /start.sh volumes: - .:/app depends_on: - db ports: - 8000:8000 # cpu_shares: 874 # mem_limit: 1610612736 # mem_reservation: 1610612736 build: context: ./ dockerfile: ./compose/local/application/Dockerfile args: - GMAS_ENV_TYPE=local db: image: mysql:5.7.10 environment: MYSQL_DATABASE: gmas_mkt MYSQL_ROOT_PASSWORD: pulkit1607 ports: - '3306:3306' volumes: - my-db:/var/lib/mysql volumes: my-db: I also changed the host in the settings.py file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'gmas_mkt', 'USER': 'root', 'PASSWORD': 'pulkit1607', 'HOST': 'db', 'PORT': '3306', } } Here is the error I get upon running the docker-compose up file application_1 | Traceback (most recent call last): application_1 | File "manage.py", line 22, in <module> application_1 | execute_from_command_line(sys.argv) application_1 | File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line application_1 | utility.execute() application_1 | File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 346, in execute application_1 | self.fetch_command(subcommand).run_from_argv(self.argv) application_1 | File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 394, … -
Error while creating a superuser on heroku with django
I've created an app,called learning logs, on heroku (it is an project from the book python crash course).When I try to create a superuser it shows me an error. I first run (in a termial): heroku run bash and then : python manage.py createsuperuser the main error is the following: You have 20 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, learning_logs, sessions. Run 'python manage.py migrate' to apply them. Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: auth_user The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) the rest of the error is this: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 61, in execute return super().execute(*args, **options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 82, in handle default_username = get_default_username() File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/auth/management/__init__.py", line 140, … -
How to make django not to ask for migrations?
When I run my Django project. It prints the following: You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. I'm using raw queries and not using admin and models feature. So migrations will not be of any use for me. How can I make Django to not ask for applying migration? -
Django get ManyToMany variable in template
i have to models linked with ManyToMany relation: class Event(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) title = models.CharField(max_length=512) class Task(models.Model): event = models.ManyToManyField(Event, blank=True, related_name='tasks') description = models.CharField(max_length=1000, blank=True) in view.py i collect all user events by: events = Event.objects.filter(user=request.user) now in template i want to display each event in loop with event-task.description {% for event in events %} {{event.title}} {{event.task.description}} ??? {% endfor %} How to get this work? Related questions: link_1, link_2 -
Unit testing a function which consumes request from django rest api view
I'm not sure what's the proper way to test functions which are used inside views/permission classes. This is the payload of my request: {"name": "John"} And this is the function I want to test: def get_name(request): return request.data['name'] This is the view that will be using the function: class SomeView(APIView): def get(self, request): name = get_name(request=request) return Response(status=200) How should I create a fixture to test the get_name function? I've tried this: @pytest.fixture def request_fixture() factory = APIRequestFactory() return factory.get( path='', data={"name": "John"}, format='json') def test_get_name(request_fixture): assert get_name(request=request_fixture) == "John" But I'm getting an error: AttributeError: 'WSGIRequest' object has no attribute data. One workaround seems to be decoding the body attribute: def get_name(request): data = json.loads(request.body.decode('utf-8')) return data['name'] But it doesn't feel like the right way to do this and I guess I'm missing something about the WSGIRequest class. Can someone explain to me how it should be tested? It would be great if I could use the same fixture to test the view too. -
drf-yasg how to display the api description outside?
I want the describe in there: but mine is in there: This is my code: @swagger_auto_schema(method='GET', manual_parameters=[project_param]) @api_view(['GET']) def get_project_info(request): """ 获取项目信息 """ Version info: Django==2.2.1 drf-yasg==1.16.1 -
Is there a way to annotate django query with non-expression?
I have use case where I need to get all objects where existing_field is the beginning of some string. some string changes dynamically so I need a smart way to filter out objects. My idea is to create annotated query like this: MyModel.objects.annotate(annotated_field='some string').filter(annotated_field__startswith=F('existing_field')) Currently it is failing with: QuerySet.annotate() received non-expression(s): some string Is there a way to annotate objects with string value? -
What is equivalent library of cStringIO in python 3? [duplicate]
This question already has an answer here: python 3.x ImportError: No module named 'cStringIO' 2 answers Currently I am converting my python2 project into python 3 & came up code related to cStringIO module. import cStringIO buffer = cStringIO.StringIO() I know that import StringIO been replaced with from io import StringIO but what will be similiar code in python 3 for CStringIO. -
Django Rest frame work "CSRF Failed: CSRF token missing or incorrect." error on JSONWebTokenAuthentication
I want to send a POST request using POSTMAN and my url is like http://127.0.0.1:8000/restaurant/article/update/23 On login I am sending a token which is Json web token (created like this) https://jpadilla.github.io/django-rest-framework-jwt/#creating-a-new-token-manually def get_token(user): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) return jwt_encode_handler(payload) And on login my api response is like { "success": true, "message": "Successfully logged in", "data": { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyLCJ1c2VybmFtZSI6IkRlbW9AZ21haWwuY29tIiwiZXhwIjoxNjAyNzU1MDE4LCJlbWFpbCI6IiJ9.sgLS4NofzDtdUSHYvuepRruw2PgTPLyGCdjIOiLdrkw", "restaurant": { "id": 1, "image": "/media/Restaurant/Entertainment.jpg", "restaurant": "Demo", } } } when I am using this token like this in post man its not working BUT token provided in post man cookie when I use that it works like this .What's going on here ? any help would be highly appreciated.