Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Images 'static' crash on redeploying - django app to heroku
When redeploying django app with heroku, and refresh the [age to see the changes, all the images crashed, are you familiar with this situation ? -
Hi everyone, I'm new to python and Django I'm trying to run a cloned repository on github when I run the commands: python manage.py migrate
Traceback (most recent call last): File "/home/cand/Python_Project/Data Science Github/gitando/django-simples/manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/cand/Python_Project/Data Science Github/gitando/django-simples/manage.py", line 21, in main() File "/home/cand/Python_Project/Data Science Github/gitando/django-simples/manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
How to fix Django logger Permission denied in Docker container?
I'm trying to run my Django project on docker I'm using logger to write in a .txt file but I'm getting an error related to permissions Django can't write in AdminFileDebug.txt This is the settings.py code LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'adminsDebug': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'log/AdminFileDebug.txt', 'formatter': 'verbose' # 'filename': '/path/to/django/debug.log', }, }, 'loggers': { 'AdminsDebug': { 'handlers': ['adminsDebug', 'console'], 'level': 'DEBUG', 'propagate': True, }, }, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {asctime} {message}', 'style': '{', }, }, } This is the docker compose file for my configuration: version: '3.9' services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=test - POSTGRES_USER=postgres - POSTGRES_PASSWORD=test app: build: context: . command: sh -c "python manage.py runserver 0.0.0.0:8000" volumes: - .:/app ports: - 8000:8000 environment: - DJANGO_DEBUG=1 - POSTGRES_NAME=test - POSTGRES_USER=postgres - POSTGRES_PASSWORD=test depends_on: - db when i run docker compose up i get this error PermissionError: [Errno 13] Permission denied: '/app/log/AdminFileDebug.txt' Any solutions? -
Is there any Django code for detecting plagiarism of a text file [closed]
I am making a website for detecting the plagiarism of a text file with Django. I need some codes that can compare two text file, and can detect that which part of the file1 is copied in file2 -
Pass data between views and response data using second view -> Django/DRF
I'm trying to implement APIView where I can pass data (category and number of flashcards that I want to see in response) from below view: def start_view(request): """ View where user is choosing the category he/she wants to learn flashcards from and number of flashcards. After submit the form view will upload chosen number of flashcards from chosen category. """ if request.method == "POST": form = LearningForm(request.POST) if form.is_valid(): category_to_learn = form.cleaned_data["category"] number_of_flashcards_to_learn = form.cleaned_data["number_of_flashcards"] queryset = Flashcard.objects.filter( # type: ignore category=category_to_learn )[:number_of_flashcards_to_learn] return render(request, "flashcard_challenge.html", {"queryset": queryset}) else: form = LearningForm() return render(request, "start_page.html", {"form": form}) In above view I have list in response (I want json using other endpoint.) I got stuck few days ago and I don't know what to do.. All I want is: Choose category (from those I have in a db) and write number of flashcards in start_view and than I want to be redirect to view where flashcards (from chosen category) will be displayed in json format. I'd be thankful for any advice. -
Don't understand how to logout of FusionAuth from Django Application
I am writing a Django app that uses a 3rd-Party Authentication Service implemented with FusionAuth. I can successfully register and login (using the authorization code flow). However, logging out is not working. I can logout from the local Django app, but when I try to login after that FusionAuth recognizes that my access_token is still valid and just goes directly to the redirect page (the page you usually goto after successfully logging into FusionAuth). Clearly I don't understand something about FusionAuth. I have tried both the python client and the restful API and I don't really understand what it does. According to the documentation it "...is intended to be used to remove the refresh token and access token cookies if they exist on the client and revoke the refresh token". Why then is the access_token still valid? -
CHECK IF A USER HAS ALREADY ADDED AN ELEMENT IN THE DATABASE
I need help💔😥 !!! please someone help me. I designed a site like a directory, where school administrators can log in and add their schools, it works perfectly. but in the life in the picture, the user creates an account and he is directed to the login page, if he logs in, he is directed to the add school page directly, after adding he is direct towards its no reception. All works perfectly. but my problem is that I want to check if the user has already added a school, he skips the step of adding a school, and that he goes directly to his home page. PLEASE I NEED HELP, I HAVE TO DELIVER THIS TOMORROW AND I AM DESPERATE! PLEASSSSSSSE😪 URLS from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from . import views, visit_views, Hot_views, user_login urlpatterns = [ path('admin/', admin.site.urls), path('base', views.BASE, name='base'), path('', views.HOME, name='home'), path('ecole', views.ECOLE_SECONDAIRE, name='ecole_secondaire'), path('contact', views.CONTACT_US, name='contact_us'), path('about', views.ABOUT_US, name='about_us'), path('View-school/<str:id>', views.VIEW_SCHOOL, name='view_school'), path('accounts/register', user_login.REGISTER, name='register'), path('accounts/', include('django.contrib.auth.urls')), path('doLogin', user_login.DOLOGIN, name='doLogin'), path('doLogout', user_login.doLogout, name='logout'), path('Hothome', Hot_views.HOME, name='hothome'), path('Add-school', Hot_views.ADD_SCHOOL, name='add_school'), path('View-school', Hot_views.VIEW_SCHOOL, name='hote_view_school'), path('Update-school', Hot_views.UPDATE_SCHOOL, name='update_school'), path('Delete-school', Hot_views.DELETE_SCHOOL, name='delete_school'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) … -
Django: How to update choice field in DJango?
I have a model with a tuple, that i use in a fields for choices, it looks like this TRANSFER_STATUS = ( ("Failed", "Failed"), ("completed", "Completed"), ("pending", "Pending"), ("processing", "processing"), ("none", "None"), ) class ModelName: status = models.CharField(choices=TRANSFER_STATUS, max_length=100, default="none") when a condition is met, i want to change the default which is processing to completed, i have tried doing it from views.py but it does not seem to work. @login_required def TransferProcess(request, account_number, transaction_id): transfer_transaction = Transaction.objects.get(transaction_id=transaction_id) if request.method == "POST": pin_number = request.POST.get("pin-number") if pin_number == request.user.account.pin_number: transfer_transaction.status = 'completed' transfer_transaction.transaction_type = 'transfer' transfer_transaction.save() # sender_account = int(sender_account.account_balance) - int(transfer_transaction.amount) sender_account.account_balance -= transfer_transaction.amount sender_account.save() account.account_balance += transfer_transaction.amount account.save() messages.success(request, "Transfer Successful.") return redirect("core:transfer-successful", account.account_number, transfer_transaction.transaction_id) else: messages.warning(request, "Pin not correct, try again") return redirect("core:transfer-confirmation", account.account_number ,transaction_id) -
How to put object datefield in html input value
I have a class "client" with an attribute datefield called "birth_date". I want to give the possibility for update this field. How can i put the default value in the form, in the input type date? Because the format in "client.birth_date" is different. If i try with, for example: The input value is setting true, but the format is different from the one i get -
Django template error in basic html file?
I have coded the navbar in basic.html which is extended with all other pages. In the navbar, I added a social link button and their links were added by admin from the admin panel and I fetched in views function and render it to basic.html. But problem is that these social buttons not working on all other pages that are extended with basic.html . one solution is that if I get these links from database in all functions then it works. But In this case code repeats and repeats. I have around 30 functions, so I need a common solution. -
When you insert a text value that contains quotation marks or an apostrophe, it is truncated
When pasting a text value containing quotes or an apostrophe using jQuery into a value field, it is truncated at that character. I know about single and double quotes. The text can be anything. It is saved in the database normally, everything is in order in the variable, but when outputting to html - confusion. How to avoid this error? One of the options: $('<div>', { class: 'menu-block', html: `<div class="menu-button"> <button onclick="return itemField(this)" type="button" class="btn btn-warning"> <i class="bi bi-pencil"></i> </button> <button onclick="return deleteField(this)" type="button" class="btn btn-danger""> <i class="bi bi-trash"></i> </button> </div> <div class="row"> <div class="col"> <input type="text" class="form-control" data="label" value='${label}' disabled /> </div> <div class="col"> <input type="text" class="form-control" data="datal" value='${datal}' disabled /> </div> </div>` }).appendTo('#div-extra'); -
Django change secret-key in settings from previous developer
I want to change my SECRET_KEY for deploying in production, and I found this tool for using - https://pypi.org/project/django-generate-secret-key/ but, it seams that this tool is not working, because it's not changing the existing key... what I'm doing wrong? P.S tried with --replace flag, but seams no result... Can anyone help me with it? -
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"]