Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NOT NULL constraint failed: MyServer_links.redirect_url
It says problem with line 82 - store_links.save() views.py from django.http import HttpResponse from django.http import JsonResponse from django.http import HttpResponseRedirect from django.views.decorators.csrf import csrf_exempt from MyServer.models import * import string import random import re from datetime import datetime import json import os # TRACKING_DOMAIN_NAME = "http://127.0.0.1:8000/tracking" # DOMAIN_NAME = "http://127.0.0.1:8000" TRACKING_DOMAIN_NAME = '127.0.0.1:8000' DOMAIN_NAME = '127.0.0.1:8000' # Create your views here. def formaturl(url): if not re.match('(?:http|ftp|https)://', url): return 'http://{}'.format(url) return url def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip def get_client_data(request): browser = request.user_agent.browser.family + " "+ request.user_agent.browser.version_string os = request.user_agent.os.family + " "+ request.user_agent.os.version_string device = request.user_agent.device.family device_type="" if(request.user_agent.is_mobile): device_type="Mobile" if(request.user_agent.is_tablet): device_type="Tablet" if(request.user_agent.is_pc): device_type="PC/Laptop" if(request.user_agent.is_bot): device="bot" resp = {"browser":browser,"os":os,"device_type":device_type,"device":device} print(resp) return resp @csrf_exempt def create_shortened_url(request): original_url = request.GET.get('127.0.0.1:8000') random_chars = ''.join(random.choices(string.ascii_uppercase + string.digits, k = 6)) random_chars2 = ''.join(random.choices(string.ascii_uppercase + string.digits, k = 5)) #append to domain name shortened_link = DOMAIN_NAME + "/" + random_chars tracking_link = TRACKING_DOMAIN_NAME + "/" + random_chars2 #What if randomly generated chars already exist? #Check the url in db before comitting - FUTUTRE WORK #Store in the DB store_links = Links(short_url=shortened_link,redirect_url=original_url,tracking_url=tracking_link) store_links.save() print("LINK SHORTENED : ",shortened_link) # return JsonResponse({'shortened_link':shortened_link,'tracking_link':tracking_link}) return render(request,'index.html',context={'shortened_link':shortened_link,'tracking_link':tracking_link}) def redirect_test(request): return redirect("https://facebook.com") … -
Permission denied, cannot open static files, Docker, Django
I am new in docker, I want dockerize my django application to production. I use the below steps My OS: Ubuntu 20.04.1 LTS Docker version 20.10.5, build 55c4c88 My docker-compose.yml file as below: version: '3.1' services: nginx-proxy: image: jwilder/nginx-proxy restart: "always" ports: - "80:80" volumes: - /var/run/docker.sock:/tmp/docker.sock:ro - ./nginx/vhost/:/etc/nginx/vhost.d:ro - ./nginx/conf.d/client_max_body_size.conf:/etc/nginx/conf.d/client_max_body_size.conf:ro - ./static/:/amd/static - ./media/:/amd/media postgres: image: postgres:9.6.6 restart: always volumes: - ./pgdb/:/var/lib/postgresql/ ports: - "5432:5432" env_file: ./.env redis: image: redis ports: - 6379:6379 restart: always web: container_name: amd build: . restart: "always" ports: - "8000:8000" volumes: - .:/code/ # - ./static/:/code/static # - ./media/:/code/media depends_on: - "postgres" env_file: .env celery: build: context: . dockerfile: celery.dockerfile volumes: - .:/code command: celery -A amdtelecom worker -l info links: - redis - postgres depends_on: - "redis" - "postgres" env_file: ./.env networks: default: external: name: nginx-proxy My Dockerfile as below: FROM python:3.7 ENV PYTHONUNBUFFERED 1 ENV DEBUG False COPY requirements.txt /code/requirements.txt WORKDIR /code RUN pip install -r requirements.txt ADD . . CMD [ "gunicorn", "--bind", "0.0.0.0", "-p", "8000", "amdtelecom.wsgi" ] in my project setting file: CORS_ALLOWED_ORIGINS = [ "http://localhost:8000", "http://127.0.0.1:8000", "http://localhost" ] STATIC_URL = '/static/' if PROD: STATIC_ROOT = os.path.join(BASE_DIR, 'static') else: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ BASE_DIR / "static", ] … -
How to extract data from the Database based on the input fields given in the HTML form using Django
I am using Django REST Framework for creating REST APIs. I am working with MySql Database where I have questionsModel table. In that table I am storing package(JEE, IEEE), Subjects(Phy, Chem, Math), Topics, SubTopics, Questions etc which are already mapped with another tables like packageModel, subjectsModel etc. This is my model : models.py : class questionsModel(models.Model): package_id = models.ForeignKey(packageModel, max_length=20, null=True, on_delete=models.CASCADE) subject_id = models.ForeignKey(subjectsModel, max_length=20, null=True, on_delete=models.CASCADE) topic_id = models.ForeignKey(topicsModel, max_length=200, null=True, on_delete=models.CASCADE) subTopic_id = models.ForeignKey(subTopicsModel, max_length=20, null=True, on_delete=models.CASCADE) Question = models.CharField(max_length=1000, blank=False, null=True) choice = (('c1','c1'), ('c2','c2'), ('c3','c3'), ('c4','c4')) answer = MultiSelectField(choices=choice) numericAnswer = models.CharField(max_length=1000, blank=False, null=True) marks = models.PositiveIntegerField(default=0) easy = models.PositiveIntegerField() average = models.PositiveIntegerField() tough = models.PositiveIntegerField() very_tough = models.PositiveIntegerField() def __str__(self): return self.Question Here, I am storing n number of Questions in this table. Now my requirement is to fetch lets say 50 random Questions depending on the input given in the HTML form. I am putting my code here with the HTML form : This is the Screenshot of HTML Form where I am giving the values. On the basis of the input fields, I want to fetch record from my questionsModel Table serializers.py : class questionPaperSerializer(serializers.ModelSerializer): class Meta: model = questionPaperModel fields = … -
Errno 5 Input/output error on request.GET
Once my Django site has been deployed into "production" and set live using Gunicorn and nginx some URLs that did work before now result in a [Errno 5] Input/output error. I already disabled the DEBUG flat in settings.py by setting DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False' What would be the best approach to troubleshooting this? Is there any obvious part of the deployment that I overlooked? My nginx conf.d file looks as follows: server { listen 80 default_server; server_name rafalkukawski.tech; root /var/www/; location / { proxy_pass http://localhost:8000; } location /img/ { } location /static/ { autoindex on; } } The views affected by this are: # called like: http://rafalkukawski.tech/todo/new?todo_name=new&due_date=2021-03-25&importance=0&required_time=1 def new_item(request): todo_name = request.GET.get('todo_name', '') #todo_auth = request.GET.get('todo_auth', '') due_date = request.GET.get('due_date', '') importance = request.GET.get('importance', '0') required_time = request.GET.get('required_time', '1') #this in particular is highlightet as the faulty line of code item = todo_item(todo_name = todo_name, todo_auth = request.user.username, due_date = due_date, importance = importance, required_time = required_time) item.save() return HttpResponse(item.due_date) or #called like: http://rafalkukawski.tech/ap/painting/1 #not sure what line exactly is causing this since the error only displays "<source code not available>" def template_painting(request, painting_id): painting = Painting.objects.get(pk=painting_id) images = Imgs.objects.filter(painting=painting_id) lang_code = request.LANGUAGE_CODE template =loader.select_template(['ap/'+lang_code+'/painting.html','ap/en/painting.html']) #template = loader.get_template('ap/'+lang_code+'/painting.html') … -
how to insert paragraph after codeblock with <pre> in summernote
i want to insert tag after i use codeblock with ext-highlight below is my code <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <!-- default css --> <link href="{% static 'css/reset.css' %}" rel="stylesheet"> <link href="{% static 'css/layout.css' %}" rel="stylesheet"> <!-- use Prism --> <link href="{% static 'css/prism.css' %}" rel="stylesheet"> <!-- bootstrap cdn --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> <!-- fontawsome --> <link href="{% static 'fontawesome/css/all.css' %}" rel="stylesheet" type="text/css"> <!-- summernote --> <link href="{% static 'summernote-0.8.18-dist/summernote-bs4.css' %}" rel="stylesheet"> <script src="{% static 'summernote-0.8.18-dist/summernote-bs4.min.js' %}"></script> </head> <body> <textarea id="id_content></textarea> <script> $(document).ready(function() { $('#id_content').summernote({ toolbar: [ ['style', ['style', 'add-text-tags']], ['font', ['bold', 'underline', 'clear']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ['table', ['table']], ['insert', ['highlight', 'link', 'picture', 'video']], ], width: '100%', height: '380px', lang: 'ko-KR', prettifyHtml: false, placeholder: '질문을 입력하세요.', dialogsInBody: true, tabDisable: true, }); }); </script> <script src="{% static 'js/summernote-ext-highlight.js' %}"></script> </body> now insert codeblock <p></p> + <pre></pre> but i want <p></p> + <pre></pre> + <p></p> now my page like this but i want like this How can I make the features I want? I don't know if I asked the question correctly because I couldn't speak English well. Please understand this. -
Connecting 2 unconnected tables but are connected to the same table via many-to-many relations
I have the following setting in a django project A model describing "Person", this model includes 2 many-to-many relation fields a. The first unit field connects to a Unit model (m2m) b. The second tool field connects to a Tools model (m2m) Unit and Tools are not directly connected, but I want to list all the tools used in a given unit. I'm not sure how this can be done, since the two tables are not connected? class Person(models.Model): name = models.CharField(max_length=100) unit = models.ManyToManyField(Unit, blank=True) rtools = models.ManyToManyField(Rtool, blank=True) class Tool(models.Model): tool_name = models.CharField(max_length=100) tool_description = models.TextField( blank= True) class Unit(models.Model): unit_name = models.CharField(max_length=250) -
Django TypeError expecting str or binary, how to satisfy?
here is the traceback Building a simple Django blog application, had it working on virtual dev server at first but after integrating summernote editor into admin side, front end site wont launch and this TypeErorr is displayed. Has anyone encountered this before and is able to point me in the right direction? Django version 3.1.7. -
django objects.filter() issues
My django project contains an application called: app_1 It stores models.py file wich contains a django models called: client I cannot filter my models throw client.objects.filter(nom=something), django search into a wrong relation it just add my app name with my model's name and search into "app_1_client" (it should be in "client") ERREUR: the relation « app_1_client » doesn't exist I can access my data with client.objects.raw(""" query """) from django.db import models # Create your models here. class client(models.Model): nom = models.CharField(max_length = 100, null=False) prenom = models.CharField(max_length=100, null=False) tel = models.CharField(max_length=12, primary_key=True) views.py from .models import client def modify_client(request, client_phone): c = client.objects.filter(pk=client_phone) context = {'clients': c} -
different number of records in django pagination pages
I make a news blog. I want 5 news to be displayed on the first page. In the order below. And on the next ones, 6 were displayed (all squares with areas are the same). .news-container { margin: 0; display: grid; grid-template-columns: 50fr repeat(2, 25fr); grid-auto-rows: 40vh; grid-column-gap: 20px; grid-row-gap: 20px; } .news-element:nth-child(1) { background:red; grid-column: 1 / 2; grid-row: 1 / 3; } .news-element:nth-child(2) { background:red; grid-column: 2 / 3; grid-row: 1 / 2; } .news-element:nth-child(3) { background:red; grid-column: 3 / 4; grid-row: 1 / 2; } .news-element:nth-child(4) { background:red; grid-column: 2 / 3; grid-row: 2 / 3; } .news-element:nth-child(5) { background:red; grid-column: 3 / 4; grid-row: 2 / 3; } <div class="news-container"> <div class="news-element"> 1 </div> <div class="news-element"> 2 </div> <div class="news-element"> 3 </div> <div class="news-element"> 4 </div> <div class="news-element"> 5 </div> </div> How can you make sure that 5 news are displayed on the first page in pagination and 6 news on the rest? pagination is done on django like this class NewsView(ListView): model = News template_name="mysite/news.html" paginate_by = 5 context_object_name = "all_news" queryset = News.objects.all().order_by("-date_news") -
Deployed Dockerized Django app with GitLab CI/CD can't find static files
Deployed django application using Docker and Gitlab CI can't find static files on the server when I am trying to access admin page, swagger or browsable-api. I checked static files for their existence and they do in the location /srv/data/public/static/ . I tried to change nginx location but it didn't help. Here is mine production docker-compose.yaml version: '3.1' services: postgres: container_name: postgres image: postgres:12.0-alpine logging: driver: none volumes: - ./data/postgres:/var/lib/postgresql/data:rw ports: - 5432:5432 environment: POSTGRES_DB: baysai POSTGRES_USER: user POSTGRES_PASSWORD: pass redis: container_name: redis image: redis:6.0-alpine logging: driver: none volumes: - ./data/redis:/data api: image: registry.gitlab.com/example/example-api:master container_name: api hostname: api command: bash -c "python /app/manage.py collectstatic --noinput && python /app/manage.py migrate --noinput && gunicorn -b 0.0.0.0:8000 config.wsgi:application" stdin_open: true tty: true restart: always environment: DJANGO_SETTINGS_MODULE: config.settings volumes: - ./data/public:/public - ./example-api.env:/example-api.env ports: - "8000:8000" depends_on: - redis - postgres celery: image: registry.gitlab.com/example/example-api:master container_name: celery hostname: celery command: bash -c "cd /app && find . -type f -name 'celerybeat.pid' -exec rm -rf {} \; && find . -type f -name 'celerybeat-schedule' -exec rm -rf {} \; && celery -A config worker -l info" stdin_open: true tty: true restart: always environment: DJANGO_SETTINGS_MODULE: config.settings volumes: - ./data/public:/public - ./example-api.env:/example-api.env depends_on: - redis - postgres nginx: … -
Credential error when trying to preserve data
I am developing an api in Django Rest Framework, which at the moment only registers new users, but I have a problem and that is that now I am adding a bit of security, which is being controlled by means of tokens, but at the time of entering the token of an authenticated user for the creation of users generates an error of The authentication credentials were not provided, but I send the token as follows: This is plugin rest client visual studio code My authentication: ### Login user POST http://localhost:8000/auth-token/ Content-Type: application/json { "username": "hamel", "password": "contraseña" } This return a token b6773c67ecb940ae4fb7c9d49466a01fd46f5eb4 My register of user: ### Create User POST http://localhost:8000/api/v1/users Authorization: Token b6773c67ecb940ae4fb7c9d49466a01fd46f5eb4 Content-Type: application/json { "first_name": "Carlos", "last_name": "Carlos", "username": "carlos", "email": "correo@rgrgr.com", "password": "contraseña", "password2": "contraseña" } My setting.py: REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ] } -
how can i set two for loop in django template for send and receive chats?
im trying to set receive and send message in django template with to for loop like this : <div class="border px-2 chat-box "> {% for box in message1 %} <div class=" my-4 border bg-light "> <span class=" p-2 my-5">{{ box.msg_content }}</span><br> <span class="date text-muted ">{{ box.whenpublished }}</span> </div> {% endfor %} {% for box2 in message2 %} <div class=" border bg-danger" style="" > <span class=" p-2 my-5" >{{ box2.msg_content }}</span><br> <span class="date text-muted">{{ box2.whenpublished }}</span> </div> {% endfor %} </div> but when i send and receive message Each of them comes separately like this: hello(user1) how are you(user1) hello(user2) im fine thnaks(user2) but i want when i send one message its show after receive message hello(user1) hello(user2) how are you(user1) im fine thnaks(user2) -
could not create unique index, key is duplicated django postgres
I got following user table with same uuid . I want this uuid to be unique . but while changing the uuid from my user model with unique=True and editable=False While executing migrate command , I am getting "psycopg2.errors.UniqueViolation: could not create unique index" error with Key (hnid)=(8c0bc4a2-165a-47d5-8084-8b87600c7fe8) is duplicated. Note: I am using postgres How can I solve this issue -
Saving Serializers with Foreign Key (django rest framework)
I have two models which is Task and Batch that are related to each other by Foreign Key field. When creating a Task Object, I want to check first if a Batch Object is available in database (batch is just the current date, so I can group each task using batch). If not, create a Batch object and then pass the newly created batch object to the Task that is being created. views.py @api_view(['POST']) def taskCreate(request): batch = Batch.objects.filter(batch = datetime.date.today()).first() serializer = TaskSerializer(data=request.data) if serializer.is_valid(): serializer.save(commit=False) if batch is None : batch = Batch.objects.create(batch = datetime.date.today()) serializer.batch = batch serializer.save() return Response(serializer.data) models.py class Batch(models.Model): batch = models.DateField(auto_now_add=True) class Meta: ordering = ['-batch'] verbose_name = 'Batch' verbose_name_plural = 'Batches' def __str__(self): return self.batch.strftime("%B %d, %Y %A") class Task(models.Model): title = models.CharField( max_length = 256, ) completed = models.BooleanField( default = False, ) batch = models.ForeignKey(Batch, on_delete=models.CASCADE) def __str__(self): return self.title serializers.py class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = '__all__' depth = 1 this is how I handle my form in frontend: var form = document.getElementById("form") form.addEventListener('submit', function(e){ e.preventDefault() var url = "{% url 'api:task-create' %}" if(activeItem != null ){ url = `http://localhost:8000/api/task-update/${activeItem.id}/` activeItem = null } var … -
Python Django __init__() takes 1 positional argument but 2 were given
Hi i started to make django and started with simple Hi app. But when i want to access on /hi/ i give error called "init() takes 1 positional argument but 2 were given" Here is code #urls.py from django.contrib import admin from django.urls import path from hi.views import hiView urlpatterns = [ path('admin/', admin.site.urls), path('hi/', hiView), ] #views.py from django.shortcuts import render from django.http import HttpRequest def hiView(request): return HttpRequest('Hi.') #settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hi', ] im adding my directory list https://imgur.com/N3uJG1f -
Empty QuerySet for Django Multi-Table Inheritance Subclass
I have the following models: APP 1: class User(AbstractBaseUser): # custom fields etc # NOT ABSTRACT APP 2: class SecondaryUser(User): # other custom fields When I do SecondaryUser.objects.create(...) I get an instance as expected: In: SecondaryUser.objects.create(first_name='test', last_name='test', email='test@etest.com') Out: <SecondaryUser> This has an id and populated fields as expected. I can also query the base class and use the django-generated 1-1 field for the inheritance to access the subclass's fields: User.objects.get(email='test@etest.com').secondaryuser.<some_field> However when I do SecondaryUser.objects.all() it returns an empty queryset. And the model admin for the SecondaryUser shows an empty list view (even when I create a new instance of SecondaryUser in the admin create view). I feel like I'm missing something obvious, I need to be able to list the SecondaryUser instances in the admin. The User class cannot be abstract. -
django apache :WSGIPythonHome cannot occur within <VirtualHost> section
i have a server with ubuntu-server that run apache2 and where i have my django project. i'm having trouble deploying the app. this is my /etc/apache2/sites-available/000-default.conf: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName HIVE.localhost ServerAdmin webmaster@localhost DocumentRoot /home/leo/HIVE/src # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For example the # following line enables the CGI configuration for … -
Django & Celery - Domotic Project with Raspberry
I started a new project with Raspberry Pi that controls a series of sensors and activates relays when certain conditions occur. The script runs well stand alone but I need to integrate it into a django app to control certain cases (e.g. temperatures, humidity, manual switches, etc.) So, I have pip installed celery and redis and configured it. What I need to understand is how to make the while scrip start contextually to the app and not block it when the app starts. The script is very simple def startdomo() stuffs = Stuffs.objects.get(pk=1) while True: do some stuffs I try to put it into url.py at the end urlpatterns = [ url(r'', include('FBIsystem.urls')), ] startdomo() In this case startdomo run but django app not run. The goal is to use Celery to run startdomo async respect to the app. Thanks in advance. -
Use elasticsearch on a local folder
So basically I have a Python Django app that get lots of html pages. I store them locally like this (imagine a lot more) : I want to search by key word(s) in all the these index.html I understood that Elasticsearch is a really powerfull tool but I don't know if it can fits my needs. I searched on the internet but didn't find really accurate websites that could help me. -
name 'ValidationError' is not defined in django form
I'm trying to restrict a user if they enter an e-mail that already exists during registration. This is the error i get Exception Value: name 'ValidationError' is not defined User Form from django import forms from django.db import models from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): email = forms.EmailField() def clean(self): email = self.cleaned_data.get('email') if CustomUser.objects.filter(email=email).exists(): raise ValidationError("Email already exists") return self.cleaned_data -
Django - is token/JWT authentication safer if backend and frontend are on the same server?
I'm researching the best security approaches for a webapp that i want to build, where the backend should be separated from the frontend but they will both be on the same server. The frontend is a standalone VueJS application while the backend is a Django app that will communicate with Vue using JSON, but i think this still applies to other frameworks like react or angular. For authentication, i would use djoser and probably token based authentication or JWT. I made some research about this topic and found that there are some concerns on token based authentication, mostly related to token storage on the client side. My question is: when backend and frontend are on the same server, instead of being cross domain, do these security concerns still apply? Or is it a much safer approach? If i deploy the two apps on the same server, can i store the tokens on Vuex or any other local storage safely? What can i do, instead, on the Django side, to make the app as safe as possible? -
Calling two fetch Requests in Django with Javascript displays the result in the same div
I am really new to Javascript therefore be kind! There must be something wrong with the way I am structuring this. I have seen possible solutions, could involve async functions and I tried them but for some reason, I might not get the order straight, or simply I am missing the point. I am using a fetch request to source some data at first from the API that I made on my local server. And that works fine. I am able to source the names of the cryptocurrencies that I have coupled with a username in JSON format. After I have created the styling for the divs to display and inserted the data in, I call another fetch for another API this time external, to further source data and insert it in divs I have created previously, per each piece of data I sourced from my own API. For some reason, it ends up displaying the data that I am fetching from this external API all in the same div, instead of displaying them for each. I have tried a forEach function, I have tried (i=0;i<data.lenght;i++), I have tried to place it differently, I have tried creating global variables and … -
making context variable from one method accessible to other other methods (and views) in Django
i'm working on a dashboard project (django + charts.js) that currently looks like this: currently, all of the charts are based on all the data in the database (approx 1.5 mil lines). however, i'd like these charts to be responsive to the dates indicated in the start date/end date HTML widget - e.g. show payment methods, taxi orders by the hour/day of week according to the start/end dates indicated. my date_input method gets the start and end dates from the frontend, and queries my MySQL database according to the dates selected. these queries are then rendered to the context variable of date_input - however, i'd like the context variable in date_input to be available to all methods (each chart is rendered by a different method, based on the JsonResponse returned to different endpoints). i've tried making context available as a global variable by defining it outside date_input as queryset = date_input(request) - NameError: name 'request' is not defined. i've looked into context processors, but that seems to be an option only if i didn't have a request (e.g. start/end date input from the frontend). i'm rather confused and would appreciate some help. here's my views.py code: def date_input(request): if request.method … -
Set different password for Django admin users than for the public Django app
We have a Django app where we're using the default password/password reset functionality. Lots of our staff also login to Django admin using the same credentials. Is it possible to create separate passwords for these two areas (the public app and Django admin)? The advantage of doing this is I can set & enforce strong passwords for everyone in Django admin, and people aren't tempted to change them to something that's easier to log into the public app with. -
Django - Override save() method of auth_user model
I want store the username of the auth_user table into the first_name, if no first name is provided. Something like this: from django.contrib.auth.models import User class CustomUser(User): class Meta: proxy = True def save(self, *args, **kwargs): if not self.first_name: self.first_name = self.username super(CustomUser, self).save(*args, **kwargs) Thank you