Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Angular + Django: runtime.js:1 Uncaught SyntaxError: Unexpected token '<' when rendering build index.html
I have a Django application, that I am attempting to pair with an Angular application. The angular application is inside the Django application, and the Django application is using the build directory, dist, for its templates. I have a simple view that uses the index.html inside the dist build folder: index = never_cache(TemplateView.as_view(template_name='index.html')). And a simple URL to send any unmatched urls to the index. re_path('.*', index, name="index") I tested this with ReactJS and I was able to start django and get the ReactJS project at localhost:8000, but with Angular, I get these errors. runtime.js:1 Uncaught SyntaxError: Unexpected token '<' polyfills.js:1 Uncaught SyntaxError: Unexpected token '<' styles.js:1 Uncaught SyntaxError: Unexpected token '<' vendor.js:1 Uncaught SyntaxError: Unexpected token '<' And inside my django terminal I can see: [09/Nov/2020 19:36:24] "GET / HTTP/1.1" 200 752 [09/Nov/2020 19:36:24] "GET /runtime.js HTTP/1.1" 200 752 [09/Nov/2020 19:36:24] "GET /vendor.js HTTP/1.1" 200 752 [09/Nov/2020 19:36:24] "GET /main.js HTTP/1.1" 200 752 [09/Nov/2020 19:36:24] "GET /styles.js HTTP/1.1" 200 752 [09/Nov/2020 19:36:24] "GET /polyfills.js HTTP/1.1" 200 752 [09/Nov/2020 19:36:24] "GET /favicon.ico HTTP/1.1" 200 752 Which is strange to me. How do i go about fixing this error, so my Django application can render the angular project? -
Django: Save auth_user to model with Foreign Key
The scenario is the following: I have a Django form which places a post request to the backend. With this data, I create an instance of my order model. One order can have one customer and a customer can have one auth_user. Database is SQLite. The relation looks like this: class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.RESTRICT) class Customer(models.Model): email = models.CharField(max_length=MAX_TEXT_LENGTH) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) I managed to save all of them, order and customer are correctly related in the database. Although I am somehow failing while saving the user to customer. I save them like this in my view.py: with transaction.atomic(): # create customer & order customer = create_customer(first_name, last_name, email, phone) order = create_order(customer, form.cleaned_data) # add additional stuff to order order.additional_services.add(*form.cleaned_data['additional_service']), order.save # create user and update customer plain_user_password = generatePassword(DEFAULT_PASSWORD_LENGTH) user = create_user(order.id, email, plain_user_password, first_name, last_name) customer.user = user customer.save I create all my models with Model.objects.create(...) Using the order.id as username is a given and cannot be changed. The last two lines seem not to work, although the customer holds the correct user_id afterwards, the column in the database table is ... No exception occurring when I use a try-catch block either... What … -
<button type="button" onclick = "locations.href='{% url 'log' %}'">logout</button>
<html lang=“en“> <head> <meta charset=“UTF-8“> <title>Title</title> <style> div{ position : absolute; right : 10px; top : 5px } .button { display: block; width: 115px; height: 25px; background: #4E9CAF; padding: 10px; text-align: center; border-radius: 5px; color: white; font-weight: bold; line-height: 25px; } </style> </head> <body> <main> <div> <button type="button" onclick = "locations.href='{% url 'log' %}'">logout</button> <a class = "button" href = "{% url 'log' %}">LOGOUT</a> </div> </main> Welcome {{e}} code in the anchor tag is working as a logout button but not when I am using button, its showing error. The problem with the anchor tag is after clicking the logout login page is coming but I can go back to home page again without logging in. Please help me with this. -
I want to display categories from CATEGORIES_CHOICE but doesnt show anything
I'm creating simple website with navbar where i want to show categories from CHOICE tuple, but when i launch my website i cant see anything there. My models.py CATEGORY_CHOICE = { ('K','K1'), ('S','S1'), ('D','D1') } class Item(models.Model): ... category = models.CharField(choices=CATEGORY_CHOICE, max_length=1) ... views.py def item_categories(request): context = { 'header': 'Cakes', 'cakes': Item.objects.all(), 'categories': CATEGORY_CHOICE } return render(request, 'home.html', context) and my home page ... <div class="col-2"> {% for category in categories %} <a href="#"><h6>{{ category }}</h6></a> {% endfor %} </div> ... Any hints why it isn't showing me the categories? Many thanks! -
AttributeError: 'ServiceModel' object has no attribute 'service_id'
i'm new to programming in django. I have an error when I do manage.py runserver, the error occurs; AttributeError: 'ServiceModel' object has no attribute 'service_id'. I re-created my virtual environment and installed the requirements, but the same error occurs again. -
DJANGO CLASSE-BASE-VIEWS WORKING WITH PRIMARY KEY
AM TRYING TO CREATE A MULTI-USER PROJECT USING DJANGO AND CLASSE BASE VIEWS.....AM TRYING TO CREATE A BLOG WITH A BLOG_TITLE AND A BLOG_MESSAGE AS ARGUMENTS, I WAS SUCCESSFUL ON CREATING THE OBJECTS AND REDIRECTING TO ANOTHER PAGE, BUT NOW AM TRYING TO GET THE USERS NAME... here are my urls here are my calsse this is my template which is getting the title and the blog-message This are my models i was SUCCESSFUL on doing this using the django-admin section, but not able to do it in the code. -
Changes are not reflecting directly in Django admin page
In Django , I have a model named "Sample" class Sample(models.Model): Name = models.CharField(max_length = 250) Business_process = models.CharField(max_length = 250,editable=False) Sub_business_process = models.CharField(max_length = 250,editable=False) def save(self,*args,**kwargs): self.Business_process = self. Application.BP self.Sub_business_process = self. Application.SBP super(Sample,self).save(*args,**kwargs) while saving this model , this function gets the values of BP and SBP from Application table and stores it in Sample model fields. But whenever the BP and SBP field values gets changed in Application table , the changes are not reflecting directly in Sample model unless we save . (ie)currently, the values are getting reflected only when the Sample admin page gets saved. The expectation is the values of BP and SBP needs to reflect in Sample admin when the page gets opened. Any idea? Thanks in advance -
Waypoint.Infinite is not a constructor
Hi everbody i have a problem about django infinite scroll paginations. I cant solve it. home.html <div class="infinite-container"> {% for post_display in post_data %} <div class="card infinite-item"> <div class="card-body"> {{ post_display }} </div> </div> </div> <script src="{% static 'js/jquery.js' %}"></script> <script src="{% static 'js/jquery.waypoints.min.js' %}"></script> <script src="{% static 'js/infinite.min.js' %}"></script> <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], handler: function(direction) { }, offset: 'bottom-in-view', onBeforePageLoad: function () { $('.spinner-border').show(); }, onAfterPageLoad: function () { $('.spinner-border').hide(); } }); view.py class HomeClassView(ListView): model = EssahDisplayModel paginate_by = 2 template_name = "authenticated/home.html" context_object_name = 'post_data' Bu i get this error on console: (index):458 Uncaught TypeError: Waypoint.Infinite is not a constructor at (index):458 it the line 458 start: var infinite = new Waypoint.Infinite({.... Someone knows it ? thans -
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.