Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
View Management in Django
I'm new to python and I have chose Django Framework. I searched over documentations and couldn't find my desired way of view management. I want to create a skeleton base view and load other view in that view. But my question is that I want to create some views in views.py write code their and output result in base skeleton. One page may contains view from different methods in views.py file. Is there any idea of this modular implementation of template ? Thanks in Advance. -
Upload image to firebase and save url in sqlite DJango
suddenly someone can guide me. I made an application, people have a normal profile, with a series of fields that can modify the profile photo, locally it works perfectly, however, when deploying it in heroku (free account) it is not possible because heroku in its free version does not handle dynamic files, or at least that is what I understood, so I want to save the images in firebase and only the urls in the database. Anyone have any idea how I can do this? Thank you very much for your answers This is the code currently views.py def edit_profile(request): if request.method == 'POST': form = UEditF(request.POST, instance=request.user) extended_profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile) if form.is_valid() and extended_profile_form.is_valid(): form.save() extended_profile_form.save() return redirect('/polls/perfil') else: form = UEditF(instance=request.user) extended_profile_form = ProfileForm(instance=request.user.profile) context = { 'form': form, 'extended_profile_form':extended_profile_form } form.fields['password'].help_text = 'Para cambiar la contraseña has clic en el menú superior derecho "Cambiar contraseña"' return render(request, 'registration/edit_profile.html', context) forms.py class UEditF(UserChangeForm): class Meta: model = User fields = ['first_name', 'last_name'] class ProfileForm(forms.ModelForm): birth_date = forms.DateField(widget=DatePickerInput(format='%d/%m/%Y'), label='Fecha de nacimiento') photo = forms.ImageField(label="Foto de perfil") models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateField('Fecha de nacimiento', default=date.today) photo = models.ImageField('Foto de perfil', upload_to='media/', max_length=200, default='default.png') -
Graphene-python performance issues for large data sets
Currently using graphene-python with graphene-django (and graphene-django-optimizer). After receiving a GraphQL query, the database query is successfully completed in a fraction of a second; however, graphene doesn't send a response for another 10+ seconds. If I increase the data being sent in the response, the response time increases linearly (triple the data = triple the response time). The data being retrieved composed of nested objects, up to 7 layers deep, but with the optimized queries this doesn't impact the time taken to retrieve the data from the DB, so I'm assuming the delay has to do with graphene-python parsing the results into the GraphQL response. I can't figure out how to profile the execution to determine what is taking so long -- running cProfiler on Django doesn't seem to be tracking the execution of graphene. SQL Query response time was determined using the graphene-django-debugger middleware, results shown below: "_debug": { "sql": [ { "duration": 0.0016078948974609375, "isSlow": false, "rawSql": "SELECT SYSDATETIME()" }, { "duration": 0.0014908313751220703, "isSlow": false, "rawSql": "SELECT [redacted]" }, { "duration": 0.0014371871948242188, "isSlow": false, "rawSql": "SELECT [redacted]" }, { "duration": 0.001291036605834961, "isSlow": false, "rawSql": "SELECT [redacted]" }, { "duration": 0.0013201236724853516, "isSlow": false, "rawSql": "SELECT [redacted]" }, { "duration": 0.0015559196472167969, … -
django-bakery page variables missing from bake
I've been reading the docs and have been able to mostly bake a site successfully. However I'm having an issue on passing page parameters to the baking view. Original View that works in the regular runserver command class auto(View): def get(self, request): return render( request, 'app/auto.html', { 'title':'Auto Insurance', 'message': 'generic message', 'year':datetime.now().year, } ) I use this bakery view class AutoTemplateView(BuildableTemplateView): build_path = 'auto.html' template_name = 'app/auto.html' The settings has the view and the page is being generated successfully outside of the title and message are blank BAKERY_VIEWS = ( 'app.views.HomeTemplateView', 'app.views.AutoTemplateView', ) html template <div class="col-sm-8 col-sm-offset-2"> <h3 class="title-one"> {{ title }}</h3> <h4>{{ message }}</h4> </div> and bakery html output : <div class="col-sm-8 col-sm-offset-2"> <h3 class="title-one"> </h3> <h4></h4> </div> I can't imagine this is an actual bug but what am I missing? -
How do I host two servers on NGINX? (Django and Angular PWA)
I want Django to keep all of its defined routes and Angular to be hosted from ip/pwa. I have these block bodies: #Angular server { listen 157.230.4.110:80; root /home/pwa/dist/reportpwa; location /pwa { try_files $uri $uri/ /index.html; } } #Django Database server { listen 157.230.4.110:80; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/django-apps/reportdbapi; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } The servers seem to run fine on their own but when I put them both up together, the Django server takes over and refuses to recognize the Angular server. Can anyone tell me what kind of configuration I need to make them both work? -
Background image not rendering correctly in Django
I am working on a project in Django 2. I have a base.html in templates: {% block removable-pagetop %} <div class="showcase"> <div class="showcase-content-top"> {% block page-title %}{% endblock %} <p>{% block page-subtitle %}{%endblock %}</p> </div> {% block button-list %} <div class="showcase-content-buttons"> <ul> <li>{% block button1 %}{% endblock %}</li> <li>{% block button2 %}{% endblock %}</li> <li>{% block button3 %}{% endblock %}</li> <li>{% block button4 %}{% endblock %}</li> </ul> </div> {% endblock %} </div> {% endblock %} The CSS for a background image is: .showcase { background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.2)), url(/static/img/vg_home.jpeg); height: 100%; background-position: center; background-repeat: no-repeat; background-size: cover; } My index.html is: {% extends 'base.html' %} {% load static %} {# Page/Tab Title #} {% block title %}Video Games | Home{% endblock %} {# Navbar with video game theme icon #} {% block navbar %} <header> <nav class="nav-wrapper"> <div class="logo"> <a href="{% url 'index' %}"> {% block nav-icon %}<img src="{% static 'img/vg_icon.png' %}">{% endblock %} </a> </div> <ul class="menu"> <li><a href="{% block home-button %}{% url 'index' %}{% endblock %}">Home</a></li> <li><a href="{% block about-button %}{% url 'about' %}{% endblock %}">About</a></li> </ul> </nav> </header> {% endblock %} {% block removable-pagetop %} <div class="showcase"> <div class="showcase-content-top"> {% … -
I want to create an RestFul Web Scraping API with a Python framework
i'm looking for recommandations about what framework is good to build a this API (DJANGO or FLASK) also what library is good for "OCR" (Scrappy or Tessaract). Thanks -
Can't add SSL certificate to Traefik running on Docker
I'm working on a project runs on Ubuntu 18.04, I depend on Docker to run the application. here is the production.yml file part of traefik: traefik: build: context: . dockerfile: ./compose/production/traefik/Dockerfile image: goplus_backend_production_traefik depends_on: - django volumes: - production_traefik:/etc/traefik/acme - ${PWD}/certs:/certs ports: - "0.0.0.0:80:80" - "0.0.0.0:443:443" here is the Dockerfile for traefik: FROM traefik:alpine RUN mkdir -p /etc/traefik/acme RUN touch /etc/traefik/acme/acme.json RUN chmod 600 /etc/traefik/acme/acme.json COPY ./compose/production/traefik/traefik.toml /etc/traefik and here is traefik.toml file: logLevel = "INFO" defaultEntryPoints = ["http", "https"] # Entrypoints, http and https [entryPoints] # http should be redirected to https [entryPoints.http] address = ":80" [entryPoints.http.redirect] entryPoint = "https" # https is the default [entryPoints.https] address = ":443" [entryPoints.https.tls] [[entryPoints.https.tls.certificates]] certFile = "/certs/hrattendence_gs-group_nl.chained.crt" keyFile = "/certs/hrattendence_gs-group_nl.key" [file] [backends] [backends.django] [backends.django.servers.server1] url = "http://django:5000" [frontends] [frontends.django] backend = "django" passHostHeader = true [frontends.django.headers] HostsProxyHeaders = ['X-CSRFToken'] [frontends.django.routes.dr1] rule = "Host:<IP name>" Each time i run docker i got this error messages about traefik: traefik_1_6f05e4889627 | time="2020-09-18T23:23:49Z" level=info msg="Using TOML configuration file /etc/traefik/traefik.toml" traefik_1_6f05e4889627 | time="2020-09-18T23:23:49Z" level=info msg="No tls.defaultCertificate given for https: using the first item in tls.certificates as a fallback." traefik_1_6f05e4889627 | time="2020-09-18T23:23:49Z" level=info msg="Traefik version v1.7.16 built on 2019-09-13_01:12:20PM" traefik_1_6f05e4889627 | time="2020-09-18T23:23:49Z" level=info msg="\nStats collection is disabled.\nHelp us … -
django Page not found Using SQLite3
Not Sure why I am getting this error I only have 1 Item Only my ToDoList its called "Habibs List" but when I go on the website and put http://127.0.0.1:8000/Habibs List Its giving me this error I am doing the same thing from this Tutorial but I am not sure why mine isnt working its at 22:12 Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/Habibs%20List Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ <int:id> [name='index'] The current path, Habibs List, didn't match any of these. this is in my view tab def index(response, name): ls = ToDoList.objects.get(name=name) item = ls.item_set.get(id=1) return HttpResponse("<h1>%s</h1><br></br><p>%s</p>" %(ls.name, str(item.text))) #def v1(response): #return HttpResponse("<h1>Game Page</h1>") #def v2(response): #return HttpResponse("<h1>Electronic Page</h1>") my url page in my main # the path to our defferent web pages # like the defferent views we have in our file from django.urls import path from . import views urlpatterns = [ path("<int:id>", views.index, name="index"), ] -
Can't create new django project [VS CODE]
PS C:\Users\Kwaku Biney\Desktop\hello_django> django-admin startproject dj_pro django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + django-admin startproject dj_pro + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotF ound: (django-admin:String) [], Comm andNotFoundException + FullyQualifiedErrorId : CommandNot FoundException This is what happens everytime a try to create a new project. How do I rectify it? Created the path and everything.. but still -
Extract date from datetime dictionary in django queryset
Spent way too much time on this so Ima ask, queryset = MyModel.objects.filter(id=id).values('send_date') the result is this <QuerySet [{'send_date': datetime.date(2020, 9, 30)}]> Trying to get 2020, 9, 30 I tried sd=queryset.strftime('%Y-%m-%d'), sd=datetime.strptime(max(queryset.keys()),'%Y-%m-%d') even tried sd=queryset['send_date'], sd=queryset.get('send_date'). -
How to set venv in Django Manage Commands for Sublime 3
I've installed Django Manage Commands for Sublime 3 via Package Control but I am unable to set virtual environment. I followed the instructions but when I try Ctrl + Shift + p and select Django: New Project it asks to choose an interpreter, but I only get the default one, virtualenvs are not listed. I also added "python_virtualenv_paths" : "C:/Users/virtualenvs/django_blog/Scripts/" to JSON. I suspect I skipped some step(s) during the setup, but I can't figure out which. -
Is there a way to add bearer token in the "urlpatterns" so that I can use the Rest API in a browser as well?
I am using the Rest Framework SimpleJWT for token authentication. In postman I add the Bearer token in the Authorization tab and the API works fine. When I try to use the API on a browser I do not have an option to pass the Bearer token. I am not sure how to pass the bearer token so the API works in the browser as well. Urlpatterns : from .views import profile, .... urlpatterns = [ path('', include('rest_framework.urls')), path('/user', profile), ....... Let me know if anymore info required, I am able to add all the code here. -
Django: how to access Postgres view
I've created a view in Postgres database and I'm struggling to connect to it via Django's ORM. I've made a model that looks like so: class PriceView(models.Model): NAME = models.CharField(max_length=200) PRICE = models.FloatField() class Meta: managed = False db_table = 'myapp_v_tablename' But I'm getting error: name PriceView' is not defined. When trying to access to it. How to solve it? -
DJANGO || How to order_by correctly with characters like æ ø å
I'm fetching some data from my Postgres database with MODEL.values().order_by('name'). This works as intended but except it doesn't sort it correctly regarding to æ,ø and å. I'm not quite sure how to fix this, and I couldn't find a clear answer in the docs either. Any good tips out there? -
Adding a css class for a Django ModelForm
I have the following form in django which is based on a model(MiniUrl): from django import forms from .models import MiniUrl class AddUrl(forms.ModelForm): class Meta: model = MiniUrl fields = ['long_url', 'pseudo'] widgets = { 'long_url': URLInput(attrs={'class': 'user-input'}), 'pseudo': TextInput(attrs={'class': 'user-input'}), } I want to add a css class to the fields long_url and pseudo . When i run the application on the local server i get the following error: long_url': URLInput(attrs={'class': 'user-input'}), NameError: name 'URLInput' is not defined How can I fixe it, please ? Thank you. -
Access model items in more than one template in Django
I have a view that is directed to the home page. In my home page, I have {% for item in items %} {{ item.name }}<br> {{ item.title }} {% endfor %} I can't find a way to access the same items in another page. Writing the same code in that other page returns nothing. How would I go about this here? -
Django+Cython import cython module in django app views
a newbie to django and Cython. I am creating an app in django and need to import function in views.py from cythonized module. following is views.py inside my app. from django.shortcuts import render import sys import numpy as np import random import math from cython_node_val import node_val def home(request): return render(request,'Home.html',{"name":"user"}) def shortest_path1(request): K=int(request.POST['number of layers']) if ((K%2!=0) or (K < 0)): return render(request,"shortest_path1.html",{'shortest_path1':"K must be an even integer"}) else: ...... Node_val=node_val(Hash,C,K) #node_val is from cython_node_val which is a .pyx file, Hash C and K are defined in body after else statement. sPath=np.zeros((K,3)) sPath[K-1,:]=Node_val[n-1,:] for m in range(K-2,-1,-1): sPath[m,:]=Node_val[int(sPath[m+1,1])] return render(request,"shortest_path1.html",{'shortest_path1':sPath[:,3]})''' the directory of my project is like following:project directory Django my app directory looks like this app directory with built cython code and supporting files highlighted cython_node_val.pyx works fine when importing into a normal .py file, but when doing the same inside views.py in my app it throws me following error File "C:\Users\amit\projects\application_shortest_path\shortest_path\DS2P\urls.py", line 9, in <module> from . import views File "C:\Users\amit\projects\application_shortest_path\shortest_path\DS2P\views.py", line 6, in <module> import cimport ModuleNotFoundError: No module named 'cimport' I believe if views.py is a python file and we can do operations, it should pull cython_node_val and associated functions. Where am i wrong? Thanks … -
Create url out of midi file - Javascript
I am sending a midi file from the server via ajax request: // Create new request add token const generateRequest = new XMLHttpRequest(); generateRequest.open('POST', '/generate'); generateRequest.setRequestHeader('X-CSRFToken', csrftoken); generateRequest.onload = () => { // Get response from server console.log(generateRequest.response); // /tmp/music21/tmp5v_ulgkr.mid let objectURL = URL.createObjectURL(generateRequest.response); document.getElementById('myVisualizer').src = objectURL; }; // Add the motif to send with the request const data = new FormData(); data.append('motif', JSON.stringify(notes)); // Send request generateRequest.send(data); Server: def generate(request): if request.method == "POST": # Do some stuff midi = mg.save_melody(melody) return HttpResponse(midi, content_type="audio/midi", status=200) Mi idea is to set the src of mi midi-visualizer to be the midi file: <midi-visualizer src="" type="staff" id="myVisualizer"></midi-visualizer> <midi-player sound-font visualizer="#myVisualizer"></midi-player> But I am getting: Uncaught TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided. I also tried srcObject with no results. How can I change the src to be my midi file? -
"Apps aren't loaded yet" when import model to a file run by manage.py
I want to get cryptocurrency data from external websocket and save it to database. In order to run producer.py from start, I added it to INSTALLED_APPS in settings.py: INSTALLED_APPS = [ 'crypto.spot.producer', ] producer.py is: from .models import Spot async def message(u, t, interval, timeout): async with websockets.connect(uri=u + '?token=' + t, ping_interval=interval, ping_timeout=timeout) as websocket: await websocket.send(json.dumps({"id": "4848226", "type": "subscribe", "topic": "/market/ticker:all", "response": True})) while True: response = await websocket.recv() result = json.loads(response) ''' write result to django model (Spot) ''' while True: response = r.post('https://api.kucoin.com/api/v1/bullet-public') payload = json.loads(response.text) uri = payload['data']['instanceServers'][0]['endpoint'] token = payload['data']['token'] ping_interval = payload['data']['instanceServers'][0]['pingInterval'] ping_timeout = payload['data']['instanceServers'][0]['pingTimeout'] asyncio.get_event_loop().run_until_complete(message(uri, token, ping_interval, ping_timeout)) asyncio.get_event_loop().run_forever() However, I get the following error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\threading.py", line 926, in _bootstrap_inner self.run() File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\a.daghestani\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\config.py", line … -
How to loop over an html with javascript?
I have an HTML code which looks like this:- <article class="media content-section"> <div class="media-body"> <h2><a class="article-title" href="{% url 'post-detail' post.slug %}">{{ post.title }}</a></h2> <div class="article-metadata"> <a class="mr-2" href="{% url 'blog-profile' name=post.author %}">{{ post.author }}</a> <div class="float-right"> <small class="text-muted">Category</small> <small class="text-muted">{{ post.date_posted }}</small> </div> <div style="float:right;"> <img style="height:19px; width:18px;" src="{% static "blog/viewicon.png" %}"> <p style="float: right; display: inline !important;" id="ViewCount"> ..... </p> </img> </div> </div> <p class="article-content">{{ post.content|truncatechars:200|safe }}</p> </div> </article> I am trying to add the values of viewcount asynchronously to all the blogs field. With this js/ajax code:- <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script> <script> $(document).ready(function(){ setInterval(function() { $.ajax({ type:'GET', url: "{% url 'getBlogs' %}", success: function(response){ $("#ViewCount").empty(); for (var key in response.blogs) { console.log(response.blogs); var temp = response.blogs[key].view_count $("#ViewCount").append(temp); } }, error:function(response){ alert("No Data Found"); } }); },1000); }); </script> I have many such blogs, But the values seem to be displayed all at once at only a single field which looks like this:- But I am trying to display the viewcount of each blogs to its dedicated position. Is there I anyway I can achive it. -
Create a post_save signal that creates a profile object for me
Good afternoon, I have the following signal inside my User model, but at the moment of creating the user it is not creating the profile object, which I am doing wrong. def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) def save_profile(sender, instance, **kwargs): instance.create_profile.save() post_save.connect(create_profile, sender=User) post_save.connect(save_profile, sender=User) -
Form with multi-step fields
I want to create a form which user will fill field by field. The reason I want to do it with views instead of javascript is the next field will be shown will be according to current answer to the field. Think of it as a chat-bot. How can I accomplish to render django forms field by field? When I tried it by writing if statements to fields in ModelForm, I faced with error of "Models have not been loaded". -
Django: using python methods
I'm trying to truncate my urls that are being populated into html table like so: {% for x in queryset %} <tr> <td>{{x.LINK}}</td> </tr> so that i.e 'www.google.com' becomes 'google'. How to achieve it? In python it would be straight forward with .split('.') method but here I'm confused. Or maybe it would be simplier to do all the data modifications before I query them in django? -
How do I store a count of a manytomanyfield in a model or filter and aggregate a manytomanyfield
I have a model where I want to create a ranking for the count of a manytomanyfield. Only it expects an integer field instead of a manytomany field. I have a problem with the votes__lt. Would the best course of action be creating a votes_count integerfield that counts the votes or is there a way to fix this code so it works? class ContestEntry(TimeStampedModel): votes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='vote_entry') def ranking(self): aggregate = ContestEntry.objects.filter(votes__lt=Count(self.votes)).aggregate(ranking=Count('votes')) return aggregate['ranking'] + 1