Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django media folder vs Flask Database
what consume bigger space in the C: directory. Images from django in the media folder or flask's files in the database that has been add like this: file = Files(file=file.read())? -
I don't understand what the error is. django ajax pagination
I'm trying to do django pagination using ajax, but there is a problem. The problem is that when I click on a page, elements on that page are cleared, but others are not added. Initially everything is fine, I start clicking on pages and all the content disappears. I don't understand why (I'm not good with js), can anyone help. Code views.py class ReviewsView(ListView): model = Review template_name = 'reviews.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['reviews'] = Review.objects.all() paginator = Paginator(context['reviews'], 1) page = self.request.GET.get('page') try: context['reviews'] = paginator.page(page) except PageNotAnInteger: context['reviews'] = paginator.page(1) except EmptyPage: context['reviews'] = paginator.page(paginator.num_pages) return context Code reviews.html <div id="reviews" class="row md-3"> {% for review in reviews %} <div class="col-md-6"> <div class="reviews-card reviews__link"> <div class="reviews-card__box"> <div class="reviews-card__author"> <div class="reviews-card__preview"> <picture> <img class="reviews-card__img" src="{{ review.photo.url }}" alt="{{ review.name }} {{ review.surname }}"></picture> </div> <div class="reviews-card__name">{{ review.name }}<br>{{ review.surname }}</div> </div> <p class="reviews-card__text">{{ review.content }}</p></div> </div> </div> {% endfor %} </div> {% if not reviews.paginator.page_range|length == 1 %} <div class="pagination__wrapper"> <div id="pagination" class="pagination"> {% for page in reviews.paginator.page_range %} {% if reviews.number == page %} <span class="active">{{ page }}</span> {% elif page > reviews.number|add:-2 and page < reviews.number|add:2 %} <a class="page" href="{{ request.path }}?page={{ page }}">{{ … -
JS & Django- How to access a value from H1 tag using DOM? I am getting no response from the JS
I am passing an integer value to HTML template, and I want to access it before it is shown to the user. Here's the code: status.html <div id="frame_body"> <div id="percentage"><h1 id="receivedVal">{{projects.phase}}<sup>%</sup></h1></div> <div id="proj-name"><p>XXXXXXXXXXX</p></div> <div id="name-of-staff-head"><p>Supervised by Mr. X</p></div> <div id="temporary"> <!-- <p>Status -{{projects.status}}</p> <br> <p>Phase -{{projects.phase}}</p> <br> <p>Collaborators -{{projects.collab}}</p> --> </div> </div> JS: function showPercentage(){ var phase_no = document.getElementById("receivedVal").value; var percentage = (phase_no / 10) * 100; document.getElementById("receivedVal").innerHTML = percentage; } As you can see from the code, I want to perform that calculation and return new value there again. How can I do that? -
csrf token missing when using django Views
When I am submitting a login form for a normal user or for admin. I get the following error CSRF token missing or incorrect. The interesting things when I use a custom view for registering everything is fine. I tried to swap the urls from my custom projects to the one created by django initially and neither options work login.html <form method="POST"> {% csrf_token %} <fieldset"> <legend>Log In</legend> {{ form|crispy }} </fieldset> <div class="logBu"> <button type="submit">Login</button> </div> </form> urls.py path('register/', views.register, name='register'), path('login/', Builtviews.LoginView.as_view(template_name='main/login.html'), name='login'), path('logout/', Builtviews.LogoutView.as_view(template_name='main/logout.html'), name='logout'), Ive cleared out all my cookies. Ive even added a csrf_trusted origins as well as CORS to settings but nothing works. I even downgraded django since i read this is a 4.0.0 thing and that didnt work either. settings.py CSRF_TRUSTED_ORIGINS = [ 'http://127.0.0.1:8080/admin', 'http://127.0.0.1:8000/admin/login', 'http://127.0.0.1:8000/admin/login?next=/admin/', 'http://127.0.0.1:8000/login', 'http://127.0.0.1:8000/login/', 'http://127.0.0.1:8000/login?next=/profile/', #Encrypted version 'https://127.0.0.1:8080/admin', 'https://127.0.0.1:8000/admin/login', 'https://127.0.0.1:8000/admin/login?next=/admin/', 'https://127.0.0.1:8000/login', 'https://127.0.0.1:8000/login/', 'https://127.0.0.1:8000/login?next=/profile/' ] CORS_ORIGIN_WHITELIST = [ 'http://127.0.0.1:8080' ] I have added corsheaders to installed apps as well as the appropriate things to middlewear -
http://127.0.0.1:8000' has been blocked by CORS policy Django AJAX
I'm working on AJAX call but I'm struggling on the CORS error 'http://127.0.0.1:8000' has been blocked by CORS policy: I've search all over the internet but no luck I also tried django-cors-headers $(document).ready(function() { var delay = 2000; $('.view-data').click(function() { var slug = $(this).attr("slug"); alert(slug); $.ajax({ method: "post", url: "core:bell_schedule/", data: { slug: slug }, beforeSend: function() { $('#applicant-display').html('<div class="spinner-border text-secondary" role="status"><span class="visually-hidden">Loading...</span></div>'); }, success: function(data) { setTimeout(function() { $('#applicant-display').html(data).fadeIn('slow'); }, delay); }, error: function(data) { alert('Error 100'); } }); }); }); -
Place management application - What technologies? [closed]
I came up with a building space management application for each floor. I would like it to be a web application. After logging in, the user could select the building, floor and the floor map should be displayed. By pressing on a room, he could reserve it. In what technologies could I implement it? I was thinking about python and django, maybe some react, java and angular. I have no experience in building such an application. I only did a few projects in python, c ++ and java. I would like to find an example of such an application, maybe a video. I can't find anything like that myself. Any ideas? -
dynamic log filename with incoming post request data in Django logging
I am very new to Django. I have a use case wherein, I have to group a log filename from incoming post request json data Example of post request json data { "name": "kurt", "year_of_birth": 1996, "course": "Arts" } I want to have a filename 1996.log to be generated, so that I can have datas of all the students with year_of_birth 1996 logged in 1996.log Example 2 { "name": "Mike", "year_of_birth": 1994, "course": "Science" } in this case log filename should be 1994.log This way I want to generate log filname by year_of_birth and have logs logged in respective log file with respect to incoming post request data views.py from rest_framework import viewsets import logging student_logger = logging.getLogger("student_log") class BlogViewSet(viewsets.ViewSet): def create(self, request, *args, **kwargs): data = request.data print(f"\n############ data: {data} \n\n") student_logger.debug(data) return Response({"data": "logged successfully", "msg": "success"}) LOGGING in settings.py LOGGING = { "version": 1, "formatters": { 'student_formatter': { 'format': '{levelname} {asctime} {pathname} {filename} {funcName} {lineno} {message}', 'style': '{', }, }, "handlers": { "student_handlers": { "level": "DEBUG", "class": "logging.FileHandler", "filename": os.path.join(BASE_DIR, "logs/year_of_birth.log"), # want to change year_of_birth.log with incoming post request data's year_of_birth i.e 1996.log, 1994.log 'formatter': 'student_formatter' } }, "loggers": { "student_log": { "handlers": ["student_handlers"], "propagate": True, … -
`django-import-export` import/export nested related objects
I want to export department name, but failed. # models.py from django.contrib.auth import get_user_model from django.db import models class Department(models.Model): name = models.CharField(max_length=180, blank=True, null=True, unique=True) class HseUser(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) dept = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, blank=True) class UserModelProxy(get_user_model()): class Meta: proxy = True admin.py from import_export.admin import ImportExportActionModelAdmin from import_export import fields from import_export import resources class UserResource(resources.ModelResource): hseuser = fields.Field(attribute='hseuser', column_name='name', widget=ForeignKeyWidget(HseUser, 'name')) # ??? department export class Meta: model = get_user_model() class MyUserAdmin(UserAdmin, ImportExportActionModelAdmin): resource_class = UserResource admin.site.register(UserModelProxy, MyUserAdmin) Using admin actinon to export xlsx, succeed to export hseuser.name, but failed to export department name. How to fix it? -
Can any one suggest how to render a pdf document using base64 string in html
Can any one suggest how to render a pdf document. I am using the same method suggested by Will Keeling, so instead of image, I am using pdf <object id="documentFileViewModalContext" frameborder="0" width="100%" height="100%" data="data:application/pdf;base64,{{ base64_string}}" type="application/pdf" class="internal"> <embed src="data:application/pdf;base64,{{ base64_string}}" type="application/pdf" /> </object> And in python code as below pdf_file = branchDocumentFileObject.document.path file_handle = open(pdf_file, "rb") base64_string = base64.b64encode(file_handle.read()).decode('ascii') context['base64_string'] = base64_string html_content = render_to_string("adminToolsApp/manage/branch/document/documentView.html", context=context, request=request) returnStatus['status'] = 'success' returnStatus['response'] = html_content return JsonResponse(returnStatus, safe=False) I would appreciate your suggestion Thanks Benny -
After Saving value in Positive Intefer filed Django Models, can not be edit later on
I am working on postive integer field on django models.py , I want to make that filed unchangeble after saving. Can not be eidt after saving value. models.py end_run = models.PositiveIntegerField( null=True, blank=True, help_text=_("Can be enter value Onece") -
Running a streaming api python script on cPanel
I have looked over lots of info on running scripts in cPanel and I have successfully learned to do it with cron jobs etc. But with regard to a script that streams data via API I can’t find much info. Cron jobs sends me an email after execution so I know its working or not. However with a continuous data streaming script I do not know how to tell if it is running and working. I have figured I would need to setup a django web app interface to monitor it but I am not a web app programmer. Is there something out there that makes this easier? Or do I need to integrate the script into a django webapp (which means paying someone to do it for me…) ? -
How to overwrite all objects in Django database after uploading an excel file?
So I have a Leaderboard page and a Django model such as: models.py class Leaderboard(models.Model): rank = models.IntegerField() team_name = models.CharField(max_length=100) score = models.IntegerField() The thing I'm confused is how can I write the views.py function so that whenever I make a request and upload a new excel file to the views.py it would overwrite the old objects inside of the database and fill the database with the new data. I'm not sure if this is the correct way of creating a manual leaderboard but it's the only way I could think of currently. What I could think of so far: views.py def update_leaderboard(request): new_excel = request.body data = pd.read_excel(new_excel) # Overwrite the database here ... ADDITIONAL INFORMATION I'm using Django Rest Framework as well in this case, because I'm using React for my frontend. So the views might come out a little different (?) -
(DRF) How to update a foreignkey field
I have two models, Account model & Thread model: class Account(AbstractBaseUser, PermissionsMixin): class Meta: verbose_name_plural = "Account List" email = models.EmailField(max_length=255, unique=True) username = models.CharField(max_length=255, unique=True) name = models.CharField(max_length=255, default="") profile_image = models.ImageField(max_length=255, upload_to=profile_image_path, blank=True, null=True, unique=True) about = models.TextField(max_length=255, default='Write something about yourself...', blank=True) start_date = models.DateTimeField(default=timezone.now) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(auto_now=True) objects = AccountManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username", "name"] def __str__(self): return self.username class Thread(models.Model): options = (('active', 'Active'), ('deactivated', 'Deactivated')) username = models.ForeignKey(Account, on_delete=models.CASCADE, to_field='username') alt = models.TextField(max_length=255, blank=True) image = models.ImageField(max_length=255, upload_to=thread_image_path, blank=True) content = models.TextField(blank=True) created = models.DateTimeField(blank=True, null=True, default=timezone.now) status = models.CharField(max_length=11, choices=options, default='active') If I have already created a thread that is ForeignKey to the Account model, I am not able to change the username of the Account model, returning the error FOREIGN KEY constraint failed. I guess the existing Thread model require a username to point to. Is there way to create a custom update method in view.py to update the ForeignKey automatically? Here is my view.py: class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = Account.objects.all() permission_classes = (AllowAny,) -
Send user to the page they requested before Signing in with google, after they sign in with google
I have a movie quiz app https://www.quizsocial.xyz/, where users can search for a trending movie and take a quiz about the movie’s story, so when they land on the homepage, they search for their movie, they click start quiz, they agree to the rules, they select how many questions they want to attempt and then they have to sign in with google or create an account, now if they create an account through us, their requested quiz will start automatically once they sign in, but when they do the same thing with google log in, they are redirected to the homepage. Where they have to search for the quiz again, agree to the rules, select how many questions they want to attempt. This may annoy some users and lead them to leave the website and never come back. My question is how do I retrieve their data before they signed up with google and then send them to the exact page they requested after they sign in with google. -
Where I can find modern django admin, that have good tools to work with images?
I want to create django project and connect it with modern admin. I want to get multiuploading images and immediate showing images when I choose them on PC (not after reloading). All that I can find - different CMS (with a lot of less tools) and some beautifiers for admin, that don't provide any new functionality. Can you recommend any? -
Django + Python vs PHP
I'm confused... Sorry for the stupid question, but I'm really confused about python I like PHP because it's so simple. You write logic in one file, then just reference it into your file OR you just write it directly in the php file that is rendering the markup... I thought python was going to be kind of the same, but it's not, to me it's way more complicated. I don't understand why I need Django or Flask to just write logic and manipulate data like I can in PHP. My Question Can I create a Website Backend like I can in PHP, but using Python without having to learn extra syntax and file structure from a framework? -
Celery disallowing the usage of dictionary data type
I have defined a shared_task with celery as follows: @shared_task(bind=True) def create_parameters_for_task_creation(project_type, dataset_instance_ids, filter_string, sampling_mode, sampling_parameters, variable_parameters, project_id) -> None: """Function to create the paramters for the task creation process. The function is passed arguments from the frontend which decide how the sentences have to be filtered and sampled. Args: project_type (str): Describes the type of project passed by the user dataset_instance_ids (int): ID of the dataset that has been provided for the annotation task filter_string (str): _description_ sampling_mode (str): Method of sampling sampling_parameters (dict): Parameters for sampling variable_parameters (dict): _description_ project_id (int): ID of the project object created in this iteration """ As soon as I try to run celery workers - celery -A shoonya_backend.celery worker -l info, I get the following errors. Unrecoverable error: TypeError("cannot pickle 'dict_keys' object") I believe that Celery is not allowing me to pass the dictionary data type which is weird because my settings allow json datatype. CELERY_BROKER_URL = 'redis://localhost:6380' result_backend = 'redis://localhost:6380' accept_content = 'json' result_serializer = 'json' task_serializer = 'json' What should be done? -
How do I connect my Django App to Postgres Databse?
How do I connect my Django App to Postgres Databse? Whenever I run python manage.py makemigrations after the changes, then I get this kind of error. How can I fix it? Got an error checking a consistent migration history performed for database connection 'default': connection to server at "localhost" (::1), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? warnings.warn( No changes detected -
How Do I Correctly Serialize and Send PayPal Transaction ID to Django Backend Doing Standard Client Side Integration
I'm trying to get PayPal's transaction ID after the payment was approved on the client-side. I'm doing client-side integration of PayPal and Django. I can totally get the Payment ID and order ID and so forth, but these will be discarded by PayPal after the payment got approved. PayPal only recorded Transaction ID which can be used to track the payment with PayPal. When I'm trying to serialize the return actions which capture the Transaction ID - somehow I got a status code of 500 - Internal Server Error. The funny thing is that I can totally do console.log(transaction.id) and get the transaction ID in the console. Anyway, my error prone code is below: In payment.html I got huge portion of html stuff, but I don't post it here. I only post where the JavaScript begins: <script> // Generating csrf_token on the fly function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + … -
Authorization header with Bearer token in swagger django DRF
During testing endpoints, for every refresh, I need to, again and again, generate a login bearer token --> go to authorize button of swagger--> add token ---> and authorize. Then I can test endpoints that need authentication. But, this is very repetitive. Once I have a token, Is there a way that I can auto-authorize swagger endpoints? -
pytest-django django_db_server fixture not working
I would like to use a specialized test database for unit testing my Django app. I'm using pytest along with pytest-django. Per the pytest-django instructions, I provided my own custom django_db_setup fixture in a conftest.py file as follows: from pathlib import Path import pytest from django.conf import settings @pytest.fixture(scope='session') def django_db_setup(): base_dir = Path(__file__).parent path = base_dir / 'test_db.sqlite3' assert path.exists() assert path.is_file() settings.DATABASES['default'] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': path } I can confirm that this code is being executed when I run unit tests, and the test_db.sqlite3 database is being found. However, the unit tests are still referring to my development database not my test database. How do I get pytest-django to reference my test database instead of my development database? -
Both logging and print statements inside django channels consumer are not working
I'm trying to integrate celery with django channels but channels consumer is not working as it supposed. Logging or prints inside consumer functions are not displaying message in terminal. The following celery task is called from signals.py tasks.py from channels.layers import get_channel_layer @app.task def send_request_notification(): text = 'You have new cleaning request' channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'companies_received_request', # group name { 'type': 'send_notification', 'text': text } ) print("SENT ---") # can see result of this print consumers.py class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): logger.info("Connected to websocket") await self.channel_layer.group_add( 'companies_received_request', self.channel_name ) await self.accept() async def disconnect(self): await self.channel_layer.group_discard( 'companies_received_request', self.channel_name ) logger.info("Disconnected from websocket") async def send_notification(self, event): logger.info("Here in sending notification") text_message = event['text'] await self.send(text_message) print("EVENT.TEXT") print(text_message) settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [('127.0.0.1', 6379)], }, }, } I am supposed to get the output of prints and logging of consumer functions in terminal but I'm getting nothing -
What task queue should be used when using RabbitMQ in JAVA?
So I was switching my code base from Django to Spring Boot Java. But before that I was trying to find analogous framework and library for every feature that I have implemented in Django. One of the thing in which I was stuck was, for my message queues, In Django I was using Rabbit MQ as message Queue and Celery as the Task queue to process the queue content. Task Queue and Message Queue. RabbitMQ is a "MQ". It receives messages and delivers messages. Celery is a Task Queue. It receives tasks with their related data, runs them and delivers the results. In Java I can use RabbitMQ as message queue but what package do I have for spawning the workers? Processing the queue? What should I use as a task queue here? How does it work exactly in Java? -
Django mod_wsgi Apache error 403 Forbidden on Ubuntu 22.04
Django mod_wsgi on Apache application works fine in Ubuntu 20.04 and previous versions with the configuration mentioned below, but when I do the same configuration in Ubuntu 22.04 it gets 403 Forbidden error. and Permission denied: mod_wsgi in the error log. I tried changing permission on all files it's doesn't work, Apache config: <VirtualHost *:80> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /home/ubuntu/mydjango/mydjango> <Files wsgi.py> Require all granted </Files> </Directory> alias /static /home/ubuntu/mydjango/static <Directory /home/ubuntu/mydjango/static> Require all granted </Directory> WSGIDaemonProcess myapp python-home=/home/ubuntu/mydjango/venv python-path=/home/ubuntu/mydjango WSGIProcessGroup myapp WSGIScriptAlias / /home/ubuntu/mydjango/mydjango/wsgi.py </VirtualHost> Apache Error Log: Current thread 0x00007fb606719780 (most recent call first): <no Python frame> [Sun Jun 05 05:59:07.594727 2022] [wsgi:warn] [pid 37044:tid 140419768883072] (13)Permission denied: mod_wsgi (pid=37044): Unable to stat Python home /home/ubuntu/mydjango/venv. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/home/ubuntu/mydjango/venv' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/home/ubuntu/mydjango/venv' sys.base_exec_prefix = '/home/ubuntu/mydjango/venv' sys.platlibdir = 'lib' sys.executable = '/usr/bin/python3' sys.prefix = '/home/ubuntu/mydjango/venv' sys.exec_prefix = '/home/ubuntu/mydjango/venv' sys.path = [ '/home/ubuntu/mydjango/venv/lib/python310.zip', '/home/ubuntu/mydjango/venv/lib/python3.10', '/home/ubuntu/mydjango/venv/lib/python3.10/lib-dynload', ] Fatal Python … -
python3 - Pass function arguments to another function
def findUser(params): user=Users.objects.filter(params).first() if(user): return user return False findUser(name='a',code=123) How to do this ? In what way to pass parameters to another function?