Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating Django Package and View Authentication
I am trying to package an App that I have created in a Django project and now I'm wondering how to handle authentication in this apps' views. Throughout the app I have used both class SomeView(LoginRequiredMixin,...): pass # for views or @login_required def someFunction(request): pass # for functions in my views.py, but I would like to make authentication optional for future use. How does one handle this? I considered stripping Mixin and decorators from views and then handle this functionality in urls.py. Is this a viable option and of course, how would this be handled better. Thank you for your time! -
Django Taggit show all tags all pages
I am using taggit in Django , when i add tag this tag show all my blog article , i want to show this only in this article where i add. can anyone fix ? i mean for example when i add tag 'Aries' it show in Aquarius article , Scorpio article and etc url.py urlpatterns = [ path('',Home,name= "Home"), path('horoscope/<slug:slug>/<slug:cat>',singCategory,name='singCategory'), path("openblog/",blog_list, name="blog_list"), path("openblog/<slug:slug>",blogDetail, name="blogDetail"), path('ads.text', read_file), path('tag/<slug:slug>', tagged, name="tagged"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def blog_list(request): articles = Blogmodel.objects.all().order_by('-id') paginator = Paginator(articles, 8) page = request.GET.get('page') posts = paginator.get_page(page) articles = paginator.get_page(page) args = {'articles':articles,'posts': posts } return render(request,'blog.html',args) def tagged(request, slug): query = Q(body__icontains=slug ) | Q(Title__icontains=slug ) articles = Blogmodel.objects.filter(query).order_by('-id') paginator = Paginator(articles, 8) page = request.GET.get('page') posts = paginator.get_page(page) articles = paginator.get_page(page) args = {'articles':articles,'posts': posts } return render(request,'blog.html',args) form.py from django import forms from .models import Blogmodel class BlogForm(forms.ModelForm): class Meta: model = Blogmodel fields = [ 'Title', 'body', 'slug', 'tags' ] Html <p>Common Tags: {% for mt in common_tags %} <a href="/tag/{{ mt }}" class="badge badge-success">{{mt}}</a> {% endfor %} -
How to filter datetime using datetime in django?
I have a Homework model that I want to filter based on the date(date_view) to show the homework. It looks like this- Homework model class Homework(models.Model): hw_id = models.CharField(unique=True, max_length=50) homework = models.TextField() subject = models.ForeignKey(Subject, on_delete=models.CASCADE) class_id = models.ForeignKey(Classes, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) date_view = models.DateTimeField(default=datetime.now()) But when I try to filter like this- hw = Homework.objects.filter(class_id=class_id).filter(date_view__gte='homework__date_added') I get this error- ['“homework__date_added” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] I think I am filtering the data in the wrong way. But how should I filter the data? -
URL patterns in django 3
I am really new to DJango and stuck at level 1. My problem is URL mapping. I am pasting the code here and let you know what I want to achieve. I have this file tree: enter image description here My myproj2 > urls.py has the following code from django.contrib import admin from django.urls import path, include from myproj2_app import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('help/', include('myproj2_app.urls')), ] And my myproj2 > myproj2_app > urls.py has the following code: from django.conf.urls import url from . import views urlpatterns = [ url('', views.index, name='index'), url('help/', views.help, name='help'), ] My myproj2 > myproj2_app > views.py has the following code: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Hello This is my myproj2") def help(request): print("Getting to get help at least") help_dict = {'help_insert' : 'HELP PAGE '} return render(request, 'myproj2_app/help.html', context = help_dict) I have a folder 'templates' in my main myproj2 folder. In 'templates' folder, I have myproj2_app folder and then I have two html files. One is index.html and the other is help.html. I want to access http://127.0.0.1:8000/help/ where I am displaying simple text with {{ help_insert }} … -
Django Rest API relationship no such column
I want to get recipes from my django rest api but now I dont know how to get a recipe with the ingredients. I tried the following: 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) ingredient = 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.ForeignKey(Ingredients, related_name='ingredients', on_delete=models.CASCADE) class Meta: managed = False db_table = 'Recipes' My serializer.py: class IngredientsSerializer(serializers.ModelSerializer): class Meta: model = Ingredients fields = '__all__' class FullRecipeSerializer(serializers.ModelSerializer): ingredients = IngredientsSerializer(many=True, read_only=True) class Meta: model = Recipe fields = ['recipeid','title','images', 'preperation', 'ingredients'] And my view: class FullRecipesView(generics.ListCreateAPIView): serializer_class = FullRecipeSerializer permission_classes = [ permissions.AllowAny ] queryset = Recipe.objects.all() In the view, I am not sure if the queryset is right. But now I get the error: OperationalError at /api/full-recipes no such column: Recipes.ingredients_id And … -
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