Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying Django+React to Heroku - Uncaught SyntaxError: Unexpected token '<'
I am trying to deploy my Django + React application to Heroku. (Django for only api and React for frontend.) I followed this video, but cannot resolve this problem for several days. There is no error during deploy process, but after deploy, only white blank screen is showed up. This is the only clue I can find until now... I tried adding type="text/babel" to your script tag, adding base href tag to index.html, and changing several package.json and settings.py options. This is my package.json file. { "name": "frontend", "version": "0.1.0", "homepage": "https://myapp.herokuapp.com/", "private": true, "proxy": "http://localhost:8000", "dependencies": { "@material-ui/core": "^4.9.5", "@material-ui/icons": "^4.9.1", "@material-ui/lab": "^4.0.0-alpha.46", "@material-ui/styles": "^4.9.0", "@testing-library/jest-dom": "^4.2.4", "@testing-library/react": "^9.5.0", "@testing-library/user-event": "^7.2.1", "babel-preset-react": "^6.24.1", "react": "^16.13.0", "react-dom": "^16.13.0", "react-redux": "^5.0.7", "react-scripts": "3.2.0", "redux": "^4.0.0", "redux-thunk": "^2.3.0" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", "postinstall": "npm run build" }, "engines": { "node": "12.14.0", "npm": "6.13.4" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "devDependencies": { "axios": "^0.19.2", "react-router-dom": "^5.1.2" } } And this is settings.py file. """ Django … -
django Model filter by list
i am getting list of value from checked checkbox , Now i want to filter the list with my model and get only filter result of value in list views.py def ResultTest(request): var = request.POST.get('selectedTests') var1 = BookTest.objects.filter(test=v) return render(request, 'posts/result.html',{'var1':var1}) html file <input type="hidden" id="selectedTests" name="selectedTests"> i am getting the selectedTests a list of values now i want the list of values to filter in models and get all data of the values. -
response change on every GET request in django
I am trying to implement a load balance in Django using a round-robin technique by getting a different response on every GET call. My Model: class Load_Balancing(models.Model): instance_name = models.CharField(max_length=100) sequence = models.IntegerField() algorithm = models.CharField(max_length=100) I have tried: class Get_Instance(APIView): def get(self, request): ins = Load_Balancing.objects.all().order_by("-sequence")[:1] print(type(ins)) data = {} for r in ins: data["instance_name"] = r.instance_name return Response(data) Here instance_name is random URL and I'm trying to make it dynamic so that on every GET request I get the last instance and then other instances in order i.e the 1st instance in the database and so on. -
I'm trying to use stripe payment. But having some issues on submitting card details
Im following just django tutorial. I'm unable to get any success message or error message after clicking submit button. the page is not even getting redirected after clicking submit button. dont know where i went wrong with my post method. P.s. Ive created my stripe acc and Ive used those public and private keys. Any help is appreciated. TIA payment.html {% extends 'base.html' %} {% block content %} <main class="mt-5 pt-4"> <div class="container wow fadeIn"> <h2 class="my-5 h2 text-center">Payment</h2> <div class="row"> <div class="col-md-12 mb-4"> <div class="card"> <script src="https://js.stripe.com/v3/"></script> <form action="." method="post" id="stripe-form"> {% csrf_token %} <div class="stripe-form-row"> <label for="card-element" id="stripeBtnLabel"> Credit or debit card </label> <div id="card-element" class="StripeElement StripeElement--empty"><div class="__PrivateStripeElement" style="margin: 0px !important; padding: 0px !important; border: medium none !important; display: block !important; background: transparent none repeat scroll 0% 0% !important; position: relative !important; opacity: 1 !important;"><iframe allowtransparency="true" scrolling="no" name="__privateStripeFrame5" allowpaymentrequest="true" src="https://js.stripe.com/v3/elements-inner-card-fbfeb5b62d598125b16ab6addef894d6.html#style[base][color]=%2332325d&amp;style[base][fontFamily]=%22Helvetica+Neue%22%2C+Helvetica%2C+sans-serif&amp;style[base][fontSmoothing]=antialiased&amp;style[base][fontSize]=16px&amp;style[base][::placeholder][color]=%23aab7c4&amp;style[invalid][color]=%23fa755a&amp;style[invalid][iconColor]=%23fa755a&amp;componentName=card&amp;wait=false&amp;rtl=false&amp;keyMode=test&amp;apiKey=pk_test_i0vc3rYRd3tcPmIsJIIQOiiI00khWr20iQ&amp;origin=https%3A%2F%2Fstripe.com&amp;referrer=https%3A%2F%2Fstripe.com%2Fdocs%2Fstripe-js&amp;controllerId=__privateStripeController1" title="Secure payment input frame" style="border: medium none !important; margin: 0px !important; padding: 0px !important; width: 1px !important; min-width: 100% !important; overflow: hidden !important; display: block !important; height: 19.2px;" frameborder="0"></iframe><input class="__PrivateStripeElement-input" aria-hidden="true" aria-label=" " autocomplete="false" maxlength="1" style="border: medium none !important; display: block !important; position: absolute !important; height: 1px !important; top: 0px !important; left: 0px !important; padding: 0px !important; margin: … -
debugging a django app (locally) in VS Code can't find my database container db
When I run a debug configuration in VS Code: "configurations": [ { "name": "Django Tests", "type": "python", "request": "launch", "program": "${workspaceFolder}/src/manage.py", "args": [ "test", "src" ], "django": true } I get this error: django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known I don't have this problem when I run the app normally: ./src/manage.py runserver db is my containerized postgresql database. services: db: container_name: db build: ./postgresql expose: - "5432" ports: - 5432:5432 ... Perhaps I'm not using the proper python path? I should be running this from within my python virtual environment but I'm not sure how to set that in the VS Code configuration, if that's the problem. Here's my settings.py POSTGRES_HOST = os.environ.get('POSTGRES_HOST', '127.0.0.1') POSTGRES_PORT = os.environ.get('POSTGRES_PORT', '5432') -
Djnago Excel file loading and performing function
I have created a django Library app to manage Authors and their books. I have also created a script that when run extracts data from a excel file and converts it into JSON format and then I have to run another script in django shell to load the json file to the database and saving it. Is there any way from where I can load the data in django itself and create a view to manage all the functions, such as extraction and data loading. Following is the models.py file: from django.db import models from django.db.models.signals import pre_save from books.utils import unique_slug_generator, unique_slug_generator_author, unique_slug_generator_genre from django.urls import reverse # Create your models here. class BookManager(models.Manager): def is_read(self): return self.filter(read='y') def is_not_read(self): return self.filter(read='n') class Genre(models.Model): name = models.CharField(max_length=200, help_text='Enter a book genre (e.g. Science Fiction)') slug = models.SlugField(max_length=250, null=True, blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('books:genredetail',kwargs={'id': self.slug}) class Author(models.Model): first_name = models.CharField(max_length=100, help_text="Enter first name of the author",default="Unknown") last_name = models.CharField(max_length=100, help_text="Enter last name of the author",blank="true") slug = models.SlugField(max_length=250, blank=True) def __str__(self): return f'{self.first_name} {self.last_name}' def get_absolute_url(self): return reverse('books:authordetail',kwargs={'id': self.slug}) class Meta: unique_together = ("first_name", "last_name") class Book(models.Model): YES = 'y' NO = 'n' DID_READ_CHOICES = [ … -
django output as django json array
Can we return it as json array with the code I wrote below? So output as json array I'm actually printing. but I want it to result as a json array ` class DebtFinancialReceivedAmountListAPIView(ListAPIView): permission_classes = [IsOwner] filter_backends = [django_filters.rest_framework.DjangoFilterBackend] def get(self, request): spending = Spending.objects.filter( createdDate__gt=(self.request.query_params.get('startingDate')), createdDate__lt=(self.request.query_params.get('endDate'))) \ .aggregate(spendingAmount=Sum('spendingAmount'), spendingKdv=Sum('spendingKdv'), spendingTotal=Sum('spendingTotal')) debtsReceived = Debt.objects.filter( paymentDate__gt=(self.request.query_params.get('startingDate')), paymentDate__lt=(self.request.query_params.get('endDate'))) \ .aggregate(totalDebt=Sum('totalDebt'), receivedAmount=Sum('receivedAmount')) constantSpending = ConstantSpending.objects \ .filter(user=self.request.user) \ .aggregate(constantSpendingAmount=Sum('constantSpendingAmount'), constantSpendingTotal=Sum('constantSpendingTotal')) result = {**debtsReceived, **spending, **constantSpending} return Response(result) ` code output as follows ` HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "totalDebt": 290.0, "receivedAmount": 53.0, "spendingAmount": null, "spendingKdv": null, "spendingTotal": null, "constantSpendingAmount": null, "constantSpendingTotal": null } -
Django not detecting new changes to models
I just added a new field to my model, but when running python manage.py makemigrations it won't detect anything and when visiting the admin interface the new field won't show up. I'm using postgresql as database. class Movies(models.Model): title = models.CharField(max_length=30, blank=True, null=True) ###(...)### director_name = models.CharField(max_length=30, blank=True, null=True) keywords = models.ManyToManyField('Keywords', through='MoviesKeywords', related_name='movies')# This is the new field class Meta: managed = False db_table = 'movies' (keywords is the new field) I already tried passing the name of the app into the command like this: python manage.py makemigrations recommendations But I also get nothing in response. -
How to use a variable or change href in HTML using javascript (Django)
So right now in my navbar I have it as the following: <a class="nav-link" href="/home/{{applicant}}">Home </a> {{applicant}} returns the applicant's id (int). For security purposes I've decided to use a basic encryption so that someone can't easily guess a persons id. The encryption is simply some math done to the id ((((((id * 3) + 5 ) * 63 ) - 1 ) * 218 ) - 5) which while obviously not secure is good enough for the project. How would I apply this in the html using either django or javascript to modify the real id so that the href points to their encrypted id? I'm looking for something like below: <a class="nav-link" href="/home/" + encrypted id>Home </a> -
How to color html table in django based on condition
class11=[10,20,30,76] class12=[23,45,23,45] <table> <tr> <th>Class11</th> {% for class1 in class11 %}<td>{{class1}} </td> {% endfor %} </tr> <tr> <th>Class12</th> {% for class2 in class12 %}<td>{{class2}} </td> {% endfor %} </tr> </table> How to color Class 11 based on conditions : if value > 20 to color to red if value > 40 to color orange if value > 50 to color green I serached web they recomedn js but i am not good with js quite new. Is there nay way to do in CSS? -
Error: Using the URLconf defined in mysite.urls, Django-3 tried these URL patterns, in this order:,
I'm doing tutorial "Blog" from "Django 3 by example" and I got error. What i'm doing wrong? Error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/ amd alsp TemplateDoesNotExist at /blog/. Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current URL, blog/, didn't match any of these. BLOG ADMIN mysite/urls.py from django.contrib import admin from django.urls import path, include, re_path urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls', namespace='blog')), ] mysite/blog/views.py from django.shortcuts import render, get_list_or_404 from .models import Post # Create your views here. def post_list(request): posts = Post.published.all() return render(request, 'blog/post/list.html', {'post': posts}) def post_detail(request, year, month, day, post): post = get_list_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) return render(request, 'blog/post/detail.html', {'post': post}) mysite/blog/admin.py from django.contrib import admin from .models import Post # Register your models here. @admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ('title', 'slug', 'author', 'publish', 'status') list_filter = ('status', 'created', 'publish', 'author') search_fields = ('title', 'body') prepopulated_fields = {'slug':('title',)} raw_id_fields = ('author',) date_hierarchy = 'publish' ordering = ('status', 'publish') mysite/mysite/urls.py from django.urls import path, include from mysite.blog import admin from . import views app_name = 'blog' urlpatterns = [ # post views path('', views.post_list, name='post_list'), path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'), ] … -
How to remove unwanted css and js from your django application?
I'm making a Fullstack application which uses Django as a backend and javascript and jquery as a frontend.The app is finished now I want to remove unwanted css,images,js which just lie there in static files but are not used in templates is there a way to remove all of this unwanted code,files.I checked on the internet and there are solutions like purgecss but they use npm for running and I don't have npm Is there any other way to it easily or if I have to do it by using purgecss.Can you guide me all the way in the answer section. Thank you -
Django - Message translation in template does not work
Translations in the same function for form.error work and messages are displayed in a different language, but for "messages" the text is still displayed in English in the template views.py from django.utils.translation import ugettext_lazy as _ form.errors['__all__'] = form.error_class([_('Bad pin')]) Works messages.add_message(self.request, messages.INFO, _('Bad pin')) Did not work, in the template after entering {{message}}, I see the English version Settings.py 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "account.middleware.LocaleMiddleware", 'django.middleware.common.CommonMiddleware', "account.middleware.TimezoneMiddleware", -
How to design an app with djano and node to make an appointment app/webapp
Where can I get proper tutorials or the steps/reference to develop an django app with node and google calendar integrated. for booking purpose. -
why flask app is not updating the browsing after reloading?
I am beginner in flask, I am facing issue in updating the template when i run the app flask run for the first time it works currently, but when I update the html or the python code and then reload the page the update does not effect in the browser i tried different browser but still doesn't work then i have to restart the IDE and run the app again this is my code from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') if __name__ == "__main__": app.run(debug=True) -
How to obtain multiple values from the drop down box django?
I am trying to obtain 2 values from an HTML dropdown menu as follows: <form action="POST"> <select name="season" id="season"> <option value="" selected disabled>Choose an option</option> <option value="Running">Running</option> <option value="2021">Summer 2021</option> </select> <h4>Select The Enrollment Batch:</h4> <select name="level" id="level"> <option value="" selected disabled>Choose an option</option> <option value="class-9">CAIE O Level (class 9)</option> <option value="class-10">CAIE O Level (class 10)</option> <option value="class-11">CAIE AS Level</option> <option value="class-12">CAIE A2 Level</option> </select> <button type="submit" class="btn deep-orange darken-2">Submit</button> </form> Is that even the proper way to obtain the data? Does the data come in as a tuple? What should the Django form be like and how do i save it in views? -
Django hosting for web development [closed]
How to host Django website in Google Cloud platform? -
keep getting this error{relation "profiles_user" does not exist}
I am a beginner programmer working on my own project on Django. I am trying to make a model create itself whenever a user is created. but i keep getting this error {relation "profiles_user" does not exist}. I am using PostgreSQL as my DB. from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save class User(AbstractUser): is_expert = models.BooleanField(default=False) is_student = models.BooleanField(default=False) EDUCATION=( ('Collage','Collage'), ('Post_Graduate','Post_Graduate'), ('Masters','Masters'), ('PHD','PHD'), ) class Expert(models.Model): expert = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) first_name = models.CharField(max_length=12, null=True, default='') last_name = models.CharField(max_length=20, null=True) discription = models.TextField(null=True) education = models.CharField(max_length=200, choices=EDUCATION, null=True) field = models.CharField(max_length=200, null=True) company = models.CharField(max_length=50,null=True) position = models.CharField(max_length=20, null=True) experience = models.TextField(null=True) charge_per_hour = models.IntegerField(default="0") def __str__(self): return (f'{self.first_name} {self.last_name}') def create_profile(sender,**kwargs ): if kwargs['created']: user_profile=Expert.objects.create(expert=kwargs['instance']) post_save.connect(create_profile,sender=User) Thank you for your help in advance -
url contains spaces in django v3
I'm trying to create my first django rest framework project and this is the scenario I'm stuck in. In project's urls.py file I have this: urlpatterns = [ path('admin/', admin.site.urls), # other paths path("api/", include("users.api.urls")), # other paths ] While in users/api/urls.py file I have this: urlpatterns = [ path("user/", CurrentUserAPIView.as_view(), name="current-user") ] What I can't understand is why If I go to localhost the list of urls look like this: admin/ ... other paths **api/ user/ [name='current-user']** ... other paths As you can see there is a space before "user" in the line between asterisks. If I go to http://localhost:8000/api/user/ I receive this error: 'str' object is not callable and I read it is related to a url configuration problem. -
PATCH method not working in Django ModelViewSet
I'm having trouble in using patch method inside a ModelViewSet for my custom User model. Here is the code: views.py @permission_classes([IsAdminUser]) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer http_method_names = ['get', 'post', 'patch', 'head', 'delete'] serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email', 'password', 'is_active', 'is_staff', 'is_admin') extra_kwargs = {'password': {'write_only': True, 'required': True}, 'is_active': {'default': True}, 'is_staff': {'default': False}, 'is_admin': {'default': False}} def create(self, validated_data): self.is_valid(raise_exception=True) if validated_data['is_admin']: validated_data['is_staff'] = True user = User.objects.create_user(**validated_data) return user def update(self, instance, validated_data): instance.email = validated_data.get('email') instance.is_active = validated_data.get('is_active') instance.is_staff = validated_data.get('is_staff') instance.is_admin = validated_data.get('is_admin') if instance.is_admin: instance.is_staff = True instance.save() return instance I set a permission in order to allow only superuser to access this view. The problem comes when trying to perform a patch. For example, if I try to change is_staff attribute to False of a User using Postman with PATCH and "http://localhost:8000/users/USER_ID", I get the following error: django.db.utils.IntegrityError: null value in column "email" violates not-null constraint DETAIL: Failing row contains (1, pbkdf2_sha256$180000$6jePqBspO6xK$tCQ9zZk1uOdJD2F7L9BQRFFDbz1GXJ..., 2020-04-18 20:02:57.052639+00, null, t, t, t). It seems like django asks me to provide every single field fo User model (email, is_active, is_staff, is_admin), which it doesn't make sense in my … -
ValueError at /pembayaran/ ModelForm has no model class specified. django
from . import forms from django.shortcuts import render from .forms import pembayaran #Create your views here. def index(request): return render(request, 'index.html') def pembayaran_function(request): form=pembayaran() if request.method=='POST': form=pembayaran(request.POST) if form.is_valid(): form.save() context={'form':form} return render(request, 'pembayaran.html', context) what's wrong in my views? i don't know to handle this pls help me, thanks before -
Can't find module name using Django
I created a faker script but when I try to run it I get an error saying: 'ModuleNotFoundError: No module named 'new_project'' Here's my 'populating.py' code: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','new_project.settings') import django django.setup() import random from homepage.models import AccessRecord, Webpage, Topic from faker import Faker fakegen = Faker() topics = ['Search','Social','Marketplace','News','Games'] def add_topic(): t= Topic.objects.get_or_create(top_name=random.choice(topics)) [0] t.save() return t def populate(N=5): for entry in range(N): top = add_topic() fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() webpg = Webpage.objects.get_or_create(topic=top, url=fake_url, name=fake_name)[0] acc_rec = AccessRecord.objects.get_or_create(name=webpg, date=fake_date) [0] if __name__=='__main': print("populating script") populate(20) print('populating complete') and here's my Project Browser: Project Browser Thank you in advance for any sugestions! -
Django Signup form inside modal box
Hi everyone in my Django Website I've got a modal box that opens whenever the user click on the singup button. I'd like the form to be shown inside the box. I didn't use the forms.py file for the form but a simple function like this in the views.py. Anyway the form doesn't appear, what am I doing wrong? Thanks views.py def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = UserCreationForm() return render(request, 'search/home.html', {'form': form}) -
Django-Graphene: No module named 'graphql_jwt'
I'm trying to implement authentication with Django and GraphQL/graphene I've run into the error No module named 'graphql_jwt'. and the solutions I've found don't seem to work Reproducing The code is available here: https://github.com/altear/hello-GraphQL.git It uses docker-compose, so you should be able to run it with just docker-compose up -d --build The error is immediately visible if you go to http://localhost:8000 What I've Tried Other posts that have this error don't seem to be applicable: one mentions having another folder named "graphql" in the python path, so my environment should be clean another mentions not having installed graphql. However, it's in my requirements.txt and it worked before I tried adding authentication -
how can i use sockets with connexion?
Is there a way to send real-time messages from a connexion backend to a django frontend ?For example send status messages every 10 seconds or the progression of a request in real time. The documentation isn't clear and I didn't find a complete example