Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
ValueError at /assignment/get/ Field 'zip' expected a number but got 'zip'
While storing data from csv file to database I am getting error ValueError at /assignment/get/ Field 'zip' expected a number but got 'zip'. model.py from django.db import model # Create your models here. class csvData(models.Model): zip=models.IntegerField() lat=models.IntegerField() lng=models.IntegerField() views.py import csv from .models import csvData def get(request): fname="uszips.csv" with open(fname) as csvfile: csv_reader=csv.reader(csvfile, delimiter=',') for row in csv_reader: csvdata=csvData() csvdata.zip=row[0] csvdata.lat=row[1] csvdata.lng=row[2] -
Django migrations aren't applying?
When running my server I get the message: You have 3 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): app_name I've tried python3 manage.py migrate, but that gives this result Operations to perform: Apply all migrations: app_name Running migrations: No migrations to apply. Where do I need to look to fix this? I've deleted migrations a few times, which I realise is a bad move but I can't wipe the db either at this point. -
How to create a stateful WSGI Python web app
I would like to create a python web api where in-memory state can be shared between requests. I understand that the recommended/best practice for this is to use memcached or redis. However, I do not want to use these, I want to have a local shared memory option: I will only ever run this application on one server. No clusters no load balancing no need to share memory between nodes. I'm also just interested to know, what if I wanted to write a cache service like memcached myself, how would I do it without using memcached?! My current understanding is that Gunicorn spawns multiple different processes, and "recycles" web workers, meaning any "global" variable is not going to be around consistently between requests. I therefore reason that either I would need to find way to serve the wsgi app using only one process, and then share memory between threads, or I would need to find a way to share memory between processes. In either event though, how would I set that up if gunicorn is in control of the processes? And how would I prevent recycling of web workers losing the state? I've also seen some recommendations to use gunicorns … -
load static and DOCTYPE html position in django views
I am new to Django and have trouble understanding the difference between the position of lines shown below: {% load static %} <!DOCTYPE html> In the above code, the PyCharm shows error but if I change the position as shown below, it works as intended: <!DOCTYPE html> {% load static %} Can anyone explain how this works or if I am doing it the wrong way? Thanks!! -
Target WSGI script '/opt/python/current/app/github/wsgi.py' cannot be loaded as Python module
I am trying for two days to deploy my django project on aws. But i am getting one error after another. After lots of searching for answers. This is the last error that i am not able to overcome. I am following these guides: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html https://www.1strategy.com/blog/2017/05/23/tutorial-django-elastic-beanstalk/ After all of it. When i try to access my site.It shows 500 Server Error. In Logs it Shows Target WSGI script '/opt/python/current/app/github/wsgi.py' cannot be loaded as Python module. Another question on net answered to comment the Database lines in settings file. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } After it my site loads. But then the problem is there is not database. So it throws another error settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. So now i am struck here. I have looked at every related question tried there solution but nothing is working. It is my first time trying AWS and it is turning out to be very hard. I deployed my project on heroku successfully but heroku does not support cron job and i really need something like cron job for my project. -
Nginx not serving media files. Dockerizing django/nginx/gunicorn/postgresql
I have a project running in 3 docker containers. One is for django project itself, another one for postgres and the third one for nginx. My static files are served just fine while all media files are not found. However every file which was uploaded is properly saved in web container in media folder. Here is the docker-compose file: version: '3.8' volumes: postgres_data: static: services: db: image: postgres:latest volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env web: build: . restart: always command: gunicorn foodgram.wsgi:application --bind 0.0.0.0:8000 volumes: - ./static:/static - ./media:/media ports: - "8000:8000" depends_on: - db env_file: - ./.env nginx: build: context: . dockerfile: nginx/Dockerfile ports: - "8080:80" volumes: - ./static:/etc/nginx/html/static - ./media:/etc/nginx/html/media depends_on: - web Here is the dockerfile: FROM python:3.8.5 WORKDIR /code COPY . /code RUN pip install -r /code/requirements.txt Here is the nginx.conf: events {} http { include mime.types; server { location / { proxy_pass http://web:8000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; } location /static/ { autoindex on; root /etc/nginx/html/; } location /media/ { autoindex on; root /etc/nginx/html/; } } } and finally nginx dockerfile: FROM nginx:latest COPY nginx/nginx.conf /etc/nginx/nginx.conf What do I miss? -
Static Files are set but not working. I keep getting 500 error
Can someone please look at the way I have my static files set up and tell me if there is something I am missing? Thank you. STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' -
How can I access to EmbedVideoField from Wagtail?
How can I access to EmbedVideoField from Wagtail? I'm getting a message "Unresolved reference 'EmbedVideoField' ". How can I import it? -
How to use bootstrap with django rest framework?
Recently I began to develop a REST API with Django REST Framework. I want to change the bootstrap, and I used the The Browsable API as a guide. But, every time I followed the instructions to override the bootstrap template, the appearance of the site changes, but the DELETE button doesn't work. I add to the setting.py: TEMPLATES = [ ..., 'DIRS': [os.path.join((BASE_DIR), 'templates/')], ..., ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') I created a folder static/css where is the file bootstrap.min.css. I also created a folder templates/rest_framework where is the file api.html with the following code. {% extends "rest_framework/base.html" %} {% block bootstrap_theme %} <link rel="stylesheet" href="/static/css/bootstrap.min.css" type="text/css"> {% endblock %} {% block bootstrap_navbar_variant %}{% endblock %} What could I be doing wrong? -
Cannot redirect to specific path name in urls.py
I have a issue in django project where I want to redirect to a specific path using its name. My code looks like this. It doesn't redirect to a path name but It redirect towards http://127.0.0.1:8000/ perfectly. I googled and also searched it in stack overflow but I didn't find any question related to this. What can be the problem and solution to it. I followed tutorial and there his code his working fine and redirecting well. urls.py from django.contrib import admin from django.urls import path from .views import * urlpatterns = [ path('', index, name='myhomepage'), path('order', order), path('signup', signup) ] And in views.py the code goes like this: from django.shortcuts import render, redirect from django.http import HttpResponse from .models.product import Product from .models.category import Category from .models.customer import Customer # Create your views here. def index(request): # calling get_all_product() method from products products = None categories = Category.get_all_categories() category_id_from_server = request.GET.get('category') if category_id_from_server: products = Product.get_all_product_by_category_id(category_id_from_server) else: products = Product.get_all_product() data = {} data['products'] = products data['categories'] = categories return render(request, 'index.html', data) def order(request): return render(request, 'orders.html') def signup(request): if request.method == 'GET': return render(request, 'signup.html') else: postdata = request.POST first_name = postdata.get('firstname') last_name = postdata.get('lastname') phone_number = … -
Django Select a valid choice.[...] is not one of the available choices. in a dynamically generated form
I am making a quiz application and I want to make a dynamic form to render the questions. I use two widgets in my questions (widgets.RadioSelect and widgets.CheckboxSelectMultiple) to render the question's choices. when I submit the form I get the following error: Select a valid choice.['option1', 'option2'] is not one of the available choices. rises only from questions with the second widget eg:widgets.CheckboxSelectMultiple. The RadioSelect submits successfully. forms.py: class QuestionForm(forms.Form): def __init__(self, fields, *args, **kwargs): super(QuestionForm, self).__init__(*args, **kwargs) # Init form fields for field in fields: self.fields[field['name']] = forms.ChoiceField( label=field['label'], choices=field['choices'], widget=getattr(widgets, field['widget']), required=False ) views.py: def quiz(request, quiz_id): quiz = get_object_or_404(QCM, pk=quiz_id) if request.method == 'POST': if request.POST['action'] == 'Save': form = QuestionForm(data=request.POST) if form.is_valid(): print('form is valid :)') form.save() else: print('form is not valid :(') else: form = QuestionForm() context = { 'form': form, } return render(request, 'quiz/quiz.html', context) quiz.html {% extends "quiz/first.html" %} {% load staticfiles %} {% block main %} <form method="POST" class="form-horizontal" id="qcm_form" enctype="multipart/form-data"> <div class="row"> <div class="col-md-12"> {% csrf_token %} {% for field in form %} <div class="form-group"> <label class="field-label" for="id_{{ field.name }}">{{ field.label }}{% if field.field.required %} <span class="text-danger">*</span>{% endif %}</label> {{ field }} </div> {% endfor %} </div> </div> <input type="submit" … -
Why when i try to create a user in django the form doesn't react?
I tried to make a Customer: models.py class Customer(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=20, null=True) phone = models.CharField(max_length=10, null=True) email = models.CharField(max_length=40, null=True) with the use of this form forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] widgets = { 'username': forms.TextInput(attrs={'placeholder': 'username'}), 'email': forms.TextInput(attrs={'placeholder': 'email'}), 'password1': forms.TextInput(attrs={'placeholder': 'password'}), 'password2': forms.TextInput(attrs={'placeholder': 'repeat password'}), } html <form method="post"> {% csrf_token %} <ul class="list-group list-group-flush"> <li class="list-group-item"><p>{{ form.username }}</p></li> <li class="list-group-item"><p>{{ form.email }}</p></li> <li class="list-group-item"><p>{{ form.password1 }}</p></li> <li class="list-group-item" style="border-bottom: 1px solid #e4e5e6;"><p>{{ form.password2 }}</p></li> </ul> <input class="btn btn-primary" type="submit" type="button" style="width: 27%;margin-left: 63%;margin-top: 4%;"> </form> views.py def register(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() group = Group.objects.get(name='customer') user.groups.add(group) user.objects.create( user=user, name=user.username, ) return redirect('/') return render(request, 'register_page.html', { 'form': form, }) but when I click submit nothing happens and it doesn't create a record. Please help :( dasdsadasdasdasdfasewgaggiuhihqworeghoashgiiasigjioasigjiaipgjiaiasoopijpgjiaspjgpisapigaspj