Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to stop objects (posts) from overlapping each other
I am trying to create the landing page of a blog, however, posts keep on overlapping with other content. How can I stop these objects from overlapping each other? I have attached an image of how the frontend looks like for better understanding. This is how the frontend looks like Here is my index.html <style> .headslider{ background-image: url("{% static 'assets/img/post-slide-1.jpg' %}"); } .postslide{ background-image: url("{% static 'assets/img/post-slide-2.jpg' %}"); } .postslide1{ background-image: url("{% static 'assets/img/post-slide-3.jpg' %}"); } .postslide2{ background-image: url("{% static 'assets/img/post-slide-4.jpg' %}"); } .box{ width: 250px; height: 200px; margin:20px; padding: 20px; } </style> </head> <!-- ======Some sections skipped====== --> <!-- ======= Post Grid Section ======= --> <section id="posts" class="posts"> <div class="container" data-aos="fade-up"> <div class="row gx-5"> {% for post in posts %} <div class="post-entry-1 col-lg-3 box mx-1"> <a href="single-post.html w-300 h-200"><img src="{{post.image.url}}"></a> <div> <div class="post-meta"><span class="date">Culture</span> <span class="mx-1">&bullet;</span> <span>{{post.created_at}}</span></div> <h2><a href="">{{post.title}}</a></h2> </div> <p class="mb-4 d-block">{{post.body|truncatewords:20}}</p> <div class="d-flex align-items-center author"> <div class="photo"><img src="{% static 'assets/img/person-1.jpg' %}" alt="" class="img-fluid"></div> <div class="name"> <h3 class="m-0 p-0">OlePundit</h3> </div> </div> </div> {% endfor %} <br> <!-- Trending Section --> <div class="col-lg-3 mx-10 pl-10"> <div class="trending"> <h3>Trending</h3> <ul class="trending-post"> <li> <a href="single-post.html"> <span class="number">1</span> <h3>The Best Homemade Masks for Face (keep the Pimples Away)</h3> <span class="author">Jane Cooper</span> </a> … -
Rendering multiple matplotlib plots in my Django view using BytesIO
I'm struggling with rendering multiple matplotlib plots in my Django View. When doing it with one plot, it works fine, but as soon as i try adding more than one plot in my view, the second plot doesn't render correctly. I'm quite sure it has something to do with how i'm using BytesIO(). In my HTML, when commenting out the Portfolio construction plot part (first plot), the Efficient frontier plot renders perfectly (second plot). So it's definitely the portfolio plot that comes first that messes up the efficient frontier one, but why? from re import search from sys import set_coroutine_origin_tracking_depth from django.http.response import HttpResponse, HttpResponseRedirect from django.shortcuts import redirect, render from django.db.models import Q from datetime import datetime, date from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from io import BytesIO import base64 import pandas as pd import seaborn as sns from matplotlib.pyplot import figure from matplotlib import pyplot as plt sns.set() import os import riskfolio as rp from .forms import UploadFileForm def index(request): data_path = format(os.getcwd()) + "/app/data/" df = pd.read_csv(data_path + "portfolio_data.csv", sep=";", decimal=",") df['Date'] = pd.to_datetime(df['Date'], infer_datetime_format=True) df.set_index('Date', inplace=True) df = df.sort_values(by="Date", ascending=True) for column in df: df.insert(loc=df.columns.get_loc(column)+1,column= column + " Returns", value=df[column].pct_change()) returns_columns = [x for … -
Django, when i change the name of my pizza_type view function to something else it starts working, why. Im new here please be nice
My code here says that pizza_type or anything with pizza is not a valid view function and i don't understand why. <p> <a href="{% url 'pizzas:index' %}">Pizzeria</a> - <a href="{% url 'pizzas:pizza_type' %}">Pizzeria</a> </p> {% block content %}{% endblock content %} -
I would like to have my group-list-item div class to have all of the stuff inside inline vertically right now it is listed horizontally like a burger
Hi there creating an application where I can have the the inputs pop up on the bottom when they add them I was just wondering why after I add them the contents in my list group look like it's horizontally flipped, I want it to be vertically inline. Also I tried d-inline in group-list-item it didn't work. html file {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" /> <link rel="stylesheet" href="{% static 'habits/styles.css' %} " /> <title>Habit</title> </head> <body class="bg-light"> <!--good--> <div class="container"> <!--good--> <div class="row mt-5"> <!--good--> <div class="col-md-8 offset-md-2"> <!--good--> <div class="card"> <!--good--> <div class="card-header shadow-sm bg-white"> <h1 class="display-5 text-info"> Habits <i class="fa fa-unlock-alt" style="color: red"></i> </h1> <div class="card-body"> <ul class="list-group"> <li class="list-group-item"> <form action="{% url 'insert_habit_item'%}" method="post" autocomplete="off" > {% csrf_token %} <!-- value used by server to make sure if the post or response is from a trusted source or not --> <div class="input-group"> <input type="text" class="form-control" name="habit" /> <div class="input-group-append text-info"> <span class="input-group-text bg-white py-0" ><button type="submit" class="btn btn-sm text-info"> <i class="fa fa-plus-circle fa-lg"></i> </button> </span> </div> </div> </form> </li> {% for habit … -
How to use same serializer class for get and post method in Django?
I have been trying, but fail miserably, to use only a single serializer class for both post and get api call. I have a Person model which has some fields. What I need is I want to create a person object using post API with certain fields and however needs to show some other fields while doing get request. For eg: My model: class Person(models.Model): name = models.CharField(max_length=255,blank=True) email = models.EmailField(unique=True) phone = models.CharField(max_length=16) address = models.CharField(max_length=255,blank=True) roll = models.IntegerField() subject = models.CharField(max_length=255,blank=True) college_name = models.CharField(max_length=255,blank=True) Now my serializer will look like this. class PersonSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ['id','email','name','phone','roll','subject','college_name', 'address'] For eg, I have a view that handles both post and get request (probably using APIView), then what I need to do is, to create a person object I only using name, phone, and email. So for post API call, I only need three fields whereas while calling the get API I only need to display the fields name, roll, subject, and college_name not others. In this situation, how can I handle using the same serializer class?? -
AgoraRTC can't add multiple users in the webpage. can't figure out what went wrong
i was trying to make a streaming website using Agora.io in my JavaScript, i made a player template which will add to my webpage every time a new user enters. the client.on method should detect a new user coming & call back the function which should add the new user to the stream! const APP_ID = "fe45f285661941ada5ef5d451fe8f626" const CHANNEL = "main" const TOKEN = "006fe45f285661941ada5ef5d451fe8f626IABxEPnj4KCl8i4+gcrg2F7Cc+nmjmOiRWq49ICnSOHfdGTNKL8AAAAAEACXVkQu42OcYgEAAQC9Y5xi" const client = AgoraRTC.createClient({mode:"rtc",codec:"vp8"}) let localTracks = [] let remoteUsers = {} let UID let joinAndDisplayLocalStreams = async ()=> { client.on("user-published",handleUserJoined) UID = await client.join(APP_ID,CHANNEL,TOKEN,null) localTracks = await AgoraRTC.createMicrophoneAndCameraTracks() let player = ` <div class="video-container" id="user-container-${UID}"> <div class="name-wrapper"><span class="user-name">My name</span></div> <div class="video-player" id="user-${UID}"></div> </div>` document.getElementById("video-streams").insertAdjacentHTML("beforeend",player) localTracks[1].play(`user-${UID}`) await client.publish([localTracks[0],localTracks[1]]) } let handleUserJoined = async(user,mediaType)=>{ remoteUsers[user.uid]= user await client.subscribe(user,mediaType) console.log(mediaType) if(mediaType==="video"){ let player = document.getElementById(`user-container-${user.uid}`) if(player!=null){ player.remove() } player = `<div class="video-container" id="user-container-${user.uid}"> <div class="name-wrapper"><span class="user-name">My name</span></div> <div class="video-player" id="user-${user.uid}"></div> </div>` document.getElementById("video-streams").insertAdjacentElement("beforeend",player) user.videoTrack.play(`user-${user.uid}`) } if(mediaType==="audio"){ user.audioTrack.play() } } joinAndDisplayLocalStreams() -
Creating a login page without registration
I want to list all my datas in one admin page. But it will be just one username and password. I won't create any registration page. How can I do that?(I'm using Django 1.11) Thanks for your help. -
How do I create a dynamic "About Me" page in Django?
Here, by dynamic I mean, I wouldn't want to update my template in order for me to update changes. I'd want them to edit in the admin page on my production site. At first, I thought I'd create a model for "About Me" itself, but then I'd need to create a model for just one instance. I need help with this, better ways to edit my pages dynamically on the admin site. -
Should i manualy save client ID and client secrets? using django rest framework
This is my first django rest framework project and my question is about manually saving clientID and client secrets vs using a package that automates this. What I am trying to build is something similar to the Spotify developer dashboard. It gives each user the option to create several projects. Once a project is created, the user gets a client ID and a client secret for the project (both are different for each project the user creates). Like in other API dashboards users can generate a new client secret. This is what it looks like: My first shot at solving this topic was to handle all user-level authorization (like browsing through the website using the developer dashboard) with simple-jwt token authorization, which will handle the blacklisting of tokens and many other things itself. But for the project level authorization, I am manually saving a permanent client ID and client secret as UUID to the project model. Here you can see the project model (it extends from a base model which includes a UUID as Primary key + date created + date modified). Blacklisted client secrets will be moved to a custom blacklist model when users want o generate a new … -
I am trying to figure out how to increment and decrement the values with Django but I get this error cannot unpack non-iterable ModelBase object
Hi there I am having an issue incrementing and decrement a value in the views.py file in my application, also I am getting the error of "cannot unpack non-iterable ModelBase object" Everything else works beside the increment and decrement function. As soon as I press the increment or the decrement button it does not work and it spits that error out. Also I will post the view.py file, the html file, and the urls just so there can be more context. the views.py file from django.shortcuts import get_object_or_404, redirect, render from django.http import HttpResponse,HttpRequest from .models import Habit # Create your views here. def list_habit_items(request): context = {'habit_list':Habit.objects.all()} return render(request,'habits/habit_list.html',context) def insert_habit_item(request:HttpRequest): habit=Habit(IndHabit =request.POST['habit']) habit.save() return redirect('/habits/list/') def delete_habit_item(request,habit_id): habit_to_delete = Habit.objects.get(id=habit_id) habit_to_delete.delete() return redirect('/habits/list/') def increment_habit_value(request,habit_id): habit_to_increment = Habit.objects.get(Habit,id=habit_id) habit_to_increment.values += 1 habit_to_increment.save(['values']) return redirect('/habits/list/') def decrement_habit_value(request,habit_id): habit_to_decrement = Habit.objects.get(Habit,id=habit_id) habit_to_decrement.values -= 1 habit_to_decrement.save(['values']) return redirect('/habits/list/') the models class Habit(models.Model): #this makes a attribute that describes the individual Habit #the individual Habit and Value. IndHabit=models.TextField() IndValue=models.IntegerField() the urls.py file from django.urls import path from . import views urlpatterns=[ path('list/',views.list_habit_items), path('insert_habit/',views.insert_habit_item,name='insert_habit_item'), path('delete_habit/<int:habit_id>',views.delete_habit_item,name='delete_habit_item'), path('increment_habit/<int:habit_id>',views.increment_habit_value,name='increment_habit_value'), path('decrement_habit/<int:habit_id>',views.decrement_habit_value,name='decrement_habit_value'), ] the html file {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> … -
django.db.utils.ProgrammingError: relation "app_bugs" already exists
After I deleted all the migration files and made them again using "python3 manage.py makemigrations" and "python3 manage.py migrate", the following error occurred: root@chat-manager:/var/www/jinabot# python3 manage.py migrate Operations to perform: Apply all migrations: admin, app, auth, contenttypes, sessions Running migrations: Applying app.0002_auto_20220604_2133...Traceback (most recent call last): File "/usr/local/lib/python3.7/dist-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.DuplicateTable: relation "app_bugs" already exists The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 23, in <module> main() File "manage.py", line 19, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/dist-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/dist-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.7/dist-packages/django/core/management/commands/migrate.py", line 246, in handle fake_initial=fake_initial, File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/operations/models.py", line 92, in database_forwards schema_editor.create_model(model) File "/usr/local/lib/python3.7/dist-packages/django/db/backends/base/schema.py", line 331, in create_model self.execute(sql, params or None) … -
how to keep loop runnning while user gets redirected back to form after making a post request to start the loop
I have a django app with a view that handles a post request from a user to start an infinite loop. The problem is after succesful post request loop starts and the browser keeps loading waiting for response from the server resulting to timeouts from proxy server handling this request. Is there anyway to start the loop and keep it running while redirecting or giving back response to the browser to prevent timeouts view code below: def ticket_miner(request): mining_urls = credentials.mining_urls if request.method == 'GET': form = forms.UpdateForm() return render(request, 'tickets/mine.html', {'form': form}) else: net_test = network_acess.network_test(urlpaths.net_urls) while net_test: with requests.session() as s: try: print('logging in ....') s.post(login_url, data=payload, headers=headers, timeout=5) r = s.get(success_url, timeout=5) print(r) if r.status_code == 200: print('Logged in successfully') while r: count = 0 for mining_url in mining_urls: r2 = s.get(mining_url, timeout=5) count += 1 response_result = r2 if response_result.status_code == 404: print('TICKET NOT FOUND!') pass else: new_data = response_result.json() miner.ticket_mapper(new_data) print('mining') continue print('mining successfull restarting ...') else: print('Unable to authenticate... redirect detected') except requests.exceptions.ConnectionError as e: print(f'ConnectionError: {e.response} response. No internet connections!!') except requests.exceptions.InvalidURL as e: print(f'InvalidURL: {e.response} response. Incorrect url specified!!') except requests.exceptions.Timeout as e: print(f'ConnectTimeout: {e.response} response. Network interrupt') except requests.exceptions.RequestException as e: … -
Django automated email sending
I am building a multivendor market place using django and I have to send automated emails for two reasons. I have to verify their email each time someone signs up (A verification email will automatically be sent when they completed their form). Automated email is sent to the user when order is ordered. All the above worked fine when I test them, but I used my gmail account for that purpose. I have read that gmail is not the perfect choice for business purposes. Plus there is no online payment system in my country for payed services and all the free options I see can only send very limited emails per day. So should I continue using gmail? Or is there any other system I can use? Thank you in advance! -
How can I utilize the JWT for authintication and authorization in Django
I started learning Django two weeks ago, while I was searching for authentication and authorization in Django I found the following lines for Jason Web Tokens (JWT): project urls.py from django.contrib import admin from django.urls import include, path from rest_framework_simplejwt import views as jwt_views urlpatterns = [ path("admin/", admin.site.urls), path("api/v1/cookie-stand/", include("cookie_stands.urls")), path("api-auth/", include("rest_framework.urls")), path( "api/token/", jwt_views.TokenObtainPairView.as_view(), name="token_obtain_pair", ), path( "api/token/refresh", jwt_views.TokenRefreshView.as_view(), name="token_refresh", ), ] app permission.py from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True if obj.owner is None: return True return obj.owner == request.user My question is: Tokens are usually sent as a header with the request, how does Django do that? I mean for example, how can I use Django and JWT to make an authorized group of users? -
Correct way to define the initial value of a form field in Django from a database, when database values may change
I am trying to create an interview feedback capture app using Django. The interview feedbacks follow a template. The template would evolve with time. Therefore whenever a new interview feedback template is available, it is updated to the database by an admin user. Whenever an interviewer opens the app, he should see the latest value of the template available in the database as the initial value of the feedback form. Currently I am able to provide the initial value of the feedback field using the 'initial' argument of the feedback field. Below is the code: from django import forms from .models import R1 from .model_templates import template_R1 from ckeditor.widgets import CKEditorWidget class R1Form(forms.ModelForm): interview_date = forms.DateField(widget = DateInput()) feedback = forms.CharField(widget = CKEditorWidget(), initial = template_R1.objects.all().last().template) class Meta: model = R1 fields = ['interview_date', 'interviewers', 'comment', 'recommended_level', 'progress'] The problem with this approach if that if the template is updated the form field still shows an earlier snapshot of the template when the django server was started. Is there any other way the form field would show dynamic values as soon as the template is updated in the database? -
Translation Memory TM (Computer assisted translation system ) CAT Tools
Can anyone help me how to code a translation memory (TM) using language python Django as I am going to build a web-based Computer assisted translation system (CAT) everything else is done only only thing remains.? Or suggest me any GitHub repository. -
Django AssertionError when testing Create View
I'm running some tests for my app 'ads', but when I try to test the CreateView it fails with the following message: AssertionError: 'just a test' != 'New title' Here's the test: class AdTests(TestCase): def setUp(self): self.user = get_user_model().objects.create_user( username='test_user', email='test@email.com', password='secret' ) self.ad = Ad.objects.create( title='just a test', text='Ehy', owner=self.user ) def test_ad_create_view(self): response = self.client.post(reverse('ads:ad_create'), { 'title': 'New title', 'text': 'New text', 'owner': self.user.id, }) self.assertEqual(response.status_code, 302) self.assertEqual(Ad.objects.last().title, 'New title') self.assertEqual(Ad.objects.last().text, 'New text') So it could be that the test fails in creating a new ad, and then it compares the fields with the first ad in the setUp method. I upload the rest of the code if it can help: urls.py from django.urls import path, reverse_lazy from . import views app_name='ads' urlpatterns = [ path('', views.AdListView.as_view(), name='all'), path('ad/<int:pk>', views.AdDetailView.as_view(), name='ad_detail'), path('ad/create', views.AdCreateView.as_view(success_url=reverse_lazy('ads:all')), name='ad_create'), ... ] models.py class Ad(models.Model) : title = models.CharField( max_length=200, validators=[MinLengthValidator(2, "Title must be greater than 2 characters")] ) price = models.DecimalField(max_digits=7, decimal_places=2, null=True) text = models.TextField() """We use AUTH_USER_MODEL (which has a default value if it is not specified in settings.py) to create a Foreign Key relationship between the Ad model and a django built-in User model""" owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) comments = … -
why TemplateDoesNotExist at / index.html
i cant findout my problem this is views.py file from django.http import HttpResponse from django.shortcuts import render def aboutUs(request): return HttpResponse('hello BD') def homePage(request): return render(request,"index.html") this is urls.py """wscubetech_firstproject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from wscubetech_firstproject import views urlpatterns = [ path('admin/', admin.site.urls), path('about-us/',views.aboutUs), path('',views.homePage), ] this is settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR,"templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] The error messagr is: TemplateDoesNotExist at / index.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.0.2 Exception Type: TemplateDoesNotExist Exception Value: index.html Exception Location: C:\Python310\lib\site-packages\django\template\loader.py, line 19, in get_template Python Executable: C:\Python310\python.exe Python Version: 3.10.2 Python Path: ['C:\Users\Asus\Desktop\31-5-22 Django\wscubetech_firstproject', 'C:\Python310\python310.zip', 'C:\Python310\DLLs', 'C:\Python310\lib', 'C:\Python310', 'C:\Python310\lib\site-packages'] Server time: Sat, 04 … -
CSS not applying to image in django
I am trying to create a django app in which i have inserted an image. But css rule is not applying on the image. Image is inside a div which is inside a section html file code: <!DOCTYPE html> {% load static %} <html lang="en"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <head> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}" /> <meta charset="UTF-8"> <title>Venkatesh Akhouri</title> </head> <body> <div class="conatiner"> <nav class="navbar navbar-expand-sm navbar-light"> <a class="nav-item nav-link" href="#">Home</a> <a class="nav-item nav-link" href="#">Contact</a> <a class="nav-item nav-link" href="#">Skills</a> <a class="nav-item nav-link" href="#">Projects</a> </nav> </div> <section id="small-info"> <div class="row"> <div class="col-md"> <img class="my-img" src="{% static 'images/myImg2.jpg' %}" alt="no img"> </div> <div class="col-md"> <h3> some info</h3> </div> </div> </section> CSS: body { background-color: #cce6ff; } .nav-item { font-family: font-family: Helvetica, sans-serif; color: black; } .col-md { float: left; width 50%; } #small-info .col-md { width: 10px; border-radius: 50px; } I know there is some foolish mistake here, but i am not able to identify. I've also tried w/o any div but still not working. -
Django POST requests from Postman forbidden after HEROKU DEPLOYMENT
I uploaded my Django REST Framwork project to Heroku after following the steps carefully. https://www.youtube.com/watch?v=TFFtDLZnbSs&t=193s&ab_channel=DennisIvy In my project, I used BEARER tokens with jwt. My database is PostgreSQL which is provided by Heroku. It worked perfect while working locally but after deployment, I couldn't send requests through Postman. Any ideas? 2022-06-04T16:36:50.456061+00:00 heroku[router]: at=info method=POST path="/api/login" host=roy-messenger.herokuapp.com request_id=******-****-****-****-********** fwd="**.***.***.**" dyno=web.1 connect=0ms service=46ms status=403 bytes=3660 protocol=https 2022-06-04T16:36:50.458497+00:00 app[web.1]: Forbidden (Referer checking failed - no Referer.): /api/login 2022-06-04T16:36:50.459018+00:00 app[web.1]: 10.1.10.154 - - [04/Jun/2022:16:36:50 +0000] "POST /api/login HTTP/1.1" 403 3372 "-" "PostmanRuntime/7.29.0" . settings.py """ Django settings for abra project. Generated by 'django-admin startproject' using Django 4.0.5. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path from datetime import timedelta import os import django_heroku import dj_database_url # 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/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['roy-messenger.herokuapp.com', '127.0.0.1'] CSRF_TRUSTED_ORIGINS = ['roy-messenger.herokuapp.com'] # Application definition … -
Filter Categories from list of Products in Django templates
So I'm working on this Django e-commerce website where I'm supposed to filter the products on my page based on three separate categories. Since there were only three fixed categories, I decided to create a dictionary in my model class for Products and thought there would be a way to filter products later on in my templates accordingly using a {%For%} loop. It's not working as I expected tho and I'm getting errors, probably because I'm not that familiar with Django and don't know how to get my way around it. Would greatly appreciate the help! (I've attached some screenshots for context) MODELS.products screenshot working implementation of for loop that directly shows all products Views.catalogue -
How to render a value of a single variable to a template using Django?
I am building a web application where the completion of the project (status) is returned to the client(user) through a dynamic URL. The view looks something like this:1 I want to retrieve the single value from phase field (phase field stores integer values from 1 to 10) and perform percentage = (phase / 10) * 100. How can I render the query phase and render percentage variable which stores the percentage, to template? Here's my model.py: from cmath import phase from pyexpat import model from django.db import models from sqlalchemy import delete class Project(models.Model): STATUS = ( ('Inititated', 'Inititated'), ('Paused', 'Paused'), ('In progress', 'In progress'), ('Aborted', 'Aborted'), ('Completed', 'Completed') ) PHASE = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'), ('8', '8'), ('9', '9'), ('10', '10') ) p_id = models.IntegerField(null=True) p_name = models.CharField(max_length=100, null=True) c_name = models.CharField(max_length=100, null=True) c_mail = models.CharField(max_length=100, null=True) init_date = models.DateField(null=True) ect = models.DateField(null=True) status = models.CharField(max_length=200,null=True, choices=STATUS) collabs = models.IntegerField(null=True) phase = models.CharField(max_length=100,null=True, choices=PHASE) def __str__(self): return self.p_name views.py: from cmath import phase from multiprocessing import context import re from unicodedata import name from django.shortcuts import render from django.http import HttpResponse from .models import Project from django.shortcuts import … -
Form not submitting to correct url in django
Im making a web app in django and im having a problem with a form which isnt submitting to the correct place searcc.html <form method='POST', action='/saveApply'"> {% csrf_token %} <div class="JobSub"> <input value="{{user.id}}" name="usrid"> <input value="{{comp.id}}" name="compid"> <button type="submit">Submit</button> </div> </form> views.py def saveApply(request): current_user = request.user if request.method == 'POST': # Foreign key to User is just the username savedApply.objects.create( user = request.POST.get('usrid'), company = request.POST.get('company') ) return render('main/profile.html') # Change later return redirect('login') The confusing thing is, when I press on the submit button Im not even getting sent to the login view. I am getting sent to the home page. I think the problem has something to do with the fact that this html page is getting included in another. main.html {% include 'main/search.html' %} {% endblock %} Main.html is also inheriting from another file -
Why can't i display my foreign key instance in Django?
I'm having trouble in viewing items from a list using foreign key. I have no problems with other models, but this one seems tricky. I'm not getting something I guess... The assignement is about creating a rental place that rents movies, books and music cd's. I've created a model for Cd's and hooked a model called "songs" to it with a foreign key. Here's the code: Models: class Cd(models.Model): cd_band=models.CharField(max_length=100) cd_title=models.CharField(max_length=100) CD_GENRE= ( ('POP', "POP"), ("HIP", "Hip-Hop"), ("ROC", "Rock"), ("BLU", "Blues"), ("SOU", "Soul"), ("COU", "Country"), ("JAZ", "Jazz"), ("CLA", "Classical music"), ) cd_genre=models.CharField(max_length=3, choices=CD_GENRE) cd_length=models.DurationField() cd_rental=models.ForeignKey(Rental, on_delete=models.CASCADE, default=1) class Songs(models.Model): song=models.CharField(max_length=50) song_duration=models.CharField(max_length=10, default='') list_number=models.ForeignKey(Cd, on_delete=models.CASCADE, related_name='song_name') def __str__(self): return "{} {}".format(self.song, self.song_duration) template: {% block content2 %} {%for songs in object_list%} <div class="song-entry"> <h3>{{object.song_name}}</h3> </div> {% endfor %} {% endblock content2 %} -
Django Query Annotation Does Not Support math.tan() Calculation
I have a django 3.2/mysql website. One of the tables, Flights, has two columns, angle and baseline. These two columns are combined in a view to display the value altitude using the formula altitude = baseline * tan(angle). I am building a search form for this table, and the user wants to search for flights using a minimum altitude and a maximum altitude. My normal approach to the problem is to gather the inputs from the search form, create appropriate Q statements, and use query the table with filters based on the Q statements. However, since there is no altitude field, I have to annotate the query with the altitude value for the altitude Q statement to work. It seems that a query annotation cannot use an expression like math.tan(field_name). For example, Flights.objects.annotate(altitude_m=ExpressionWrapper(expression=(F('baseline') * math.tan(F("angle"))), output_field = models.FloatField(),),) generates the error builtins.TypeError: must be real number, not F whereas the expression Flights.objects.annotate(altitude_m=ExpressionWrapper(expression=(F('baseline') * F("angle")), output_field = models.FloatField(),),) does not generate an error, but also does not provide the correct value. Is there a way to annotate a query on the Flights table with the altitude value so I can add a filter like Q(altitude__gte= min_altitude) to the query? Or, is …