Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error hosting Django on Elastic beanstack; 404 not found
I follows tutorial on AWS https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html When I do eb open on cmd, it open new link but got error as The requested URL was not found on this server. I have make sure that ALLOWED_HOSTS = ['*'] -
Fixtures data for model containing images and files
I am using Djano 3.1, Python 3.6 and easy-thumbnails 2.7 I want to create a fixtures data file for my model. Here is my (simplified) model: myapp/models.py class Post(models.Model): featured_image = ThumbnailerImageField(upload_to='uploads/post/featured_image', blank=True, null=True) content = models.CharField(max_text=1000, null=False, blank=False) class PostFileAttachment(models.Model): post = models.ForeignKey(Post, related_name='attachments', on_delete = mFixtures data for model containing images and filesodels.CASCADE) file = models.FileField(upload_to="uploads/post/attachments") class PostImageGallery(models.Model): post = models.ForeignKey(Post, related_name='pictures', on_delete = models.CASCADE) description = models.CharField(max_length=100, blank=True, null=True, default='') image = models.ImageField(upload_to='uploads/blogpost/gallery') myapp/fixtures/sample_data.json [ { "model": "myapp.Post", "pk": 1, "fields": { "featured_image": ??? "content": "This is where the content goes" } }, { "model": "myapp.PostFileAttachment", "pk": 1, "fields": { "post": 1 "file": ??? } }, { "model": "myapp.PostImageGallery", "pk": 1, "fields": { "post": 1 "description": "File description", "image": ??? } } ] How do I specify files in my JSON fixtures file? -
django.db.utils.OperationalError: could not translate host name "postgis-container" to address
I am trying to build an image in django that will later be deployed on a digitalocean droplet with my own domain name. I am currently trying to get rid of an issue that I believe is affecting my progress in relation to my local postgis container. I have a container named: postgis-container in the network: awm. After I run: python manage.py makemigrations I get the error: django.db.utils.OperationalError: could not translate host name "postgis-container" to address: Temporary failure in name resolution I was told by my lecturer to use the network alias for the ALLOWED_HOSTS field in my settings.py but it didn't make any difference. I put a comment to the right hand side of the possible offending line. settings.py """ Django settings for AdvancedWebMapping project. Generated by 'django-admin startproject' using Django 3.1.3. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os import socket from pathlib import Path import docker_config from whitenoise.storage import CompressedManifestStaticFilesStorage # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used … -
Form Handling CBV Django
I am learning Django, and have stumbled upon a problem while using a CBV approach. I have two forms(one for posts, and one for comments), and two classes (both use CreateView) for each form and I am trying to allow users to comment, on the same template where the posts are listed. However, whenever I post a comment, my Post class's form_invalid function is triggered, and a "This field is required" pops up. Is there a way to override this, or a specific way to handle multiple forms in a single template? I understand that code is necessary to efficiently answer these types of question, but because this is a school project I am hesitant in posting code... -
Can't deploy to Heroku because heroku is running latest version of Django (i.e. 3.1.1)
I am running Django 2.2.3 and Python 3.6 locally. Everything is working fine locally until I deploy to Heroku then I get the error below.enter image description here I think the problem is caused by the mismatch in Django versions (i.e. my local version and heroku's version). I don't know how to solve this issue without upgrading my local version. I am afraid if I upgrade I am suddenly going to have all sorts of errors. How can I solve this? -
Using post form to update Django ListView
Context I would like to use a POST form to update the queryset for my CardListView. I have looked at other posts describing how you would do it using GET, althought I would like to implement it using POST. My current code successfully updates the view based upon what the user enters into the form. However, I am having an issue with pagination and URLs. Problem If I have navigated to another page in the list view, say page 2, my URL becomes: http://localhost:8000/cards/?page=2. Then, if I submit the POST form on this page, my URL doesn't get updated to http://localhost:8000/cards (i.e. it stays as http://localhost:8000/cards/?page=2) and therefore if there are no results on page 2 as a result of the search form, I get a Page not found (404) error. I have realised this is because of the way I return in my post() method. I use render() rather than redirect(), but I can't seem to get the form to work with redirect(). I have tried figuring out how to hard code the paginator page object within my post() method, although that does not change the URL "?page=2" so it didn't help. Here is the relevant code: CardListView class … -
How to write test for views which create multiple DB objects?
There is transaction table in my database, i've API which create multiple transaction rows in database on single request, i've write code to test the API but somehow it fails following is my code Here is my View: class CreateMultipleTransactionAPIView(APIView): """create multiple transactions""" def post(self, request): """handling post request""" serializer = TransactionSerializer(data=request.data, many=True) if serializer.is_valid(): serializer.save(user=self.request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) here is my test code which is failing: def test_create_multiple_transactions_errors(self): url = reverse('transaction_apis:create_multiple'); request_data = {'items': [{}]} response = self.client.post(url, request_data) print(response.content_type) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) Ouput after running test: self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) AssertionError: 201 != 400 -
Django Rest API get many to many relationship with two Models
I want to have an API that returns recipes. At the moment it can return the recipes without the ingredients and the ingredients without the recipe, this is because the ingredients are in a different table. Now I want to get the recipes but also with their ingredients. My models.py: class Ingredients(models.Model): ingredientid = models.AutoField(db_column='IngredientID', primary_key=True, blank=True) recipeid = models.ForeignKey('Recipe', models.DO_NOTHING, db_column='RecipeID', blank=True, null=True, related_name='+') amount = models.CharField(blank=True, null=True, max_length=100) unit = models.CharField(blank=True, null=True, max_length=100) unit2 = models.CharField(blank=True, null=True, max_length=100) ingredients = models.CharField(db_column='Ingredient', blank=True, null=True, max_length=255) class Meta: managed = False db_table = 'Ingredients' class Recipe(models.Model): recipeid = models.AutoField(db_column='RecipeID', primary_key=True, blank=True) # Field name made lowercase. title = models.CharField(db_column='Title', blank=True, null=True, max_length=255) # Field name made lowercase. preperation = models.TextField(db_column='Preperation', blank=True, null=True) # Field name made lowercase. images = models.CharField(db_column='Images', blank=True, null=True, max_length=255) # Field name made lowercase. ingredients = models.ManyToManyField(Ingredients) class Meta: managed = False db_table = 'Recipes' I know that I have to add something in the Recipes model but I don't know what in order to get just the ingredients with the recipe id of the recipe. I tried this: ingredients = models.ManyToManyField(Ingredients) but this didn't work. In my serializer.py I tried something like this: class FullRecipeSerializer(serializers.ModelSerializer): … -
not able to paginate by the number of objects provided
So pagination isn't working even without initiating django-filters from templates, I'm not able to paginate by the number of objects I want, it's showing all of them at once Note: I'm not saying both should work together, just that I wanna fix the pagination views.py def music_page(request): #pagination & filter music = Music.objects.all().order_by('-id') music_filter = MusicFilter(request.GET, queryset=music) paginator = Paginator(music, 6) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) try: music = paginator.page(page_number) except PageNotAnInteger: music = paginator.page(1) except EmptyPage: music.paginator.page(paginator.num_pages) return render(request, template_name='main/music.html', context={'music': music, 'page_obj': page_obj, 'filter': music_filter}) template <div class='card'> {% for m in filter.qs %} <div class='year'>{{m.Year}}</div> <div class='song_name'>{{m.song}}</div> {% endfor %} </div> -
Fixtures file for Taggable model using django-taggit
I am using Django 3.1, django-taggit 1.3 and Python 3.6 I want to create a fixtures file for the following model myapp/models.py class Foo(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, null=False, default=1, tags = TaggableManager() myapp/fixtures/foo_data.json [ { "model": "myapp.Foo", "pk": 1, "fields": { "author": 1, "tags": ['foo','foobar','foofoo'], } }, ] When I run ./manage.py loaddata foo_data.json, I get the following error message: django.core.serializers.base.DeserializationError: Problem installing fixture '/path/to/myapp/fixtures/foo_test_data.json': ['“foo” value must be an integer.']: (myapp.Foo:pk=1) field_value was 'foo' -
Django database router - apps are not exclusive in database
I'm trying to set up a database router with the help of the django docs from here: https://docs.djangoproject.com/en/dev/topics/db/multi-db/#topics-db-multi-db-routing Currently i have two databases: - default # remote database (in production) - local # local database settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'webapps', 'USER': 'webapps', 'PASSWORD': 'password', 'HOST': '127.0.0.1', }, 'webapps_local': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'webapps_local', 'USER': 'webapps_local', 'PASSWORD': 'password', 'HOST': '127.0.0.1', } } DATABASE_ROUTERS = ['path_to.db_routers.DbRouter'] Now i want all apps listed in route_apps_local_labels to be only in database local and all other apps to be only in database default db_routers.py class DbRouter: """ A router to control all database operations on models listed in route_apps_local_labels to use DB 'webapps_local'. Apps not listed in route_apps_local_labels will use default database 'webapps' """ route_apps_local_labels = {'meeting',} def db_for_read(self, model, **hints): """ Attempts to read route_apps_local_labels models go to webapps_local. """ if model._meta.app_label in self.route_apps_local_labels: return 'webapps_local' return None def db_for_write(self, model, **hints): """ Attempts to write route_apps_local_labels models go to auth_db. """ if model._meta.app_label in self.route_apps_local_labels: return 'webapps_local' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the route_apps_local_labels apps is involved. """ if ( obj1._meta.app_label in self.route_apps_local_labels or obj2._meta.app_label in self.route_apps_local_labels ): return … -
What is the usage of **Kwargs in django
What is the use of **kwargs in a class based view i.e get_success_url(self, **kwargs) in Django. All I understand is that it is a parameter of a function. -
Trying to have an anchor tag that renders to an edit.html using Django but having problem writing the parameters to link to the template
Urls.py from django.urls import path from . import views path('edit/int:user_id', views.edit), on views.py def edit(request, user_id): context = { 'edit':User.objects.get(id=user_id) } return render(request, 'edit.html', context) on the template a href="edit/{{ request.session.user.id }}">Edit</a (I know the a tag is not closed or open but need you to see the the parameters) -
Using Celery with Django: How do you save an object inside of a task?
I have a Django project and have set up a Celery worker. I have a test Task in which I attempt to create and save an object to the database: def get_genome(): return Genome(genome_name='test-genome2', genome_sequence='AAAAA', organism='phage') @shared_task def test(): sleep(10) g = get_genome() g.save() I call the task in a view using test.delay(). The sleep command and the get_genome commeand executes within the celery worker however calling .save() returns the following error: [2020-11-09 10:53:09,131: ERROR/ForkPoolWorker-8] Task genome.tasks.test[cdd748a9-f889-4dae-bec6-3f869f96daf9] raised unexpected: TypeError('connect() argument 3 must be str, not None') Traceback (most recent call last): File "/home/daemon/miniconda/envs/mas/lib/python3.8/site-packages/celery/app/trace.py", line 409, in trace_task R = retval = fun(*args, **kwargs) File "/home/daemon/miniconda/envs/mas/lib/python3.8/site-packages/celery/app/trace.py", line 701, in __protected_call__ return self.run(*args, **kwargs) File "/home/daemon/MAS/genome/tasks.py", line 14, in test g.save() File "/home/daemon/miniconda/envs/mas/lib/python3.8/site-packages/django/db/models/base.py", line 753, in save self.save_base(using=using, force_insert=force_insert, File "/home/daemon/miniconda/envs/mas/lib/python3.8/site-packages/django/db/models/base.py", line 790, in save_base updated = self._save_table( File "/home/daemon/miniconda/envs/mas/lib/python3.8/site-packages/django/db/models/base.py", line 895, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "/home/daemon/miniconda/envs/mas/lib/python3.8/site-packages/django/db/models/base.py", line 933, in _do_insert return manager._insert( File "/home/daemon/miniconda/envs/mas/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/daemon/miniconda/envs/mas/lib/python3.8/site-packages/django/db/models/query.py", line 1254, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/home/daemon/miniconda/envs/mas/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1395, in execute_sql with self.connection.cursor() as cursor: File "/home/daemon/miniconda/envs/mas/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/daemon/miniconda/envs/mas/lib/python3.8/site-packages/django/db/backends/base/base.py", line 259, in … -
Should I have React as a SPA and Django as a REST API or should I have the React inside Django?
So I have been researching this for a while and I honestly feel like I am going in a loop. I am creating a website for customers to view & unlock discounts. Originally, I wanted the React and Django to be completely separate. The reasoning for this is that in the future, I would like to create an Android & iOS application and it would be much easier to only create the front-end for them and connect it to the Django REST Api to fetch data from my PostgreSQL database. However, with further research it seems that it's recommended to have React inside Django due to making use of Django's user authentication? The argument is that it is too hard and also a bit of a security risk to handle the authentication yourself. (Django REST with SPA - what structure). Also I would have to worry about deploying 2 servers but I'm not sure what issues this could cause. So I found this library which helps with JWT authentication. If I was to use this library would my application be "safe"? I am not a security expert and I am the only developer working on this so I am a … -
python 2 for loop not working with list after using sorted()
I think I faced a weird behavior with python 2.7 for loop. Here is the code: events = Event.objects.filter(event_data__xpos=int(xpos), event_data__ref=ref, event_data__alt=alt, event_data__family_id=family_id) events = sorted(events, key=lambda e: get_date_from_event(e), reverse=True) for e in events: logger.info(e) def get_date_from_event(event): from_zone = tz.tzutc() to_zone = tz.gettz('America/New_York') date_saved = parser.parse(event.event_data['date_of_event']) date_saved = date_saved.replace(tzinfo=from_zone) date_saved = date_saved.astimezone(to_zone) return date_saved Event is a Django model with event_data JSONField where all the data is stored. I get a QuerySet with 2 results, then I use sorted and the following list is there: [<Event: Event object>, <Event: Event object>] I checked its type and it is list, and len and it is equal 2. But the for loop does not work, there is no iteration happens since logger prints nothing. -
How to have Django `manage.py test` recognize pytest test method that has no unittest base class?
I'm running parallel unittesting using Django 's manage.py test command. The issue is that this command only recognize the unittest-way test method - for those that has the pytest-way eg no test class and have fixture param, manage.py test will skip them. So my question is how to get manage.py test collect the pytest-way test methods? -
Did django compile views.py everytime a view is requested?
i'm working on a django project and in views.py i need to use an external class for doing some stuff. If i declare the reference of the class, like: class = MyClass() in the top of views.py. Did django need to instantiate the class everytime a view is requested? Or it uses the same instance for all the views(this is what i want)? What i want to achive is to have this external class that is very slow to initialize (4-5 seconds), and use it in one view for all the users... like: def myview(request): # ... some code ... output = class.doSomeStuff() # ................. -
Is it possible to connect a Django back-end to a SparkSql database? [closed]
I'm trying to connect a SparkSQL database to a Django back-end, which uses the Django Rest Framework. I've read Django documentation and learned that Django doesn't apparently support SparkSQL. The purpose of this connection os to access a database that aggregates information, which is then to be retrieved and displayed on dynamic tables on our front-end. So far, I've managed to do this with other databases (PostgreSQL and SQLite) and I've looked at the documentation for SparkSQL, PySpark, and even how to connect to Hive, but to no avail. Some years ago, I have implemented a solution that connected to this same database and then retrieved the information we needed. However, the back-end at the time was written in Java. Is it possible to connect a Django back-end to this sort of database? If so, what would you suggest? Thanks in advance! -
How to see the logs from docker? using django background_tasks
I'm running django background_tasks in the background with a docker container. The dummy tasks run smoothly @background(schedule=30) def dummy_backgrountask(**kwargs): print("running...") logger.debug('logger shows running 1.2..3....') print (kwargs) in docker: tasks_django: build: context: . dockerfile: docker/tasks_dj.dockerfile volumes: - .:/tasks_app command: python manage.py process_tasks depends_on: - db container_name: my_background_tasks While I can see in my my-sql that the job repeat itself, I'm unable to see the dummy logs with: $docker logs my_background_tasks it shows nothing -
Elastic Beanstalk - Django API calls getting 504 Gateway Timeout
Context I've setup a basic Django and React app with DRF. The app loads a single HTML page and lets React handle the frontend. React makes API calls to the Django backend. To be clear, Django and React live in the same domain. (I followed Option 1 here: https://www.valentinog.com/blog/drf/#django-rest-with-react-django-and-react-together). It's working well locally during development, and I wanted to deploy to production. I decided to go with aws elastic beanstalk, and I've been able to render the frontend assets successfully. The Problem I'm running into issues whenever I make any sort of API call to Django, for example logging in: I get a 504 gateway timeout error every time. What I've tried I've tried increasing the time limit but it still times out. I assumed that the backend API was not accessible, and so I needed to extend the nginx config for my Django and React setup - I followed this: https://stackoverflow.com/a/27230658/14603395, but I believe there is actually no support for doing this with Django. (And I realized the config file I wrote wasn't even being used). Where I'm at now Thinking about it more, I can't see why I would have to change the nginx config anyway, since I'm … -
Django create unique foreign key objects
I have a FK in my Django model, that needs to be unique for every existing model existing before migration: class PNotification(models.Model): notification_id = models.AutoField(primary_key=True, unique=True) # more fields to come def get_notifications(): noti = PNotification.objects.create() logger.info('Created notifiactions') logger.info(noti.notification_id) return noti.notification_id class Product(models.Model): notification_object = models.ForeignKey(PNotification, on_delete=models.CASCADE, default=get_notifications) When migrating, I get three PNotification objects saved into the database, however each existing Product is linked with notification_id=1, so each existing Product gets linked with the same PNotification object. I thought the method call in default would be executed for each existing Product? How can I give each existing Product a unique PNotification object? -
pytest and selenium usage to test a django view
I intend to test a simple CBV ListView with pytest and selenium. To avoid the repetition of getting in each method the call of reg_customer_browser and live_server fixtures, I thought of creating a fixture in the class like here: class TestAddressesListView: view_name = "dashboard_customer:addresses_list" @pytest.fixture def browser_as_regular_user(self, reg_customer_browser, live_server): return reg_customer_browser.get(live_server.url + reverse(self.view_name)) def test_regular_user_can_not_create_addresses(self, browser_as_regular_user, customer_regular): br = browser_as_regular_user create_url = reverse("dashboard_customer:create_address") with pytest.raises(InvalidSelectorException): br.find_element_by_xpath(f'//a[@href="[{create_url}]"') def test_regular_user_can_not_update_address(self, browser_as_regular_user, customer_regular): br = browser_as_regular_user i = random.randint(0, customer_regular.company.addresses.count() - 1) address = customer_regular.company.addresses.all()[i] update_url = reverse("dashboard_customer:update_address", args=(address.pk,)) with pytest.raises(InvalidSelectorException): br.find_element_by_xpath(f'//a[@href="[{update_url}]"') But adding this inner fixture makes the browser reopens few times and none of my tests passes. To pass, I need to write each time a method like this: def test_regular_can_not_update_address(self, reg_customer_browser, live_server, customer_regular): br = reg_customer_browser.get(live_server.url + reverse(self.view_name)) i = random.randint(0, customer_regular.company.addresses.count() - 1) address = customer_regular.company.addresses.all()[i] update_url = reverse("dashboard_customer:update_address", args=(address.pk,)) with pytest.raises(InvalidSelectorException): br.find_element_by_xpath(f'//a[@href="[{update_url}]"' Isn't it a way to avoid initializing each method with reg_customer_browser and live_server? -
nginx, flower, Django, proxy_pass, and rejecting invalid HOSTs
I have a server on AWS running nginx/uWSGI/Django, with RabbitMQ, flower, and Celery. The problem: use nginx to proxy for flower without opening up a new port, and also reject badly-formed requests that would cause Invalid HTTP_HOST Header errors in Django. I can do either but not both because I am not super experienced with nginx. I'm running flower 0.9.4, as I'm aware of the bug in 0.9.5. In the following config files, if I comment out the "reject_hosts.conf" line, flower works, but I stop rejecting hosts like I should. If I leave it in, the web browser times out making the request for the /flower URL. Here's the relevant config files: nginx-app.conf # the upstream component nginx needs to connect to upstream django { server unix:/home/app.sock; # uwsgi socket } include redirect_ssl.conf; #301 SSL redirects # actual webserver. Note that https is handled by AWS so no listen on 443 server { # default_server indicates that this server block is the block to use if no others match server_name listen 8080 default_server; listen [::]:8080 default_server; charset utf-8; # max upload size client_max_body_size 3M; # adjust to taste include django_aliases.conf; # media and static directories include reject_hosts.conf; # return 444 … -
React Not Starting in DRF project
I am currently trying to create a react app in a django restframework project using "npm start" but i keep getting the following errors: $ npm start > ui@0.1.0 start C:\Users\Admin\Desktop\Projects\Workout & Api\reacter\ui > react-scripts start 'Api\reacter\ui\node_modules\.bin\' is not recognized as an internal or external command, operable program or batch file. internal/modules/cjs/loader.js:883 throw err; ^ Error: Cannot find module 'C:\Users\Admin\Desktop\Projects\react-scripts\bin\react-scripts.js' at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15) at Function.Module._load (internal/modules/cjs/loader.js:725:27) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) at internal/main/run_main_module.js:17:47 { code: 'MODULE_NOT_FOUND', requireStack: [] } npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! ui@0.1.0 start: `react-scripts start` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the ui@0.1.0 start script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\Admin\AppData\Roaming\npm-cache\_logs\2020-11-09T14_21_33_819Z-debug.log The thing is outside of the DRF project, "npm start" works just fine. I have tried force cleaning my npm cache, deleted my npm cache and npm folder, deleted my node_modules folder, uninstalled and reinstalled nodejs, added c:program/win32 to path but nothing has worked. Any help would be appreciated, thanks.