Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Images not store in media folder but creating a folder and store
I am trying to upload some images in my app media folder. The problem is images uploaded successfully but not in media folder. Its creates another folder and store their. My code details are given bellow: urls.py from django.contrib import admin from django.urls import path from ssibdweb import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIAFILES_DIRS) settings.py MEDIA_DIR = BASE_DIR / 'media' MEDIA_URL = '/media/' MEDIAFILES_DIRS = [ STATIC_DIR, ] models.py class BlogImage(models.Model): id = models.AutoField(primary_key=True) sub_id = models.ForeignKey(Subject, on_delete=models.CASCADE) pic = models.ImageField(upload_to='blog/') def __str__(self): return str(self.id) I am using following form for upload <form method="POST" enctype="multipart/form-data" > -
Add crontab form in non-admin forms django
I want to add crontab schedule to a non admin form. I can see the registered jobs with crontab class Scheduler(ModelForm): class Meta: model = Scheduler fields = [ 'id', 'title', 'description', 'crontab' ] The problem here is I can't see the button to add a new schedule. How to add that can someone tell me. -
problem with updating counter with jquery inside loop with django
everything is working correctly, except when clicking the increment or decrement buttons, only the last product on the cart is updated!!!, for other carts, I can update the value manually and click the button it will updated without any problem !!! this is the code for .html in django {% for item in cart %} <div class="card rounded-3 mb-4 "> <div class="card-body p-4"> <div class="row d-flex justify-content-between align-items-center"> <div class="col-md-2 col-lg-2 col-xl-2"> <img src="{{ item.product.product_image.url }}" class="img-fluid rounded-3" alt="Cotton T-shirt"> </div> <div class="col-md-3 col-lg-3 col-xl-3"> <p class="lead fw-normal mb-2">{{ item.product.name }}</p> <p><span class="text-muted"> {% if item.product.is_service %} Service {% else %} Product {% endif %} </span> <span class="text-muted"> </div> <div class="col-md-3 col-lg-2 col-xl-2 d-flex product_data"> <input type="hidden" value="{{ item.product_id }}" class="prod_id"> {% csrf_token %} {% if item.product.is_service == False %} {% if item.product.quantity >= item.product_quantity %} <div class="container"> <div class="row"> <div class="col-lg-2"> <div class="input-group"> <span class="input-group-btn"> <button type="button" id="quantity-left-minus" class=" changeQuantity btn btn-primary btn-number" data-type="minus"> <span class="glyphicon glyphicon-minus"></span> </button> </span> <input type="number" id="quantity" class=" align-items-center qty-input" value="{{ item.product_quantity }}"> <span class="input-group-btn"> <button type="button" id="quantity-right-plus" class=" changeQuantity btn btn-primary btn-number" data-type="plus"> <span class="glyphicon glyphicon-plus"></span> </button> </span> </div> </div> </div> </div> {% else %} <h3>Out of Stock</h3> {% endif %} {% endif … -
Problem downloading full database in Django
First I used export_import to download the database but I only downloaded a single table at a time but I need to export the entire database to a file then import it back. Now I'm trying to fix it with another way I just saw using resources If you could help me to change it to a view instead of a function I would be grateful. Note: Thanks for the help. views.py from django.shortcuts import render from django.http import HttpResponse from .resources import CommentResource, CategoryResource # Create your views here. def export_data(request): if request.method == 'POST': # Get selected option from form file_format = request.POST['file-format'] comment_resource = CommentResource() dataset = comment_resource.export() print(type(CommentResource())) print(type(CategoryResource())) if file_format == 'CSV': response = HttpResponse(dataset.csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="exported_data.csv"' return response elif file_format == 'JSON': response = HttpResponse(dataset.json, content_type='application/json') response['Content-Disposition'] = 'attachment; filename="exported_data.json"' return response elif file_format == 'XLS (Excel)': response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="exported_data.xls"' return response return render(request, 'export_import_data_page.html') resources.py from import_export import resources from label.models import Comment, Category class CommentResource(resources.ModelResource): class Meta: model = Comment class CategoryResource(resources.ModelResource): class Meta: model = Category This is the html file to call the function to download the database export_import_data_page.html <!DOCTYPE html> <html> … -
How to remove "Select all" options from Django model admin
Django model admin allows to select all the objects in a page to take certain actions ('Delete selected' being one of them). After selecting all the model objects in a User model page, it gives an option to "Select all xxxx users" (xxxx being a number) as shown in the image. This allows the admin to select all the users and when exported to CSV, such a huge data size causes Gateway Timeout issue. We only want the admin to select the objects in a single page and not all of it in one go. Any help regarding this is appreciated. -
How to structure files in Django Rest Framework?
My requirement is the following: Create endpoints that will return various reports(json) representing organized data based on some specifications. Example: We have a car company with a lot of customers data. What I need to do is to generate reports which will contian month to month revenue from different categories of customers. Our project uses Django Rest Framework and the file structure is as the one below: mysite/ ├── manage.py │ ├── mysite/ │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py │ └── app1/ ├── api/v1/ │ └── serializer/ │ │ └── serializer_model1.py │ │ └── serializer_model2.py │ └── view/ │ │ └── view_model1.py │ │ └── view_model2.py │ └── permissions.py ├── migrations/ │ └── __init__.py ├── __init__.py ├── admin.py ├── apps.py ├── forms.py ├── signals.py ├── models.py ├── tests.py └── views.py // not used So, for "car" model we have one view and one serializer file inside api/v1/. My questions are: Is this structure ok? Where I should write those queries to generate data for the reports? (new app?, different view?) If I have snippets of code which are used on multiple views, where should I place that code so I can … -
Django Notification HQ - I installed the app manually but no signal is being sent
I have a django app and I wanted to install django-notification-hq (https://github.com/django-notifications/django-notifications) I wanted to modify some parts of the app so I downloaded the repo and install it. I first install it using the recommended approach in github (here below) and it all worked. $ git clone https://github.com/django-notifications/django-notifications $ cd django-notifications $ python setup.py sdist $ pip install dist/django-notifications-hq* However, I wanted to try a different way (also because I wanted to learn) and add the app like if had developed it entirely. So I removed everything I did I took the notifications folder inside django-notifications and added it directly to my project. I changed my project settings and add 'notifications.apps.Config', I updated my req.tx and installed necessary libraries Now, the project runs and nothing breaks....however, no notification is being generated. I followed as much as possible the code and noticed that it's the notify.send() that doesn't send anything. This makes me think that there is something about signals that I am not doing right? -
Django templates - sudden appearance of "" in my html
Has anyone discovered the sudden appearance of "&#xFEFF;" in their html? -
I want to be able to render a Django object on the HTML and have other Django objects manipulate the rendered HTML
I am building fan website for my portfolio for a popular MOBA game. What I want to happen is when you go to a champions detail page that shows the champions stats (attack damage, magic damage, etc), I want the user to be able to click on an item, and that items stats will add on the already rendered stat value. For example, Champion "x" has 25 base attack damage. Item "a" has 5 attack damage. Click on item "a" and the champion's stats will now show 30 attack damage. When double clicking the item it will remove the added 5 attack damage and now show 25 attack damage again. The clicking method and order is not mandatory but preferred because that was my initial draft and since I am learning I think I should force myself to deal with it. I was wondering if someone could point me in the right direction for using event listeners/what javascript or method would be the best way to do this, other than loading every single item into global variables in the script file. Code for reference. I have heard about AJAX but I don't want to dive into that into the moment … -
Getting same IP address for all my devices while getting the META data from the request
In my webapp I was getting the IP address of the user system and showing the same in the landing page. However for testing when I am making a request from all my devices at home I see same IP address(49.37.71.31). 2 questions Why is this happening How can I uniquely identify the machine which is making the request to my web app. index.html <div class="button add-list-button"> <a href="javascript:void(0)" class="btn">{{ ip }}</a> </div> views.py def index(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return render(request, 'index.html', context = {'ip':ip}) -
Tried to handle is_active=False accounts differently with simple jwt authetication but couldn't get it to work - Django Rest
I was trying to get a different error and handle the inActive accounts differently. I tried to use an answer from here https://github.com/jazzband/djangorestframework-simplejwt/issues/368 but I am still getting the same error 401 for inactive or is_active=False accounts. Below is my code custom serializer class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) # Add custom claims token['is_active'] = user.is_active token['is_teacher'] = user.is_teacher token['is_student'] = user.is_student token['is_superuser'] = user.is_superuser token['is_staff'] = user.is_staff return token def validate(self, attrs): data = super().validate(attrs) if not self.user.is_active: raise InActiveUser() token = self.get_token(self.user) data['refresh'] = str(token) data['access'] = str(token.access_token) if api_settings.UPDATE_LAST_LOGIN: update_last_login(None, self.user) return data custom view class CustomTokenObtainPairView(TokenObtainPairView): serializer_class = CustomTokenObtainPairSerializer def post(self, request, *args, **kwargs): print(f'\nCustomTokenObtainPairView is being called\n') serializer = self.get_serializer(data=request.data) try: serializer.is_valid(raise_exception=True) print(f'\nthis is the validated data {serializer.validated_data}\n') except AuthenticationFailed: print('is active exception raised') raise InActiveUser() except TokenError: print(f'token error raised') raise InvalidToken() return Response(serializer.validated_data, status=status.HTTP_200_OK) account/custom_authentication.py def custom_user_authentication_rule(user): print('custom authentication rule has been applied') return True if user is not None else False simple jwt settings in settings.py SIMPLE_JWT = { 'USER_AUTHENTICATION_RULE': 'account.custom_authentication.custom_user_authentication_rule', } Please suggest to me what should I do and correct me wherever I am wrong. -
How to create multiple dropdown of all my model
how to create an alphanumeric that picks first initial letter of model name and generate for every user that signup firstname = models.CharField(max_length=20) lastname = models.CharField(max_length=20) i want to create something like this firstname = Seung lastname = Jo this will be the alphanumeric generated = SJ000001 -
Page not found (404) Request Method: POST
I have stucked in this error for a few days can't able to find where the mistake is i tried my level best to clear the error but cant able to do it. views section from django.shortcuts import render,redirect from django.contrib.auth.models import User,auth # Create your views here. def register(request): if(request.method=='POST'): username=request.POST['username'] password1=request.POST['password1'] password2=request.POST['password2'] user=User.objects.create_user(username=username,password=password1) user.save(); print("user created") return redirect('/') else: return render(request,'registration.html') urls.py section from django.urls import path from . import views urlpatterns=[path('register/',views.register,name="register")] html section <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Registration</title> </head> <body> <form action="register" method="POST"> {% csrf_token %} USERNAME <input type="text" name="username" id=""> <br><br> PASSWORD <input type="password" name="password1" id=""> <br><br> RETYPE PASSWORD <input type="password" name="password2" id=""> <br><br> <input type="submit" value=""> </form> </body> </html> -
raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch in Django
I have this view that allows me to delete data. But the I keep getting the this error below whenever I click on the delete button. what I want to archive is when a user clicks the on GUARDAR, that model data should be deleted. But I keep getting the NoReverseMatch error bellow raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'book_delete' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<pk>[0-9]+)/delete/$'] View.py def book_delete(request, pk): envío = get_object_or_404(Control, pk=pk) data = dict() if request.method == 'POST': envío.delete() data['form_is_valid'] = True envíos = Control.objects.all().order_by('-fecha') data['html_book_list'] = render_to_string('includes/partial_envio_list.html', { 'envíos': envíos }) else: context = {'envío': envío} data['html_form'] = render_to_string('includes/partial_envío_delete.html', context, request=request) return JsonReson Model.py class Control(models.Model): control_id = models.AutoField(primary_key=True) cliente = models.ForeignKey(Cliente, null=True, blank=True, on_delete=models.CASCADE) familia = models.ForeignKey(Familia, null=True, blank=True, on_delete=models.CASCADE) estado = models.ForeignKey(Estado, null=True, blank=True, on_delete=models.CASCADE) fecha = models.DateField(blank=True, null=True) Fecha_desde = models.DateField(blank=True, null=True) Fecha_hasta = models.DateField(blank=True, null=True) control_id_hash = models.CharField(max_length=260, db_collation='utf8_unicode_ci') control_codigo = models.CharField(max_length=50, db_collation='utf8_unicode_ci') URL path('envío/<int:pk>/delete/', views.book_delete, name='book_delete'), template <form method="post" action="{% url 'agric:book_delete' control.pk %}" class="js-book-delete-form"> {% csrf_token %} <div class="modal-body"> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> <div class="modal-status bg-danger"></div> <div class="modal-body text-center py-4"> <h3>Are you sure?</h3> <p class="lead">Do you really want to delete envío <strong>{{ control.control_codigo }}</strong>?</p> </div> <div class="modal-footer" … -
How to update queryset field using some other dictionary in django
I have one dic and i want to update one field according to that dict. How to do that in django? -
Django ckeditor 5 upload images to Google Cloud Bucket
I am trying to use the package django-ckeditor-5 on my webapp. I am using django-storages with storages.backends.gcloud.GoogleCloudStorage backend. I have set these settings: CKEDITOR5_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' CKEDITOR_5_UPLOADS_FOLDER = 'uploads/' However, when I try to upload an image, I get this error: Internal Server Error: /ckeditor5/image_upload/ Traceback (most recent call last): File "/opt/homebrew/Caskroom/miniforge/base/envs/stokk/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/opt/homebrew/Caskroom/miniforge/base/envs/stokk/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/homebrew/Caskroom/miniforge/base/envs/stokk/lib/python3.9/site-packages/django_ckeditor_5/views.py", line 54, in upload_file url = handle_uploaded_file(request.FILES["upload"]) File "/opt/homebrew/Caskroom/miniforge/base/envs/stokk/lib/python3.9/site-packages/django_ckeditor_5/views.py", line 41, in handle_uploaded_file fs = storage(location=uploads_path) File "/opt/homebrew/Caskroom/miniforge/base/envs/stokk/lib/python3.9/site-packages/storages/backends/gcloud.py", line 97, in __init__ check_location(self) File "/opt/homebrew/Caskroom/miniforge/base/envs/stokk/lib/python3.9/site-packages/storages/utils.py", line 93, in check_location if storage.location.startswith('/'): AttributeError: 'PosixPath' object has no attribute 'startswith' [04/May/2022 15:00:20] "POST /ckeditor5/image_upload/ HTTP/1.1" 500 105904 Other relevant settings: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' django-ckeditor4 worked fine, so is it a question of supporting GCB storage or am I missing something in my settings? -
Serialize JSON with a python keyword using the django-rest-framework
I have a django app (using the django-rest-framework) that needs to serialize and deserialize JSON payloads with the python keyword "import" as one of the fields. To prevent conflicts in the model, I can call the field import_flag and use the source option in the ModelSerializer. models.py class MyModel(model.Model): import_flag = models.BooleanField(verbose_name='Import') But (for obvious reasons) I cannot use the import keyword as to create a JSON field named "import" like so. serializers.py class MyModelSerializer(serializer.ModelSerializer): import = serializers.BooleanField(source='import_flag') def Meta: model = MyModel This field is present in the JSON I consume from a third-party's RESTful API and I also need to serialize it and send it back to the same third-party. Is there something like a destination option for the Django-rest-framework ModelSerializer class? I have been unable to find anything in the documentation. -
PyCharm - Error: Please enable Django support for the project
I have a django app that I have been developing on PyCharm for quite some time. I recently changed something or maybe deleted a folder, not sure what, but all of a sudden PyCharm does not recognize my app anymore. I can't edit files because it says they are "out of the project". All files are also slightly highlighted red. I can't run the server from pycharm because Error: Please enable Django support for the project And I click "Fix" I see "nothing to show" -
CITIES_LIGHT no búsqueda no funciona con acentos, ni tildes DJANGO, PYTHON
CUANDO REALIZO UN AUTOCOMPLETAR USANDO LA LIBRERIA CITIES_LIGHT NO ME APARECEN PAISES QUE TENGAN TILDES NI ACENTOS A MENOS QUE LOS ESCRIBA CON SU TILDE. Asi: enter image description here Sin embargo cuando busco con tilde si aparece: enter image description here Requiero poder buscar con o sin acento la ciudad o país correspondiente. Muchas gracias. -
Django - Filtering Post Form option by currently logged-in User's Vehicle
I'm a django newbie and i'm making a form where a User can make a Post and pick one of his Vehicles for the Post. The Vehicle and the Post models are created like so: *blog/models.py* class Post(models.Model): date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE, null=True) def get_absolute_url(self): return reverse('post-detail', kwargs ={'pk': self.pk} ) *vehicles/models.py* class Vehicle(models.Model)*: TESLA = 'TESLA' MAZDA = 'MAZDA' VOLVO = 'VOLVO' VEHICLE_CHOICES = ( (TESLA, "Tesla"), (MAZDA, "Mazda"), (VOLVO, "Volvo"), ) owner = models.ForeignKey(User, on_delete=models.CASCADE) model = models.CharField(max_length=9, choices=VEHICLE_CHOICES, default=TESLA) def __str__(self): return self.model My blog views: *blog/views.py* class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = [ 'vehicle'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) I would like to filter the vehicles so that only the current logged in User's vehicles show up in the form, i've tried a variety of different solutions but I seem to be going around in circles, if you could help me out that would be awesome. Thanks! -
How to update a single field in django?
How do I update a single field in django using html template? I have an html page to add records. I need to make an html page only to update a single field of the model. How do I do that. And what should be the view function for it. -
Change saved filepath in a django celery task
I have a model named Flights class Flights(models.Model): field = models.ForeignKey(Field, on_delete=models.CASCADE) datetime = models.DateTimeField(blank=True, null=True, default=timezone.now()) nir = models.FileField(upload_to = user_directory_path_flights, null=True, blank=True) red = models.FileField(upload_to = user_directory_path_flights, null=True, blank=True) rededge = models.FileField(upload_to = user_directory_path_flights, null=True, blank=True) green = models.FileField(upload_to = user_directory_path_flights, null=True, blank=True) User uploads some files and through a celery task i get those files and edit them into new ones. After that though they are saved at src folder when i want to save them at src/media/flights/username How do i do that ? Should i change the Flights model and add a filepath or something? And how so? celery task : @shared_task(bind=True) def get_Flights_Data(self,flight_id): identifier = Flights.objects.get(pk=flight_id) redF = identifier.red nirF = identifier.nir rededgeF = identifier.rededge print('Analyzing Flight') red = Image.open(redF) nir = Image.open(nirF) rededge = Image.open(rededgeF) ............... -
Django unable to load svg file in external js file using static reference
I need to load a svg file from my javascript code which I am including in my index.html. I understanding that jinja template cannot be used inside a js external file. And so as a workaround I am storing the same in my whiteLogo and logo variable which I am using in the js code. But when I am running the server and on scrolling on the page I am getting error, that the resource cannot be found. Not Found: /[object HTMLImageElement] [04/May/2022 12:18:05] "GET /[object%20HTMLImageElement] HTTP/1.1" 404 2441 Where am I going wrong, am I loading the logo path correctly? index.html <script type="text/javascript"> var whiteLogo = "{% static "app/images/logo/white-logo.svg" %}"; var logo = "{% static "app/images/logo/logo.svg" %}"; </script> <script src="{% static 'app/js/main.js' %}">></script> main.js window.onscroll = function () { var header_navbar = document.querySelector(".navbar-area"); var sticky = header_navbar.offsetTop; var logo = document.querySelector('.navbar-brand img') if (window.pageYOffset > sticky) { header_navbar.classList.add("sticky"); logo.src = logo; } else { header_navbar.classList.remove("sticky"); logo.src = whiteLogo; } // show or hide the back-top-top button var backToTo = document.querySelector(".scroll-top"); if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) { backToTo.style.display = "flex"; } else { backToTo.style.display = "none"; } }; -
Google Authenticaon in Django and React
Using django-allauth I've enabled google authentication on backend. I can sign in to my Django project and everything. Now, I want to connect that authentication with my React frontend, so I can login/register using google on http://127.0.0.1:3000. What do I need to do? -
Range slider value used in django for advanced search
I have a question. I am attempting to make a multi-value search bar but am having errors having it complete the search. Aim: To be able to search using integer values for people, data, Calls, Messages, and text input. The error being received: MultiValueDictKeyError at /find 'people' Request Method: POST Request URL: http://127.0.0.1:8000/find Django Version: 4.0.3 Exception Type: MultiValueDictKeyError Exception Value: 'people' Exception Location: C:\Python310\lib\site-packages\django\utils\datastructures.py, line 86, in getitem Python Executable: C:\Python310\python.exe Python Version: 3.10.4 ''' Python Path: ['C:\Users\TOSHIBA\Documents\django_projects\Daniskapp\Daniskapp', 'C:\Python310\python310.zip', 'C:\Python310\DLLs', 'C:\Python310\lib', 'C:\Python310', 'C:\Python310\lib\site-packages'] Server time: Wed, 04 May 2022 11:46:59 +0000 ''' Views.py file: def find(request): if request.method=="POST": searched = request.POST['searched'] people = request.POST['people'] SearchData = request.POST['Data'] SearchCalls = request.POST['calls'] SearchMessages = request.POST['demo'] results = informationBase.objects.filter(title__contains=searched,People=people,Data__lte=SearchData,Calls__lte=SearchCalls,Messages__lte=SearchMessages) return render(request,'finder.html', {'results': results}) ''' ''' Model : ''' ''' class informationBase(models.Model): title = models.CharField(max_length=200) People = models.IntegerField() Data = models.IntegerField() Calls = models.IntegerField() Messages = models.IntegerField() body = models.CharField(max_length=100000000) created_at = models.DateTimeField(default =datetime.now(), blank= True)