Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unity Facebook SDK Login, served with Django encounters CORS/CORB issues on Chrome
I am trying to get a very simple Unity application (Unity Version 2019.4.20f1 Personal) to authenticate with Facebook's SDK for unity. I have set up a local HTTPS server (with self-signed certificates) using Django & Gunicorn (Yes, not ideal, but just trying this out first), which serves the build products of Unity's WebGL. Here is my one and only script in unity: public class FacebookHelper : MonoBehaviour { // Awake function from Unity's MonoBehavior void Awake () { if (!FB.IsInitialized) { // Initialize the Facebook SDK FB.Init(InitCallback, OnHideUnity); } else { // Already initialized, signal an app activation App Event FB.ActivateApp(); } } private void InitCallback () { if (FB.IsInitialized) { // Signal an app activation App Event FB.ActivateApp(); // Continue with Facebook SDK // ... } else { Debug.Log("Failed to Initialize the Facebook SDK"); } } private void OnHideUnity (bool isGameShown) { if (!isGameShown) { // Pause the game - we will need to hide Time.timeScale = 0; } else { // Resume the game - we're getting focus again Time.timeScale = 1; } } public void Login() { var perms = new List<string>(){"public_profile", "email"}; FB.LogInWithReadPermissions(perms, this.AuthCallback); } public void Logout() { FB.LogOut(); Debug.Log("User logged out."); } public void … -
Django crispy-forms shows all tab under one tab
I have been upgrading a Django application from Python 2 and Django 1.11 and I found a very strange issue when I am trying to show a tabular fashion modal where 4 fours tabs are shown under 1 tab. The loading of this form seems to make the site load super slow as well. I have upgraded the django-crispy-forms library from 1.5.0 to 1.10.0. The bug's screenshot is shown here: The form template: incident_form.html {% load crispy_forms_tags i18n %} <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id="incidentForm">{% trans "Submit a new report" %}</h4> </div> <div class="modal-body"> <label class="control-label">{% trans "What kind of report is this?" %}</label> <!-- Nav Tabs --> <ul class="nav nav-tabs" role="tablist"> <li role="presentation" class="active"><a href="#incidentReport" role="tab" data-toggle="tab">{% trans "Collision or Fall" %}</a></li> <li role="presentation"><a href="#nearmissReport" role="tab" data-toggle="tab">{% trans "Near miss" %}</a></li> <li role="presentation"><a href="#hazardReport" role="tab" data-toggle="tab">{% trans "Hazard" %}</a></li> <li role="presentation"><a href="#theftReport" role="tab" data-toggle="tab">{% trans "Theft" %}</a></li> {% if request.user.is_staff %} <li role="presentation"><a href="#newInfrastructureReport" role="tab" data-toggle="tab">{% trans "New Infrastructure" %}</a></li> {% endif %} </ul> <!-- Tab panes --> <div class="tab-content"> <div role="tabpanel" class="tab-pane active" id="incidentReport"> <form action="{% url 'mapApp:postIncident' %}" method="POST" role="form" enctype="multipart/form-data"> {% crispy incidentForm %} </form> </div> <div role="tabpanel" class="tab-pane" id="nearmissReport"> <form action="{% … -
Django ignores the LANGUAGE_CODE and redirects the language that mi device/machine has
As i say, if a configure the language code "es" in my settings.py and i have my device or machine whit english settings, django redirects to the english version of my view, and if i do the opposite, configure "en" in the settings,py and try to enter whit a spanish device, the view is displayed in english version. Im currently using django 3.0.8 settings.py # middleware MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ PARLER_LANGUAGES = { None: ( {'code': 'es'}, {'code': 'en'}, ), 'default': { 'fallback': 'es', 'hide_untranslated': True, } } LANGUAGE_CODE = 'es' LANGUAGES = ( ('es', _('Spanish')), ('en', _('English')), ) TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale/'), ) urls.py of the proyect from django.utils.translation import gettext_lazy as _ from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.conf.urls.i18n import i18n_patterns urlpatterns = i18n_patterns( path(_('admin/'), admin.site.urls), path(_('cart/'), include('cart.urls', namespace='cart')), path(_('orders/'), include('orders.urls', namespace='orders')), path(_('payment/'), include('payment.urls', namespace='payment')), path(_('coupons/'), include('coupons.urls', namespace='coupons')), path('rosetta/', include('rosetta.urls')), path('', include('shop.urls', namespace='shop')), ) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urls.py app main from django.urls import path from . import views … -
Django deployment with nginx, gunicorn without virtual enviroment
I have a django website which was hosted using one click app option at digitalocean. Site gets good pageview and has grown bigger. I am moving the site to new server and do not want to use one click application option to do everything manually. I am not good at server part. Following this tutorial. https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 I am stuck on gunicorn part. Everything working fine till gunicorn --bind 0.0.0.0:8000 myproject.wsgi Can some one help on these points: How to setup Gunicorn I am not using virtualenviroment Project located at below directory: >>home/django_project Could not find a single solution on entire internet. Have hopes with experts here. -
Django DRF all routes are resulting in { "detail": "User not found", "code": "user_not_found" }
I am building an API with Django and DRF. It contains dj-rest-auth, allauth, simplejwt libraries for authentication procedures. Yesterday all links were working as supposed to, providing the relevant response based on the request. But now after I started working on the project again, I am getting the above error on all routes although nothing was changed. If I check the routes from the browser (drf interface), they work fine, but not in postman or from a mobile interface. Note that I restarted my device and changed the host as well just in case. -
How to set two different expiry time in djangorestframework-simplejwt for admin end and customer end?
I want to set 30 days of expiry time for customer login and 1 day expiry for admin login. How would I do that in djangorestframework-simplejwt. -
Djnago Model Object has no attribute '_default_manager' when using factory boy
I am using Django Rest Framework to create some api's. I am using factory boy to create test instances. I have an Abstract model called base_model which is inherited by all other models of the project. created_at = models.DateTimeField(editable=False) updated_at = models.DateTimeField(editable=False) class Meta: abstract = True ordering = ['id'] def save(self, *args, **kwargs): if not self.created_at: self.created_at = timezone.now() self.updated_at = timezone.now() super(BaseModel, self).save(*args, **kwargs) My client Model from django.db import models from mtl_manager.api.base_model import BaseModel from mtl_manager.projects.enums import ProjectStatus class Client(BaseModel): client_name = models.CharField(max_length=250, blank=False) phone_number = models.CharField(max_length=250, blank=False) email = models.EmailField(blank=False, unique=True, null=False) addressLane1 = models.TextField() This model worked. I was able to create retrieve and list client objects . Now I was about to unit test the routes and started with creating instance using Factory boy class ClientFactory(DjangoModelFactory): name = Faker("company") gst = "323232"; phone_number = Faker("phone_number") zipCode = "686542" address_lane = Faker("street_address") registration_number = "32313094839483" state = "kerala" country = Faker("country") class Meta: model = Client() This raises error Attribute-error: 'Client' object has no attribute '_default_manager'. But from my console I verified if client has default manager using In [11]: Client.objects Out[11]: <django.db.models.manager.Manager at 0x7fe4fc6d7bb0> -
Running Django command /generating index with manage.py
I need to run to Heroku a web job that every night needs to generate the index for Elasticsearch, I wanted to know if is possible. The command that I need to run on the python shell automatically are: heroku run python3 manage.py shell --app My_app from aliss.search_tasks import delete_index, create_index, index_all; delete_index(); create_index(); index_all(); Thank you very much for the help. -
How to to use django createsuperuser --noinput command
I'm fairly new to django and python and know this is a basic question, but if anyone is able to tell me what I'm doing wrong and/or how to correctly struture a non-interactive django createsuperuser command (https://docs.djangoproject.com/en/3.1/ref/django-admin/#createsuperuser), I'd be really grateful. I would like to use this to create a superuser on a google cloud-run app I have running, and am trying to get this to work locally (on a seperate app created for testing purposes), but can't seem to. I've found surprisingly little about from quite a bit of googling and browsing Stackoverflow (probably because it's too obvious). I have a basic django app that is working locally on Ubuntu with a CustomUser model in place. I'm able to create a superuser interactively without a problem. I have DJANGO_SUPERUSER_PASSWORD/EMAIL/USERNAME defined in my settings.py as detailed below (I know I will need to remove actual values in the future but just want to get it to work first). # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Local 'accounts', ] AUTH_USER_MODEL = 'accounts.CustomUser' DJANGO_SUPERUSER_PASSWORD = 'xxx' DJANGO_SUPERUSER_EMAIL = 'xxx@email.com' DJANGO_SUPERUSER_USERNAME = 'xxx' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'config.urls' … -
Django app asynchronous Celery tasks fail when run under Docker
I have a distributed app that comprises three servers. Two are DRF servers and the third is a Django app. The Django app spawns asynchronous Celery tasks that send requests to the first DRF server. The Celery task results are written to the database of the second DRF server. The three servers are all on the same network. These services are now working correctly except that Celery tasks fail to access the DRF server when run asynchronously. The Celery tasks run fine when run synchronously. I don't know how to debug or fix this problem. Here is console output after remote shelling into the Django app's container: root@f9986ad51d60:/code# echo $DJANGO_SETTINGS_MODULE pop_model.settings.compose root@f9986ad51d60:/code# ./manage.py shell [TerminalIPythonApp] WARNING | Config option `deep_reload` not recognized by `TerminalInteractiveShell`. Python 3.6.9 (default, Jul 18 2019, 03:19:08) ... [ins] In [3]: from game.tasks import change_run_phase_task [ins] In [4]: change_run_phase_task('a', 'Play') Out[4]: "Run 'a' (id: 3)\ngetting run's current_phase: Setup\ngetting new phase: Play\nupdating run to phase: Play\n" Running the same Celery task asynchronously fails to query the DRF server: [ins] In [5]: task = change_run_phase_task.delay('a', 'Play') [ins] In [7]: print(task) 448b0828-b9c7-44a0-b7e1-34e41aaa780d model.celery_1 | [2021-02-25 15:05:16,758: INFO/MainProcess] Received task: game.tasks.change_run_phase_task[448b0828-b9c7-44a0-b7e1-34e41aaa780d] model.celery_1 | [2021-02-25 15:05:16,775: INFO/ForkPoolWorker-4] Task game.tasks.change_run_phase_task[448b0828-b9c7-44a0-b7e1-34e41aaa780d] succeeded in … -
JSON parse the fields which user wants in Django REST API framework
I want to make users to be able to change some values of the object. For example, there is an event with ID "Id1" at "20.12.2021 14:00:00+00:00", a title of the event "the title", a description - "the description" and participants of the event ["Anne", "Jean", "Eren", "Sasha", "ME"]. I need to write a view which allows a user to change/update any of this values. If he wants, he can change only datetime, or only participants, or only title, or datetime AND title, or all the fields at once(although it is better to create a new event if it is needed to change everything in the first event, but anyways). So I need to know how to write a view which allows user to JSON parse only the fields he wants. -
Pipenv doesn't recognize virtual environment that was created by itself
I'm new to pipenv and it might be some very newbie problem I'm facing. I'm using python 3.9 and installed pipenv using python3 -m pip install pipenv. I have a project with a requirements.txt and after running pipenv install it was supposed to create a virtual environment but after running pipenv shell and pipenv run src/manage.py runserver it says: Error: the command src/manage.py could not be found within PATH or Pipfile's [scripts] The virtual environment was created at /Users/myuser/.local/share/virtualenvs/project1-iLzXCwVe and not at the working space. Is it possible it has something to do with that? Any way this can be solved? -
Adobe Analytics Consent Preferences Manager doesn't work in Django
While implementing Adobe Analytics in my project, I am facing an issue in my Django project. I have done implementation in reactJS and it works but it didn't work in Django. The following popup appears in both Django and reactJS Image : Adobe Analytics Consent Manager popup on clicking CONFIRM in reactJS, its start sending data. google chrome screenshot of data but on clicking CONFIRM in django it doesnt send any data.google chrome screenshot of data Help link : Adobe analytics help link I added the following line in my code in <\head> tag <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://tags.tiqcdn.com/utag/**/********/prod/utag.js"></script> in <\body> tag <script type="text/javascript"> (function(a,b,c,d){ a='//tags.tiqcdn.com/utag/**/*******/prod/utag.js'; b=document;c='script';d=b.createElement(c);d.src=a;d.type='text/java'+c;d.async=true; a=b.getElementsByTagName(c)[0];a.parentNode.insertBefore(d,a); })(); </script> ReactJS (Index.html) <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="theme-color" content="#000000"> <link rel="manifest" href="%PUBLIC_URL%/manifest.json"> <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> <title>React App</title> <!-- Adobe analytics --> <script src="https://tags.tiqcdn.com/utag/**/*********/prod/utag.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> </head> <body> <!-- Loading script asynchronously --> <script type="text/javascript"> (function(a,b,c,d){ a='//tags.tiqcdn.com/utag/**/*********/prod/utag.js'; b=document;c='script';d=b.createElement(c);d.src=a;d.type='text/java'+c;d.async=true; a=b.getElementsByTagName(c)[0];a.parentNode.insertBefore(d,a); })(); </script> </body> </html> Django (Index.html) {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500"> <link rel="icon" href="/static/bundles/favicon.ico"> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width" /> <title>SharkSpray</title> <style type="text/css"> .hidden { display: none; } body { min-width: 600px; … -
Can not group by queryset django
I have a queryset like this: <QuerySet [{'company_id': 999, 'сurrent_burn_rate': Decimal('70125.00')}, {'company_id': 999, 'сurrent_burn_rate': Decimal('2892.00')}, {'company_id': 999, 'сurrent_burn_rate': Decimal('32811.00')}}]> All company_id are 999. I want to group by it by id and make sum of сurrent_burn_rate. I make this code: Objects.all().values('company_id').annotate(total=Sum('сurrent_burn_rate')) I expected: <QuerySet [{'company_id': 999, 'total': 'Toal sum of all records with id 999'}]> But get: <QuerySet [{'company_id': 999, 'total': Decimal('70125.00')}, {'company_id': 999, 'total': Decimal('2892.00')}, {'company_id': 999, 'total': Decimal('32811.00')}}]> why it is don't work? -
Is it possible to pass extra data to the django admin form as argument?
I have a Django model with the implemented Django admin interface and I want to display the form for the model. If the form displays only the attributes of the model, it's a simple task. My problem is that I would like to change the fields of the form depending on the user authenticated. Is there any way how to pass extra data (user) as an argument to the ModelForm init function from the admin? I found some tutorials, but their implementation worked only for basic views, not for the Admin implementation. I have also tried to pass an extra argument to the admin get_form() function, but it is not possible to. I get the error that an unexpected argument was provided. -
Using @login_required for queries/mutations in django-graphql-jwt leads to graphql.error.located_error.GraphQLLocatedError
I'm a begginer with GraphQL and started developing a small app using Django and decided to use django-graphql-jwt for authentication. I can use the getTokenAuth, VerifyToken and RefreshToken with no problem. But when I try to use a query with decorator @login_required, all I get is a "GraphQLLocatedError: You do not have permission to perform this action" response. But, somehow, the unit tests are working nicely. My code: settings.py MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] GRAPHENE = { "SCHEMA": "myproject.graphql.api.schema", "MIDDLWARE": [ "graphql_jwt.middleware.JSONWebTokenMiddleware", ], } GRAPHQL_JWT = { "JWT_ALLOW_ARGUMENT": True, "JWT_VERIFY_EXPIRATION": True, "JWT_EXPIRATION_DELTA": timedelta(minutes=5), "JWT_REFRESH_EXPIRATION_DELTA": timedelta(days=7), "JWT_AUTH_HEADER_NAME": "Authorization", "JWT_AUTH_HEADER_PREFIX": "Bearer", } AUTHENTICATION_BACKENDS = [ "graphql_jwt.backends.JSONWebTokenBackend", "django.contrib.auth.backends.ModelBackend", ] queries.py from graphene import String, ObjectType from graphql_jwt.decorators import login_required class HelloQuery(ObjectType): hello = String(name=String(default_value="stranger")) @login_required def resolve_hello(self, info, name): return f"Hello {name}!" tests.py from graphql_jwt.testcases import JSONWebTokenTestCase from users.factories import UserFactory class QueryTest(JSONWebTokenTestCase): def setUp(self): self.user = UserFactory() self.client.authenticate(self.user) super().setUp() def test_00_hello(self): """ This test evaluates the HelloQuery """ query = """ query hello { hola: hello(name: "tester") } """ result = self.client.execute(query) self.assertIsNone(result.errors) self.assertEqual("Hello tester!", result.data["hola"]) Request info POST http://localhost:8000/graphql 200 34 ms Network Request Headers X-CSRFToken: 7ZZrDHmpkly1FHexdLASComfiqCo81iaHOHJuywRabRHsdIDgKbBXK3ex687G7Xt Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImpvY2hvIiwiZXhwIjoxNjE0MjczNTcxLCJvcmlnSWF0IjoxNjE0MjczMjY0fQ.C6yDzim5jliu6yIMDJ70Xl3WPP69HpYTR0VSGmy0brc Content-Type: application/json User-Agent: PostmanRuntime/7.26.10 Accept: … -
Make sure the user is uploading video not anything else in djano
How to make sure the user is uploading video not anything else in Django in FileField. I want to make function is valid the fileinput is video not anything else, otherwise show warning I using Django forms. My view def VideosUploadView(request, *args, **kwargs): V_form = Video_form() video_added = False if not request.user.is_active: # any error you want return redirect('login') try: account = Account.objects.get(username=request.user.username) except: # any error you want return HttpResponse('User does not exits.') if 'submit_v_form' in request.POST: print(request.POST) V_form = Video_form(request.POST, request.FILES) if V_form.is_valid(): instance = V_form.save(commit=False) instance.author = account instance.save() V_form = Video_form() video_added = True if instance.save: return redirect('home') My form class Video_form(forms.ModelForm,): class Meta: model = Video fields = ('video') widgets = { 'video': forms.FileInput(attrs={'class': 'custom-file-label ', 'id': 'formGroupExampleInput2'}), } -
What does this means <int:question_id>?
When I was reading Django documentation I noticed this line of code path('<int:question_id>/vote/', views.vote, name='vote'). What is <int:question> for? Is it specific to Django or is it something taken from python? -
Set a result on a Celery task when the task fails
I would like to set a result to a celery task when it fails. I want to be able to show a tailored message depending which kind of error occurred while processing the task. As I have checked, the only way to define a task as failed is when an exceptions is raised during the task. If the task gets to the final code line the status is always 'SUCCESS', even if I try to change it manually. My result backend is using Redis I thought about querying the task id on the error callback, but it seems wrong to do that. Here is how I call the task: run_long_process.apply_async(args=(instance.id, ), link=commit_instances.s(), link_error=rollback_instances.s(), ) The tasks: @shared_task(bind=True) def run_long_process(self, some_parm): . . . if some_condition: // I tried here to do something like self.update_state(state='FAILURE') without // raising the exception raise CustomException("Error") return {some_response} @shared_task def rollback_instances(request, exc, traceback): //I want to set a message or something and when I query the task id I get the result with //state FAILURE doSomethingElse() @shared_task def commit_instances(*args, **kwargs): doSomething() Is there Celeryiesque way to accomplish this, if so. -
i`m getting the 400 response error in react.js i know the backendd is ok but the client side i am not sure i am not fimiliar with react
i cant create a class and i dont know why i am not fimiliar with react so much i am learning from this project i set for my self so please help i am working on it for 2 days and i dont know why this is happenning #this is my view i know this one is working class CreateClassRoomView(APIView): serializer_class = CreateClassRoomSerializer def post(self, request, format=None): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): ostad = request.data['ostad.name'] lesson = request.data['lesson.name'] day = request.data.get('day') lesson_obj = Lesson.objects.get(name=lesson) master_obj = Master.objects.get(name=ostad) room = ClassRoom.objects.create( ostad=master_obj, lesson=lesson_obj, day=day ) room.save() return Response(CreateClassRoomSerializer(room).data, status=status.HTTP_201_CREATED) else: return Response( { 'message': "This is problem" }, status=status.HTTP_400_BAD_REQUEST ) serializer from rest_framework import serializers from .models import (ClassRoom, Lesson, Master) class StringSerializer(serializers.StringRelatedField): def to_internal_value(self, value): return value class LessonSerializer(serializers.ModelSerializer): class Meta: model = Lesson fields = ( 'name', ) class MasterSerializer(serializers.ModelSerializer): class Meta: model = Master fields = ( 'name', ) class ClassRoomSerializer(serializers.ModelSerializer): lesson = LessonSerializer() ostad = MasterSerializer() class Meta: model = ClassRoom fields = ( 'id','user', 'code','image', 'ostad', 'lesson', 'slug', 'deadline', 'day' ) class DetailClassRoomSerializer(serializers.ModelSerializer): lesson = LessonSerializer() ostad = MasterSerializer() class Meta: model = ClassRoom fields = ( 'code','image', 'ostad', 'lesson', 'slug', 'deadline', 'day' ) class CreateClassRoomSerializer(serializers.ModelSerializer): … -
Can not print specifict values from an api response dictionnary (Dango)
i'm ne to Django and APIs and i'm struggling with this for days. Here's my views.py file : import requests import os from pprint import pprint from django.views.generic import TemplateView import json from django.http import JsonResponse, HttpResponse from django.shortcuts import render def index(request): query_url = "https://api.blockcypher.com/v1/btc/main" params = { "state": "open", } headers = { } result = requests.get(query_url, headers=headers, params=params) json_data = result.json() data = json.dumps(json_data, sort_keys=True, indent=4) t = json.loads(data) print(type(data)) print(type(t)) context = { "t": t, } return render(request, "navbar/navbar.html", context) And here's the index.html : {% load static %} <!DOCTYPE html> <html> <head> <title>Blockchain Explorer</title> <meta charset="utf-8"> </head> <body > <div class="API-response"> {{ t }} </div> </body> </html> But when i try to do for example : {{ t["height"] }} i get an error : (TemplateSyntaxError at / Could not parse the remainder: '["height"]' from 't["height"]') Please help me and excuse me if it is a dumb question, i'm still a beginner in this framework -
dynamically getting parameters and adding condition in Dataframe
I am working on a Django project in addition to Pandas Dataframe. I am having a multiple dropdown in my from for multiple selection. I have to get the parameter from the url and get the data from Dataframe with OR condition as per the parameter obtained. I am trying as: names_in_param = request.GET.getlist('names') #get the params list_names_in_param_with_df = [] for i in names_in_param: name = f'df["name"] = "{i}"' list_names_in_param_with_df.append(name) param_name = " | ".join(list_names_in_param_with_df) df = df[param_name] return df let say we have name as "Tom" and "Harry" then we are getting param_name as df["name"]="Tom" | df["name"]="Harry" but the issue is param_name is a string which is giving an error: KeyError: 'df["suite"] = "JCK" | df["suite"] = "JTReg"' -
Django Rest Framework ViewSet render serializer form not displaying?
I'm trying to load a form to create an object into a modal window which then submits the data (via AJAX) when the user presses Submit and redirects them to the object it just created. my models look like this: class Game(models.Model): end_year = models.IntegerField() lead_dev = models.ForeignKey( User, on_delete=models.PROTECT, related_name="%(class)s_lead_dev" ) created = models.DateTimeField(auto_now=False, auto_now_add=True) created_by = models.ForeignKey( User, on_delete=models.PROTECT, related_name="%(class)s_created_by" ) updated = models.DateTimeField(auto_now=True, auto_now_add=False) updated_by = models.ForeignKey( User, on_delete=models.PROTECT, related_name="%(class)s_updated_by" ) admin_locked_on = models.DateTimeField( auto_now=False, auto_now_add=False, blank=True, null=True ) report_url = models.CharField(max_length=350, blank=True) objects = models.Manager() managers = GameManager() class Level(models.Model): game = models.ForeignKey(Game, on_delete=models.PROTECT) level_type = models.ForeignKey( LevelType, on_delete=models.PROTECT ) level_difficulty = models.ForeignKey( LevelDifficulty, on_delete=models.PROTECT ) publish = models.BooleanField(default=False) lead_dev_locked = models.BooleanField(default=False) admin_locked = models.BooleanField(default=False) created = models.DateTimeField(auto_now=False, auto_now_add=True) created_by = models.ForeignKey( User, on_delete=models.PROTECT, related_name="%(class)s_created_by" ) updated = models.DateTimeField(auto_now=True, auto_now_add=False) updated_by = models.ForeignKey( User, on_delete=models.PROTECT, related_name="%(class)s_updated_by" ) When a user goes to the Game detail screen (just handled through a generic Django DetailView) I'm showing a list of 'Levels' for that Game. I want a user to be able to click "Add Level" and a modal box pop up just confirming that is the Level they wish to add. When they click "confirm" (submit) the AJAX … -
hi want to show the names from other classes to the Basic class
but when i run it i shows errors that it cant find the muscel_id i Muscel class, how can i show only the names. i ma trying to build a workout plan using django class Days(models.Model): day_name = models.CharField(max_length=60) class Muscel(models.Model): Muscel_name = models.CharField(max_length=60) class Exercise(models.Model): exercise_name = models.CharField(max_length=70) class Basic(models.Model): dagen_basic = models.ForeignKey(Days, related_name='days_basic', on_delete=models.CASCADE) muskel = models.ForeignKey(Muscel.Muscel_name, related_name='muskel_basic', on_delete=models.CASCADE) exercise_name = models.ForeignKey(Exercise.exercise_name, related_name='exercise_name_basic', on_delete=models.CASCADE) reps = models.CharField(max_length=20) sets = models.IntegerField() -
no module named 'my project name'.context_processors in django
Im trying to use a form in every single page of my app. the form is in the base.html page. this is my views.py: def base_info_form(request): if request.method == 'POST': form = BaseContactForm(request.POST) if form.is_valid(): form.save() return redirect('Help-Page') else: form = BaseContactForm() return render(request, '', {'form': form}) def base_forms(request): return { 'info_form': BaseContactForm() } and I added it in my settings like this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ ...... 'Ghoghnoos.context_processors.base_forms', ], }, }, ] 'Ghoghnoos' is the name of my project. That view was my Blog app views. when I refresh the browser, I get this error: No module named 'Ghoghnoos.context_processors' what am I doing wrong here? I've never worked with custom context_processors before.