Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Open local drives in browser using django?
I want to open a local drives in browser using django For example I am developing an API to download .mp3 files and I want to access them to local drive and getting the file I want to download. I do this but it does nothing <a href="file:///C:\Users\Diaa\Desktop\ITTechWebsite\ittech\media\api\readers">Reader</a> Please help me doing this. -
paginator function not working in django?
My issue is that i want to retrieve only 6 objects per page but its showing all 10 per page my view def home(request): if request.method == 'GET': entry = Entry.objects.all().order_by('date_added') # top_rated = Entry.objects.annotate( # no_of_likes=Count('likes')).order_by('-no_of_likes')[:2] pages = Paginator(entry, 6) if request.GET.get('page'): print('executed') page_num = request.GET.get('page') pages = pages.page(page_num) entries = pages.object_list print(len(entries)) return render(request, 'base/base.html', {'entries': entries, 'pages': pages}) -
Django create view with parent model and child information
I am a beginner with Django and feel I have a fundamental misunderstanding of how to use context dictionaries. I am trying to make a function list view where it displays a list of parent models(projects) and under each project it displays the child models(stages).NOTE: I am creating a function list view rather than using a generic list view so I can include more logic such as booting those that aren't staff. I would like the list to look like: Project A Stage A(For Project A only) Stage B(For Project A only) Project B Stage B(For Project B only) My current code prints all stages in the database for each Project even if it is not the right one, but i also tried {% for stage in project.stages %} and got an error. Here are my models class Project(models.Model): name = models.CharField(max_length=70, null=False, blank=False) completion_date = models.DateTimeField(verbose_name="completion_date", null=True,blank=True ) class Stage(models.Model): DESIGN = "DESIGN" QUOTE = "QUOTE" DEPOSIT = "DEPOSIT" SCREENSHARE = "SCREENSHARE" DIGITAL_PROOF = "DIGITAL_PROOF" SAMPLE_PRODUCTION = "SAMPLE_PRODUCTION" WHOLESALE_PRODUCTION = "WHOLESALE_PRODUCTION" SHIPPING = "SHIPPING" STAGE_TYPE_CHOICES=[ (DESIGN,'Design'), (QUOTE,'Quote'), (DEPOSIT,'Deposit'), (SCREENSHARE,'Screenshare'), (DIGITAL_PROOF,"Digital Proof"), (SAMPLE_PRODUCTION,"Sample Production"), (WHOLESALE_PRODUCTION,"Wholesale Production"), (SHIPPING,"Shipping") ] project=models.ForeignKey(Project, related_name="stages", on_delete=models.CASCADE) type = models.CharField(max_length=30, choices=STAGE_TYPE_CHOICES,) completion_date = models.DateTimeField(verbose_name="completion_date", null=True,blank=True ) … -
mocking getattr function input
this is my test @tag("third_party","mock") @patch("layers.api.serializers.import_from_service.get_wms_store_layers") def test_validate_and_publish_WMS_service_layer_serializer(self, mock_wms): mock_wms.return_value = ["some_layer","some_other_layer"] bar = foo(id=4) self.assertEqual(bar,["some_layer","some_other_layer"]) and this is my sample code from geos.helpers import stores def foo(id): ows_profile = OWSProfile.objects.get(id=id) valid_layers = getattr(stores, f'get_{ows_profile.type}_store_layers')(username=ows_profile.username,password=ows_profile.password,url=ows_profile.url) return valid_layers but I got this error AttributeError: <module 'layers.api.serializers.import_from_service' from '/home/sajjad/app/sajjad/layers/api/serializers/import_from_service.py'> does not have the attribute 'get_wms_store_layers' how to fix this Thanks -
403 Forbidden Error When Editing a Form - Javascript and Django
I'm trying to use a form to edit a previous post on my site. After clicking edit, using Javascript, I'd like this to happen without requiring a reload of the page. I'm using Django and trying to use fetch in the Javascript file but I'm pretty lost as to why it's not working. I've been having a lot of trouble with saving things to the database, but also using Javascript at the same time. Any help is appreciated. When I click edit and try to save, I get 403 forbidden error. relevant urls.py - I tried this with edit_post/ and it still didn't work: path('edit_post', views.edit_post), javascript: edit = document.querySelectorAll(".edit"); edit.forEach((element) => { element.addEventListener("click", () => { edit_handeler(element); }); }); function edit_post(id, text) { form = new FormData(); form.append("id", id); form.append("text", text.trim()); fetch("edit_post", { method: "POST", body: form, }).then((res) => { document.querySelector(`#post-content-${id}`).textContent = text; document.querySelector(`#post-content-${id}`).style.display = "block"; document.querySelector(`#post-edit-${id}`).style.display = "none"; document.querySelector(`#post-edit-${id}`).value = text.trim(); }); } function edit_handeler(element) { id = element.getAttribute("data-id"); edit_btn = document.querySelector(`#edit-btn-${id}`); if (edit_btn.textContent == "Edit") { document.querySelector(`#post-content-${id}`).style.display = "none"; document.querySelector(`#post-edit-${id}`).style.display = "block"; edit_btn.textContent = "Save"; edit_btn.setAttribute("class", "text-success edit"); } else if (edit_btn.textContent == "Save") { edit_post(id, document.querySelector(`#post-edit-${id}`).value); //here edit_btn.textContent = "Edit"; edit_btn.setAttribute("class", "text-primary edit"); } } views.py … -
Vim as an IDE for Django. Is it possible to?
If anyone configured vim configuring to this instruction, share the .vimrc config. I will also be glad to see your options for configuring Vim as IDE for Django. -
Django restframework unique error not processed
When I fill in the necessary fields, Django will return a message to the client, but when the field is unique, there will be an error message. Why didn't Django handle it? models.py class UserModel(models.Model): email = models.EmailField(unique=True) username = models.CharField(max_length=16, blank=True, null=True) password = models.CharField(max_length=512) is_active = models.BooleanField(default=False) sign_up_date = models.DateTimeField(auto_now_add=True) sign_in_date = models.DateTimeField(null=True, blank=True) serializers.py class UserSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) email = serializers.EmailField() username = serializers.CharField(max_length=16) password = serializers.CharField(max_length=512) is_active = serializers.BooleanField(read_only=True, default=False) sign_up_date = serializers.DateTimeField(read_only=True) sign_in_date = serializers.DateTimeField(read_only=True) class Meta: model = UserModel fields = ( 'id', 'email', 'username', 'password', 'is_active', 'sign_up_date', 'sign_in_date',) views.py class SignupView(CreateAPIView): serializer_class = UserSerializer queryset = UserModel.objects.all() error IntegrityError at /api/signup/ duplicate key value violates unique constraint "User_email_key" DETAIL: Key (email)=(test@gmail.com) already exists. -
Django creating a route that takes the last part of the URL as parameter for a view?
For example: I would like: http://localhost:8000/computers/laptops/ To return the same as: http://localhost:8000/computers/?c=laptops What would be the best way to do it? -
Rendering Django Templates using Python Dictionaries
How do I use a python dictionary to automatically render multiple html templates in Django? Each button in picture 1 should create an output similar to picture 2. Picture 1 Picture 2 This is the code I have written in views.py and it has been linked in urls.py: class RandomView(TemplateView): template_name = "random.html" def dict_lookup(request): dic = ({ "Linkam": ["Optical spectra vs Temperature", "Reflectance vs Temperature", "Video of crystallisation (formed by composing images)"], "Vector Network Analyser (VNA)": ["Permittivity", "Permeability"], "Four Point Probe": ["Resistivity", "Resistivity vs temperature"], "Static Tester (Optics Lab)": ["Switching times (Reflectivity vs Time and Power)"], "Transient Grating Spectrometer": ["Elastic Tensor", "Thermal diffusivity"], "Raman Microscope": ["Intensity vs Energy", "Intensity vs Frequency"], "Perkin Elmer Spectrometer": ["Reflectivity vs wavelength","Transmissivity vs wavelength"], "Scanning Electron Microscope":["Images"], "SEM - Energy dispersive X-ray Analysis (EDX)" : ["Fluorescent intensity vs energy"], "SEM - Electron Backscattering diffraction (EBS)": ["?"], "X-ray Diffractometers": ["Intensity vs angle", "X-ray reflectivity (thickness, density, roughness)"], "Ellipsometer": ["Refractive index vs wavelength"], "Atomic Force Microscope (AFM)": ["Thickness vs length", "Map of roughness"] }) return render(request, "random.html", dic) This is the code written in random.html under templates: {% for key, value_list in dic.items %} {% for value in value_list %} <div class ="row pt-3"> <button type="button" … -
GCP: connect to Memotystore from cloud run Django app?
I'd like to add cache to my Django app hosting on Cloud Run. From Django official docs, we can connect Django to a memory-based cache. Since I'm using Cloud Run, the memory get cleaned. Memotystore seems good for this purpose, but there's only tutorial for flask and redis. How could I achieve this? Only should I just use a database caching? -
Django how to write query for get current logged in user email?
I have abstract user model. I am using this queryset for getting current logged in user username. currentuser_username = UserManagement.objects.filter(username=request.user) my terminal result: I am not understanding how to write queryset for get current user email. If I don't know the username of current user then I can write this queryset currentuser_username = UserManagement.objects.filter(username=request.user) and it will give me the username of current user. How to apply same method for getting mail for current user??? here my models.py class UserManagement(AbstractUser): is_blog_author = models.BooleanField(default=False) is_editor = models.BooleanField(default=False) is_subscriber = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) -
django with celery error:No result backend is configured
my version: Django==3.2 celery==5.1.2 my settings.local: CELERY_RESULT_BACKEND = 'redis://@127.0.0.1:6379/1' celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings # # 设置环境变量 os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cmdb.settings.local') # 实例化 # app = Celery('celeryPro', include=['message.tasks']) app = Celery('celeryPro', backend='redis://127.0.0.1:6379/1') # app = Celery('cmdb') # namespace='CELERY'作用是允许你在Django配置文件中对Celery进行配置 # 但所有Celery配置项必须以CELERY开头,防止冲突 app.config_from_object('django.conf:settings', namespace='CELERY') # app.config_from_object(config, namespace='CELERY') # 自动从Django的已注册app中发现任务 app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request:{0!r}'.format(self.request)) always get the error -
Django Restframework database error message handling
I want to send the error message to Drf to help me deal with it and return it to the client. But i don't know what to do views.py class SignupView(CreateAPIView): serializer_class = UserSerializer queryset = UserModel.objects.all() def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) password = self.request.data.get('password') # I hope try can be handled by Drf try: serializer.save(password=make_password(password=password)) except IntegrityError as error: key, msg = str(error).split('Key (')[1].split(')')[0], str(error).split(')=(')[1].split(') ')[1].strip() print(key, msg, {key: msg}) return Response({key: msg}) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) But if I can, I hope Drf can handle it for me. -
How to rename file in django which uses custom storage?
I am using a custom django storage class (digitalocean spaces), which behind the hood uses S3. I have some code which uses "os.rename". Django provides a utility called default_storage through which we can use some of os module's features in remote storage. However, it doesn't have the ability to rename/move/copy a file. I am doing a lot of file operations in the backend using os module. However, in production, the file storage system would be digitalocean spaces. Which means I can't do file operations using os module, I have to use django's default storage utility which doesn't provide all features of os module. Will my code still work in a remote storage or will it fail? If it will fail, then how can I solve it? -
How to change to BooleanField after True to False every month in Django?
Info: When i create a new customer i want to make pending_customer True which i set with Default value True so it's working fine and after the month the pending_customer make to false automatically. I also try to make function get_pending_customer who could do it i know this is not the way to what i want to do. It's like a task based funcion which is automatically make pending_customer field True to false after the month. i want to know how can I do this? Can anyone tell me what is the best way to do this? models.py class Customer(models.Model): """Customer Model""" name = models.CharField(max_length=255) phone = models.CharField(max_length=11) created_on = models.DateTimeField(auto_now_add=True) pending_customer = models.BooleanField(default=True) """Example""" # I know it's wrong way def get_pending_customer(self): today = self.created_on month = 30 # days after_month = month - today if after_month: panding = self.object panding.pending_payment = False panding.save() return today -
I was trying to run the uwsgi and supervisor but it's not working properly
Here is the configuration file for supervisor command=/home/ubuntu/.local/bin/uwsgi --ini /home/ubuntu/socialtalks/config/uwsgi.ini directory=/home/ubuntu/socialtalks startsecs=0 autostart=true autorestart=true stderr_logfile=/var/log/socialtalks.err.log stdout_logfile=/var/log/socialtalks.out.log When i reloaded this file using sudo service supervisor reload It's reloading and running. Here is the out put. sudo supervisorctl status socialtalks socialtalks RUNNING pid 8639, uptime 0:00:00 But, it's not starting the server on boot and when i checked the log file it's shwoing errors. Here is error log. *** Starting uWSGI 2.0.19.1 (64bit) on [Wed Jul 28 01:52:32 2021] *** compiled with version: 7.5.0 on 02 January 2021 08:22:31 os: Linux-5.4.0-1054-aws #57~18.04.1-Ubuntu SMP Thu Jul 15 03:21:36 UTC 2021 nodename: ip-172-31-2-189 machine: x86_64 clock source: unix detected number of CPU cores: 1 current working directory: /home/ubuntu/socialtalks detected binary path: /home/ubuntu/.local/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! setgid() to 33 setuid() to 33 chdir() to /home/ubuntu/socialtalks your processes number limit is 3800 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) error removing unix socket, unlink(): Operation not permitted [core/socket.c line 198] bind(): Address already in use [core/socket.c line 230] [uWSGI] getting INI configuration from /home/ubuntu/socialtalks/config/uwsgi.ini open("./python37_plugin.so"): No such file … -
Python Request inside Django View stop request when client gets disconnected
I have an DRF API in which a client will call then once called it will pass the data from client to another server (using request package) and returns to client the response of the other server. In short, I am an API in the middle to sync them. Now, I need to terminate the request to other server (the one that is using request package) from my DRF API once the client got disconnected to my DRF API. Note. I need to terminate it because the data sending from the client is need to be map by the id being returned from the other server, and the client needs to save the id they received. In case your wondering why my API exist, the client can just sent the request over to the other server directly. Because the other server is a legacy server and it runs SOAP so my API is converting the JSON payloads to SOAP payload then from SOAP payload to JSON payload. -
How to refresh view.py in Django when clicking form checkbox and passing checkbox boolean?
Hello I'm trying to refresh my webpage when clicking a form checkbox and passing the checkbox boolean to the view.py. I'm trying to accomplish this using Ajax, but this is the first time using Ajax and I honestly have no idea if its working correctly. HTML and AJAX: <script type="text/javascript"> $("check_legend").click(function(){ var form_data = $("form_legend").serialize(); $.ajax({ url: '{% url 'post_form_api' %}', type: "POST", dataType: "json", data: form_data, cache: false }).done(function(data) { if (data.result === true){ alert(data.message); } }); }); </script> <div class="row"> <div class="col-sm-10"> {{ map|safe }} </div> <div class="col-sm-2"> <form method="post" id="form_legend"> <h3><span style="color: #e8c4b4;">Places</span></h3> <div class="form-check"> <input type="checkbox" class="form-check-input" id="check_legend" name="cities"> <label class="form-check-label" for="check_legend">Cities</label> </div> </form> </div> </div> This is in my url.py if it's of any use: path('api/post_form/', post_form_api, name="post_form_api") and my view.py goes as follows for the ajax response: from django.views.decorators.csrf import csrf_exempt @csrf_exempt def post_form_api(request): data = {} if request.method == "POST" and request.POST.get('cities', None) is not None: form_field1 = request.POST.get('cities') # save the form data and indicate success data['result'] = True data['message'] = "Form saved successfully" ... if request.is_ajax(): return JsonResponse(data) else: return HttpResponseBadRequest() In a different part of the view.py where I get give values to the webpage I handle the POST request … -
Using Git?? : how to update my Django website I deployed by DigitalOcean
my gorgeous friends on the Internet. A week ago, I deployed my first Django website on the Internet. Now, I have made some updates in the local environment (I cloned the website from GitHub and did coding in VSCode). Once I deployed it a week ago, the environment was Django, Postgresql, Nginx, Gunicorn, and DigitalOcean as a VPS. I am wondering that all I have to do is to command 'git pull' or 'git clone' here (I put a picture of the terminal. If just commanding 'git pull', let me know I am correct. Thanks for your time. -
Override the third party view for end-point
I am using Django-rest-framework-social-oauth2 , convert-token endpoint. This endpoints returns json as following { "access_token": "************", "token_type": "Bearer", "expires_in": 36000, "refresh_token": "************", "scope": "read write" } Now I want to add user id or deta of user model(like name ,email,etc,,) to this json. So I want to override the this view,maybe class ConvertTokenView in this code. How can I do this?? class ConvertTokenView(CsrfExemptMixin, OAuthLibMixin, APIView): """ Implements an endpoint to convert a provider token to an access token The endpoint is used in the following flows: * Authorization code * Client credentials """ server_class = SocialTokenServer validator_class = oauth2_settings.OAUTH2_VALIDATOR_CLASS oauthlib_backend_class = KeepRequestCore permission_classes = (permissions.AllowAny,) def post(self, request, *args, **kwargs): # Use the rest framework `.data` to fake the post body of the django request. mutable_data = request.data.copy() request._request.POST = request._request.POST.copy() for key, value in mutable_data.items(): request._request.POST[key] = value url, headers, body, status = self.create_token_response(request._request) response = Response(data=json.loads(body), status=status) for k, v in headers.items(): response[k] = v return response -
Ajax GET request returns current HTML page
Hi Im building Django first project. I use ajax to update product when user inputs keyword This is my HTML: <form id="productform" method="GET">{% csrf_token %} <label>Producto:</label> <div class="input-group"> <span class="input-group-label"><i class="fi-magnifying-glass"></i></span> <input type="text" class="input-group-field" placeholder="Buscar.." id="keyprod" name="keyprod"> </div> </form> When submitting form this is my JS: $("#productform").submit(function (e) { e.preventDefault(); var keyprod = $("#keyprod").val(); $.ajax({ type: 'GET', url: "ajax_get_products", data: {"keyprod": keyprod}, success: function (response) { var sel = $("#productselect"); sel.empty(); console.log(response) for (var p in response) { sel.append('<option value="' + response[p]["id"] + '">' + response[p]["full_name"] + '</option>'); } }, error: function (response) { console.log(response) } }) }) This is my urls file: app_name = "sales_app" urlpatterns = [ path( 'sales/register/', views.LoadCurrentSaleInfo.as_view(), name='sale-register', ), path( 'sales/register/<str:new>', views.LoadCurrentSaleInfo.as_view(), name='sale-register', ), path('sales/register/ajax_get_products', ajax_get_products, name="ajax_get_products"), ] And finally this is the code in my view: def ajax_get_products(request): print("Im in ajax request") --> This is never shown if request.is_ajax and request.method == "GET": keyprod = request.GET.get("keyprod", None) products = Product.objects.search_key_word(keyprod, 'name') serializer = ProductSerializer(products, many=True) return JsonResponse(serializer.data, safe=False, status=200) return JsonResponse({}, status=400) When I print the response in the console in my JS method, the current html page in which the form is being submitted is printed. What am I doing wrong any ideas? … -
I want to fetch all subcategories based on my parent ID category. Using Django/Vuejs. More info bellow
I'm trying to fetch subcategories from api, based on PAREND ID, using Vue and Django So, I have 2 categories: Phone Brands Phone Models Example: Category: Sony, id:1 Related subcategory: XZ3, XZ2, XZ... Category: Samsung, id:2 Related subcategory: S10, S9, S8... So when the user click on 'Sony, id:1' category(), I want all data based on that Category(parent)ID to be displayed on the screen(inside component). What is happening now, when I pass ID from parent to child component, response returns only 1 objects, that matches ID which I get from parent ID. Like, Sony(parent category) have ID:1, XZ3 (child category)have ID:1 too, so it show only matched ID inside component, nothing else DJANGO views.py: from rest_framework import serializers from . models import Specs, Models, Brands from django.shortcuts import render from rest_framework.decorators import api_view from rest_framework.response import Response from . serializers import ModelsSerializer, SpecsSerializer, BrandsSerializer # Create your views here. @api_view(['GET']) def BrandsView(request): brand = Brands.objects.all() serializer = BrandsSerializer(brand, many=True) return Response(serializer.data) @api_view(['GET']) def ModelsView(request, pk): model = Models.objects.get(pk=pk) serializer = ModelsSerializer(model, many=False) return Response(serializer.data) @api_view(['GET']) def SpecsView(request, pk): specs = Specs.objects.get(pk=pk) serializer = SpecsSerializer(specs, many=False) return Response(serializer.data) urls.py: from django.urls import path from . import views urlpatterns = [ path('', … -
Django log errors and traceback in file in production environment
I'm quite new working with logging in django, I'm making a production deployment (DEBUG=False) of an app but I'm not allowed to use any error tracker like Sentry to catch possible problems, so I was wondering if it's possible to log the traceback or part of it in production environment to a file using a logger. I made something like this in my production settings: import logging.config # Clear prev config LOGGING_CONFIG = None # Get loglevel from env LOGLEVEL = os.getenv('DJANGO_LOGLEVEL', 'debug').upper() logging.config.dictConfig( { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'level': 'INFO', 'filters': ['require_debug_false'], 'class': 'logging.StreamHandler', }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'debug.log', }, }, 'loggers': { "": { "level": "ERROR", "handlers": ["console", "file"], }, 'django': { 'handlers': ['console', 'file'], 'level': 'DEBUG', 'propagate': True, }, 'django.request': { 'handlers': ['console', 'file'], 'propagate': True, 'level': 'ERROR', }, } } ) But the only thing I got on debug.log is: Internal Server Error: /job/create/ Internal Server Error: /job/create/ Internal Server Error: /job/create/ Logs to file without any other information, I would like to have some meaningful information in debug.log to have a clue where can … -
How use brackets django apps?
Heey, I have a problem, probably very simple and i have one ask. How i can use a '{{ }}' in other my apps? for example: enter code here def show_profile_info(request) new_user = Profile.objecs.all().order_by('-id')[:1] context = { 'new_user': new_user return render(request, 'urprofile.html' context) This views is in in app with name "Profile" In Profile this is easy, but i dont have idea how i can do this is "Post" app or other Anyone can give me a small hint? -
Django user groups selector
I'm new in Django and I'm facing this problem. I have created a custom user model and afther that I'm not able to set the user groups in the create/change form of the admin panel. This is my user class class User(AbstractUser): class UserRole(models.TextChoices): ADMIN = "ADMIN", "Administrador" MANAGER = "MANAGER", "Manager" HUNTER = "HUNTER", "Hunter" NONE = "NONE", "Sin especificar" # override first_name = models.CharField(_('first name'), max_length=150, blank=False) last_name = models.CharField(_('last name'), max_length=150, blank=False) email = models.EmailField(_('email address'), blank=False) # new fields role = models.CharField( max_length=50, choices=UserRole.choices, default=UserRole.NONE, verbose_name="Rol" ) And this is my users admin class in admin.py class UserAdmin(admin.ModelAdmin): list_display = ('username', 'first_name', 'last_name') search_fields = ('username', 'first_name', 'last_name') fieldsets = ( ("Datos personales", {'fields': ('username', 'first_name', 'last_name', 'email')}), ('Permisos', {'fields': ('role', 'is_active', 'is_superuser', 'is_staff', 'groups')}), ) And this is what I'm getting enter image description here Instead of this, that is what I want to get enter image description here I need someone to light my way, thanks!