Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to do transactions with Metamask and Python?
I am trying to develop a web app based on Django. The application has a button which should open Metamask in order to perform a payment transaction. In order to do so, I found some tutorials which suggest to use the JSON-RPC API or in other words, I need to add some javascript code which opens Metamask and asks to confirm the transaction. Here is my question: is there some way to achieve the same result but using only Python code which could be embedded in the Django back-end? I saw there is a library called web3.py which allows to do something similar but does not open the Metamask plug-in and therefore it lacks the nice interface. -
mw_instance = middleware(adapted_handler) TypeError: 'module' object is not callable
I have changed my database from SQLite to Mongo DB in setting.py and I have also run python manage.py makemigrations python manage.py migrate and everything seems to work fine but after starting the server with python manage.py runserver it given me the following error System check identified no issues (0 silenced). September 25, 2022 - 18:48:03 Django version 4.0.4, using settings 'passmanager.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Ashutosh Anand\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Ashutosh Anand\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Ashutosh Anand\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Ashutosh Anand\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 157, in inner_run handler = self.get_handler(*args, **options) File "C:\Users\Ashutosh Anand\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 31, in get_handler handler = super().get_handler(*args, **options) File "C:\Users\Ashutosh Anand\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 78, in get_handler return get_internal_wsgi_application() File "C:\Users\Ashutosh Anand\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\servers\basehttp.py", line 47, in get_internal_wsgi_application return import_string(app_path) File "C:\Users\Ashutosh Anand\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\module_loading.py", line 30, in import_string return cached_import(module_path, class_name) File "C:\Users\Ashutosh Anand\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\module_loading.py", line 15, in cached_import import_module(module_path) File "C:\Users\Ashutosh Anand\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", … -
How can I fetch more than one attribute from a serializer
My models have multiple attributes, all of which are being serialized. According to the user's request, I want my API to return only limited information This is my model's code from django.db import models class User(models.Model): name = models.CharField(max_length=50) age = models.PositiveSmallIntegerField() description = models.CharField(max_length=200) def __str__(self) -> str: return self.name This is my Serializer's code from rest_framework import serializers from .models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = "__all__" This is my View's code from rest_framework.decorators import api_view from rest_framework.response import Response from .models import User from .serializers import UserSerializer from rest_framework import serializers from rest_framework import status from django.http import JsonResponse @api_view(['GET']) def viewUsers(request): users = User.objects.all() serializer = UserSerializer(users, many=True) return JsonResponse({'id': serializer.data['id'], 'name': serializer.data['name']}) The code below works if I want to return a single attribute/field return JsonResponse(serializer.data['id']) but when I try to fetch more than one attribute by the dictionary method, it throws this error list indices must be integers or slices, not str -
Django. Serving staticfiles in production on local
Work directory: http://127.0.0.1:8000/static/apis/icons/random-svgrepo-com.svg gives me error 404 not found. settings.py STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/') STATICFILES_DIR = [ os.path.join(BASE_DIR, 'staticfiles/'), ] MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media') template.html {% load static %} <img src="{% static 'apis/icons/random-svg.svg' %}"> root urls.py from django.conf.urls.static import static from django.conf import settings urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I am running ./manage.py collectstatic, and then run the server. But it doesn't show me my image. My questions are: Difference between STATICFILES_DIR and STATICFILES_DIRS What I am doing wrong? Why my static files doesn't appear to work fine? Thanks! -
Django+React AWS LightSails Ubuntu deployment not using js
this is my first deployment, I have gone so far as to create and configure Ubuntu instance on lightsails following official guide. However, I run into problems when instead of an empty project I use my own Django hosting React frontend. My project works on my computer and if I start up django's production server thorugh manage.py runserver but does not run at all if I use gunicorn to run it with: gunicorn my_app.wsgi --bind 0.0.0.0:8000 --workers 4 It seems that it cannot find proper filepaths of any static files but I do not undertstand how to configure it to use it since Django already has all the right paths. One of the errors in the browser console: Refused to execute http://3.127.76.103/static/rest_framework/js/bootstrap.min.js as script because "X-Content-Type-Options: nosniff" was given and its Content-Type is not a script MIME type. How can I start fixing it, I do not understand why it does not see the any files. -
Why this type of error in my views.py file shown to me and how can I resolve them?
def visualisation(request,*args,**kwargs): payers=fees_record.objects.filter(month='SEPTEMBER',year=2022).order_by('-collected_time') for i in payers: all_borderers=students_detail.objects.exclude(name=i.student_name) context={ 'dataline':payers, #'def_list':defaulter } return render(request,'record_start.html',context) the error shows like this: Exception Value: Cannot resolve keyword 'name' into field. Choices are: School, created_time, department, email_id, id, phone_number, roll_number, room_number, students_name, wing_name -
Why does using a \r when calling django templates in views result in error?
I'm creating a view from my Django app that's suppose to call a template in my app directory called rooms. My app's name is room. When I write the code return render(request, 'base\room.html', context) I get an error at \r and the page doesn't load. Mind you, changing the template name to anything other than it starting without an r works fine. So, 'base\loom.html' works. Any idea why this is so? I only started noticing this recently -
Django - data retrieved in postgres database not showing in application
I had a database backup that i restored in postgres using COPY. The data is loaded correctly in database, a SELECT would show everything correctly. Yet in the connected app, the data is not being showed. The application is a django application, in admin I can see the data count yet I can't see data records, as shown in the picture joint bellow. We can see that I have 110 Question records yet the record entries are not accessible. Same thing with fetch and get. It would be great if anyone can guide me through this, thanks. -
DJANGO - call view.py function with HTML button click
I want to be able to CRUD data from my django-db through the view.py. {% extends 'home/base.html' %} {% load crispy_forms_tags %} {% block content %} <form method="POST" action ="{% url 'twitter' %}" enctype="multipart/form-data"> {% csrf_token %} <fieldset="form-group"> <legend class="border-bottom mb-4">Twitter Information</legend> {{ tw|crispy }} </fieldset> <div class="form-group"> </form> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> <button class="btn btn-info" type="submit">Update</button> <button class="btn btn-dark" type="reset">Reset</button> <a href="{% url 'twitter_container.twitter-edit' %}" class="btn btn-danger" type="submit">Delete</a> </form> {% endblock content %} twitter_container.twitter-edit is a view in my view.py. I'm trying to call this function on button clicked. -
optional values Django-rest-Framework
I am building API in Django-rest-framework but I have a model which has two main fields The request should be valid if user submit one field at least, he can submit both of them the problem is when I build the serializer I am getting error for set optional Fields here is my code models.py class KG(models.Model): content = models.TextField() image = models.ImageField(upload_to=nameFile, validators = [FileExtensionValidator(['png','jpg','jpeg'])],blank=True) serializer.py class KGSerializer(ModelSerializer): class Meta: model = KG fields = ['content',] def __init__(self, *args, **kwargs): if self.image: self.Meta.fields = list(self.Meta.fields) self.Meta.fields.append('image') super(PostSerializer, self).__init__( *args, **kwargs) views class createPostAPIView(APIView): def post(self, request): data = request.data content = data['content'] image = data['image'] serializer = KGSerializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) but when I request without image I get This QueryDict instance is immutable is there a way to allow any field to be optional -
Page not found (404) No post found matching the query Request Method: GET Request URL: http://127.0.0.1:8000/news/
As a newbie in Django, I am currently doing an entire website as a project with Django. My website has a navbar like the following: navbar I have created models, views and templates for all the tabs. My News tab is supposed to show the news objects that I gave as input in admin panel, and when I click the news, the details will be shown in the template that I wrote. Resources tab is a submenu which has Reports in it; if you click on Reports you will get to see a list of pdf files and upon clicking the file is shown, just like the News tab. My problem is, I have written the url paths in the project's urls.py file and app's urls.py file, but I am getting the following error. I cannot seem to figure it out. 404 My models file looks like the following; I am adding the models of home page, news page and reportpage: models.py from django.contrib.auth.models import User from django.db import models from django.urls import reverse from django.utils import timezone from ckeditor.fields import RichTextField from ckeditor_uploader.fields import RichTextUploadingField class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug … -
How to set the incoming object to true or false in Django
What I want to do is write "True" if there is data suitable for the filters made, otherwise "False" if ChartSimilar.objects.get(chart=pk, year=year): print('True') else: print('False') charts.models.DoesNotExist: ChartSimilar matching query does not exist. I get an error -
templateDoesNotExist at / in django (what settings to do)
I'm new to django. The error is coming templateDoesNotExist at / There is one app in my project,I've put the template folder in the app Structure is like: Project_name , manage.py,app_name,SQLite The structure of the app (app_name): other files... Inside template folder .. (Templates(folder) -> app_name(folder) ->HTML file) What setting I've to do in settings.py of prj to debug this error. Did I've to include path of every template of each app. ? Like inside setting.py in Templates DIRS: ['BASE_DIR', "path"] -
I get Is the server running on host "db" (192.168.176.2) and accepting TCP/IP connections on port 5433? when adding AUTH_USER_MODEL to settings
I have django web app with authentication. It all worked fine when I worked with sqlite and pipenv, but now I switched to docker and postgres and I constantly get an error: web_1 | File "/usr/local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect web_1 | conn = _connect(dsn, connection_factory=connection_factory, **kwasync) web_1 | django.db.utils.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "db" (192.168.176.2) and accepting web_1 | TCP/IP connections on port 5433? If I remove line with AUTH_USER_MODEL in settings.py this error goes away but I get other errors: web_1 | django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: web_1 | web_1 | ERRORS: web_1 | accounts.User.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'accounts.User.groups' clashes with reverse accessor for 'auth.User.groups'. web_1 | HINT: Add or change a related_name argument to the definition for 'accounts.User.groups' or 'auth.User.groups'. web_1 | accounts.User.user_permissions: (fields.E304) Reverse accessor 'Permission.user_set' for 'accounts.User.user_permissions' clashes with reverse accessor for 'auth.User.user_permissions'. web_1 | HINT: Add or change a related_name argument to the definition for 'accounts.User.user_permissions' or 'auth.User.user_permissions'. web_1 | auth.User.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'auth.User.groups' clashes with reverse accessor for 'accounts.User.groups'. web_1 | HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'accounts.User.groups'. … -
Is it possible to convert this Python CLI application into a Django app?
I created a python application that takes input from a user for hours and minutes and then displays an onscreen notification when the system has reached the time of the total hours and minutes. I wanted to turn this into a web application with the use of Django is this possible? import time import os from threading import Thread def userTimeSet(): while True: try: hours = int(input("Number of hours? ")) minutes = int(input("\nNumber of minutes? ")) if hours > 0 and minutes > 0: interval_sec = (hours*3600)+(minutes*60) print(f"hours and minutes to seconds checking: {interval_sec}") elif hours > 0 and minutes == 0: interval_sec = (hours*3600) print(f"hours to seconds checking: {interval_sec}") elif hours == 0 and minutes > 0: interval_sec = (minutes*60) print(f"minutes to seconds checking: {interval_sec}") else: print("invalid.") futureTime = timeConfirmation(hours, minutes) # create and start the daemon thread print('Starting background task...') daemon = Thread(target=timeCheck, args=(futureTime, interval_sec,), daemon=True, name='Background') daemon.start() print('Main thread is carrying on...') time.sleep(interval_sec) print('Main thread done running.') break except ValueError: print("Enter a number.") def timeConfirmation(hours, minutes): print(f"{hours}:{minutes} (hours:minutes)") currentDateTime = time.ctime() print(f"\n Current Date and Time: {currentDateTime}") timeInSeconds = (hours * 3600) + (minutes * 60) futureTime = time.time() + timeInSeconds print(f"\n Timer Ends at: {time.ctime(futureTime)}") return … -
Trying to pass two arguments to celery from django
Im quite new to celery and im trying to pass two arguments from django to a celery task to use them. If i try to pass one argument, task works fine but if i add a second argument the whole thing collapses. Any idea? My original working view-celery look like this: view: def detection(request): if request.method == 'GET': . . . . . . . elif request.method == 'POST': stress = AddImg(request.POST, request.FILES) if stress.is_valid(): stress = stress.save(commit=False) try: stress.stressImg = request.FILES['stressImg'] stress.save() Detection.delay(stress.pk) # Celery Task except: print("Something went wrong! Try again.") task: @shared_task(bind=True) def Detection(self, stressID): print("\n\n\n\n\n\n===============START===============\n\n\n\n\n\n") print(stressID) I tried changing my view but still no result: username = request.user.username Detection.apply_async(args=[stress.pk, username]) # Celery Task It does not work if i use .delay(stres.pk, username) and def Detection(self, stressID, username): as it says it finds 3 arguments instead of two even though it doesnt say the same when argument is one less . Any help would be appreciated. -
why I can not link these two pages in my django project
I have 2 models named developer and skill and I maid a page for all of the developers to show them all and after that I want to make a link for any of them to navigate to the page that shows that specific developer informations the page that shows all the developers url is 'developers/' and its name is developers and the url of the second page is 'developers/id' and its name is developer but I have no idea because it navigates to 'developers/developers/id' I tried the page that shows the informations of a certain developer and it was ok but I have problem with this one cause it won't navigate pleassseee helpp here are my codes : views.py from django.shortcuts import render from .models import Developer, Skill # Create your views here. def show_developers(request): query = Developer.objects.all() context = {'devs': query} return render(request, 'users/devs.html', context=context) def show_single_developer(request, pk): query = Developer.objects.get(id=pk) context = {'dev': query} return render(request, 'users/single_dev.html', context=context) models.py from django.db import models # Create your models here. class Skill(models.Model): choices = ( ('Beginner', 'Beginner'), ('Junior', 'Junior'), ('Senior', 'Senior'), ) name = models.CharField(max_length=50) level = models.CharField(choices=choices, max_length=10) class Developer(models.Model): full_name = models.CharField(max_length=50) username = models.CharField(max_length=50) intro = … -
Django Server on Raspberry Pi
I got an Raspberry Pi 3 Model B+ and I already installed DJango. But I have an already existing Django Projekt on my Computer. Does anybody know, who I put my existing Django Server on my Raspberry Pi. Or does someone have a video recomendations for my problem? Thans alot! -
Can we create a superuser in django without SHA256 hashing?
I am trying to create a superuser in django. but i dont want hashing, can we do it? or how to decrypt SHA256 using hash and key? -
Should the calculated values be placed in the database?
In the project I use django, django-rest-framework, postgresql database + react/next on frontend. While developing the application, I came across a problem which, for lack of more experience, I am not able to solve on my own despite reading dozens of similar topics. In every topic one statement manifests itself: it depends. Keep the calculated totals in the database or calculate them with each query? The application is the simplest WMS (goods receipt, orders, goods release, invoices, etc.) with the ability to display reports with charts. The problem, however, is the volume of data totals I have never encountered. 1000 orders per day * 40 products on order * 25 work days * 12 months = 12 000 000 rows and from this data will be made calculations for example charts about profit, total revenue, amount of tax, etc. Documents will not be changed practically ever, totals values also. However, I will read the values quite often, whether in the customer panel about invoices, orders or charts.... I'm afraid that recalculating these values every time will be a bad solution. On the other hand, these values used for later calculations are quite a lot ~20/30, maybe more. I will certainly … -
Django - Flexible DateTimeField precision with timezone
I have a database model that includes a DateTimeField as below: class Person(models.Model): .... date_of_birth = models.DateTimeField() date_of_birth_precision = models.CharField(max_length=3, choices=( ('Y', 'Year'), ('M', 'Month'), ('D', 'Day'), ('H', 'Hour'), ('Min', 'Minute'), ('S', 'Second'), ('MS', 'Millisecond') )) I have USE_TZ = True in my settings.py. My indentation is to give the user the flexibility to input the date_of_birth with the precision he wants according to the selected date_of_birth_precision, and I have already handled the picker format according to the selected date_of_birth_precision. So, for an instance, the input could be 1992, 1992-07, 1992-07-28, 1992-07-28 15, 1992-07-28 15:33, or 1992-07-28 15:33:45 depending on the selected precision. To be able to accept those different formats in my form, I have extended the accepted formats in settings.py as below: DATETIME_INPUT_FORMATS += ( "%Y", "%Y-%m", "%Y-%m-%d %H", ) So far, everything is working fine except some time zone problems: As the time zone settings is enabled, the date_of_birth is converted from my local time zone to UTC before saving to database, and the application will translate it back to the user's local time zone wherever he/she is when trying to show the object details. This is working fine if I have time fractions in my input … -
can not create virtual environment for a django project
I'm trying to create a Django project from scratch. I executed django-admin startproject autoshine in my zsh terminal. Then I opened pycharm and run pipenv install in its local terminal to create a virtual environment for this project. But I got this error: raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: '/home/mohsen/.local/share/virtualenvs/autoshine-YDp111VE/bin/python' I realized that in the above directory, it can create a virtual environment but unfortunately it doesn't have any bin file. I don't know how to solve this problem. Thank you for your answers in advance. -
How to run commands in CLI with Railway.app
I have Django project deployed to Railway.app. I've installed Railway CLI, but can't understand how to run python manage.py makemigrations and so on in its CLI to make Django runnig. My laptop is running Windows 10 Home. Ho do I? -
python3 flasktest.py * Serving Flask app 'flasktest' * Debug mode: off Permission denied
**Whenever this error comes while running the flask **> python3 flasktest.py > * Serving Flask app 'flasktest' > * Debug mode: off Permission denied**** make sure you have Authenticated Admin Mode. or you can change port if the port used is 80 which is already a Reserved/custom port you might get this error. change the port and try the issue will be resolved. Error Occurs - enter image description here Error Resolved - enter image description here -
KeyError at /api/rooms/create-grade/ 'grade'
I don't understand this error one bit, I'm trying to do a basic create method but i get a KeyError This is serializer.py code class GradeCreateSerializer(serializers.ModelSerializer): grade = serializers.ChoiceField(choices=GRADES, source="get_grade_display") class Meta: model = Grade fields = ["grade"] # ordering = ['-created_date'] def create(self, validated_data): user = None request = self.context.get("request") if request and hasattr(request, "user"): user = request.user try: perms = Perm.objects.get(user=user) except: perms = None if user.role in ['OWNER', 'PARTNER']: school = user.owns.first() elif perms is not None: if user.role == 'STAFF' and perms.can_crt_grade_class: school = user.works instance = Grade.objects.create( grade=validated_data['grade'], school=school, ) instance.save() return instance what am i doing wrong??