Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error : no command namde "listener" when trying to install "django-tracking"
while Trying to install 'django-tracking' library with pip, easy install and get Using mobile android .. JuiceSSH app on Android.. Latest version of Django(4.1.7), pip3, and python (3.9) Debian server and Apache web server. Hello guys, i am almost new to django and i am working on some demo website, i want to track the visitors number, where they come from, and other things, so i tried to use 'django-tracking' library.. This error is appear to me when i run the command: Pip install django-tracking enter image description here It seems that the error appears twice, then it install 'django-tracking' version 0.2 Then i tried this: pip install git+https://github.com/bashu/django-tracking.git I got the same issue: enter image description here When i run : ` pip freez ` enter image description here The listiner is installed but no thing called listeners with S .. Same issue with easy_install django-tracking Note that i use mobile android to do everything and the error is on web server Apache.. I want solution please... Thanks.. -
Populating Django model field from another model field value
I added a something like this class Inventory(models.Model): quantity = models.PositiveBigIntegerField(default=0) def __str__(self): return str(self.quantity) and Product model class Product(models.Model): title = models.CharField(max_length=20) inventory = models.OneToOneField(Inventory,on_delete=models.CASCADE) @property def stock(self): if self.inventory: return self.inventory.quantity else: return 0 So now for stock to be populated it will check the inventory model But I have concerns regarding the performance of this way. When i look for product.stock Is it the right approach ? What would happen if i get 1000s of products ? What's the better way to do this considering performance and scalability ? I am also open to idea for re-creating the model architecture if no other way found. Hope you will guide me right way.. Looking forward for your reply. Thanks & Regards Manish -
Python Django, how to connect to database ssh tunneling
What settings I need to connect django app with ssh tunnel for my database, Connection is working fine when I create a standalone python file. I am using mysql for database connection -
I can't access to django admin panel after integrate django-keycloak to my project
I'm still learning about django and Keycloak for authentication, and I'm following the documentation https://django-keycloak.readthedocs.io/en/latest/ 1- I did the initial setup 2- I Setup for remote user 3- I did the migrations but when i try to access to Admin panel to do the server configuration it shows me the next error: Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive Even I'm sure about the username and the password and I created that using the next command: python manage.py createsuperuser This is my code is simple I just want to see how the django-keycloak works: models.py from django.db import models # Create your models here. class Info(models.Model): title= models.CharField(max_length=50) Settings.py INSTALLED_APPS = [ 'pages.apps.PagesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_keycloak.apps.KeycloakAppConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_keycloak.middleware.BaseKeycloakMiddleware', 'django_keycloak.middleware.BaseKeycloakMiddleware', 'django_keycloak.middleware.RemoteUserAuthenticationMiddleware', ] AUTHENTICATION_BACKENDS = [ 'django_keycloak.auth.backends.KeycloakAuthorizationCodeBackend', ] LOGIN_URL = 'keycloak_login' KEYCLOAK_OIDC_PROFILE_MODEL = 'django_keycloak.RemoteUserOpenIdConnectProfile' Does anyone have any idea about this problem, thank you in advance -
Django project with various apps how is top level models?
settings.py # Application definition INSTALLED_APPS = [ 'food', 'nursing', 'shopping', 'stay', 'tourism', 'transportation', 'treatment', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] There is a specific model in each 7 applications models.py. How is creating master top level of that may in project folder to inheriting with applications specific model? (How all project's applications inherit from an overall model with common fields?) I have tried: inner_project_directory/ --_pycache__ --_init__.py --app.py --asgi.py --models.py --settings.py # I have created top master level in project folder --urls.py Encountered with: raise RuntimeError( RuntimeError: Model class projectfolder.models.User doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. What is the right approach for implementing top level model with most common fields which is inheriting in project applications? -
Use two instances of the same model for foreignkeys on the same model in Django
I need to be able to store two ManyToManyFields referring two account model objects. acctId_from should refer to the account object that the transaction was from, acctId_to should refer to the account object that the transaction was sent to. This is how I'm doing it: class transaction(models.Model): id = models.AutoField(primary_key=True) acctId_from = models.ManyToManyField(account, related_name="acctfrom") acctId_to = models.ManyToManyField(account, related_name="acctto") amount = models.DecimalField(max_digits=10, decimal_places=2) I have also tried using plain ForeignKeys which also returned the same error. I am using related names but I'm not sure why I'm still getting this error: login.transaction.account_from: (fields.E304) Reverse accessor 'account.transaction' for 'login.transaction.account_from' clashes with reverse accessor for 'login.transaction.account_to'. -
how do i save a user to a database in DJANGO using request.method == 'POST'?
i have an issue where iwant to register a user my request method POST doesn't save a user to my database... let me give you a clear context on what iwant to achieve: i have a role based sign up for a jobseeker and a recruiter, so now iwant to show different pages to each user based on the role they picked when they were registering.... : my role.html template: {% extends 'core/base.html' %} {% block title %}Choose A Role{% endblock %} {% block content %} <div class="flex flex-col justify-center items-center"> <div class="w-full max-w-md"> <h1 class="text-3xl font-bold mb-4 text-center">Register by your role</h1> <p class="text-center">Choose the right role for you to enter our site</p> <form method="post" action="{% url 'core:role' %}" class="bg-amber-100 grid grid-cols-2 gap-2 w-full max-w-screen-sm"> {% csrf_token %} <div class="flex items-center"> <input type="radio" id="jobseeker1" name="role" value="jobseeker"> <label class="w-full px-6 py-8 rounded-lg shadow-md bg-white border-2 border-blue-500 hover:bg-blue-500 hover:text-white cursor-pointer transition-colors duration-300" for="jobseeker1"> <span class="text-xl font-bold uppercase">I'm a Jobseeker</span> <ul class="text-sm mt-2"> <li> i want to apply for jobs </li> </ul> </label> </div> <div class="flex items-center"> <input type="radio" id="recruiter2" name="role" value="recruiter"> <label class="w-full px-6 py-8 rounded-lg shadow-md bg-white border-2 border-blue-500 hover:bg-blue-500 hover:text-white cursor-pointer transition-colors duration-300" for="recruiter2"> <span class="text-xl font-bold uppercase">I'm a Recruiter</span> … -
Is It possible to make a horizontal slider form with Django?
I have searched through the Django documentation, and can't find any Field for a slider. I wish to have 8 sliders with a 5 value range. I can't find any examples of one, and don't have any experience on making custom form Fields. How would I go about doing this? Here is an image on what I mean by horizontal slider. I attempted to use javascript to handle the sliders but ran into a wall when it came to collecting and sending this data back to the view in order to update model attributes. -
Django REST API Media URL Problems
when I send a get request to a question with rest api in django. It looks like "image": "question_images/myphoto.png", But I also want the media folder to appear like "image": "media/question_images/myphoto.png", how can this be achieved? question_images located in the media folder. I configured MEDIA_URL. -
Change image upload path inside form_valid() method
I have this CreateView for an image model. class ImageCreateView(CreateView): model = Image form_class = ImageCreateForm owner = None def form_valid(self, form): self.object = form.save(commit=False) owner = self.owner.objects.get(id=self.kwargs['pk']) files = self.request.FILES.getlist('image') for f in files: file_hash = hashlib.sha256() while chunk := f.read(8192): file_hash.update(chunk) hexhash = file_hash.hexdigest() if existing := self.model.objects.filter(hashsum=hexhash): owner.images.add(existing.last()) else: f.name = '{0}_{1}/{2}'.format(str(owner._meta).split('.')[-1], owner.id, f.name) new_image = self.model.objects.create( image=f, hashsum=hexhash, user=self.request.user.profile, desc=self.object.desc, ) owner.images.add(new_image) return redirect(owner.get_absolute_url()) Is it possible to have this image instance save with new file name f.name? -
How can I save bulk images with type django.core.files.uploadedfile.InMemoryUploadedFile
I am upload Images from Postman, and receiving them as type django.core.files.uploadedfile.InMemoryUploadedFile but am getting an error. Below is my View in Django : class LiveImageBulkUploadView(generics.CreateAPIView): queryset = LiveImages.objects.all() serializer_class = LiveImagesSerializer parser_classes = [MultiPartParser] def post(self, request, *args, **kwargs): # get the relevant event based on the uuid in the URL # TODO Finish this uploading part, it should be bulk upload. event_uuid = kwargs.get('event_uuid') event = get_object_or_404(Events, uuid=event_uuid) live_images_list = [] for image in request.FILES.getlist('image'): # Open the image using PIL print(' image ', type(image)) img = Image.open(BytesIO(image.read())) live_images_list.append( LiveImages(image=img, caption='', event=event)) LiveImages.objects.bulk_create(live_images_list) return Response(status=status.HTTP_201_CREATED) My models are here : class Events(TimeStampedModel, models.Model): """Events model""" uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) name = models.CharField(_('Title'), max_length=100, blank=False, null=False) image = models.ImageField(_('Image'), upload_to='event_images', null=True, max_length=900, blank=True) is_public = models.BooleanField(_('Is public'), default=True) event_type = models.ForeignKey( EventTypes, max_length=25, related_name='events_types', null=True, blank=True, on_delete=models.CASCADE) views_count = models.BigIntegerField(_('Views count'), default=0) # TODO: Add an attribute is_live. def __str__(self): return self.name def increment_views(self): Events.objects.filter( pk=self.pk).update(views_count=F('views_count') + 1) class LiveImages(TimeStampedModel, models.Model): """LiveImages model.""" uuid = models.UUIDField(unique=True, max_length=500, default=uuid.uuid4, editable=False, db_index=True, blank=False, null=False) caption = models.CharField( _('Caption'), max_length=100, blank=True, null=True) image = models.ImageField(_('Image'), upload_to='live_images', null=True, max_length=900, blank=True) event = models.ForeignKey( Events, max_length=50, related_name='event_live_images', null=True, blank=False, … -
How to use social auth app django with React.js frontend?
I'm using Django on my backend, where I'm loging users with LinkedIn account. I've done everything following documentation, and it's working great. Now I want to use my views as API to my React.js project. How can I remake <a href="{% url 'social:begin' 'linkedin-oauth2' %}">Sign in with Linkedin</a> as React button? I found similar question Google Auth using social-auth-app-django on project(Django + React) -
Download random files from Amazon S3 with Django
I need a django app that allows users to download random PDFs from aws s3. But I want users download PDFs when they click the download button without showing actual link to Amazon. First problem is how to make link secret. Second problem is how to make it random. As I searched I seen I I need to save links in database. But I don't know if it's secure or even how to do that. -
Unable to delete a user from the admin side (IntegrityError at /admin/register/user/26/delete/) | Django Intellij
Could someone assist me in solving this issue please. I am unable to delete a user from the django admin site as the following error keeps popping up (I'm fairly new to coding as well): enter image description here these are my codes: - models.py: from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models class UserManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, password=None): if not email: raise ValueError("Users must have an email address") if not username: raise ValueError("Users must have a username") if not first_name: raise ValueError("Users must have a first name") if not last_name: raise ValueError("Users must have a last name") user = self.model( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, first_name, last_name, password): user = self.create_user( email=email, username=username, first_name=first_name, last_name=last_name, password=password, ) user.is_admin = True user.is_staff = True user.save(using=self._db) return user class User(AbstractBaseUser): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) username = models.CharField(max_length=100, unique=True) email = models.EmailField(max_length=100, unique=True) balance = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'username' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'email', 'balance'] objects = UserManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property … -
django url config - inconsistent local vs. EC2 hosted
I have a Django 2.2 application running Python 3.8.10. Trying to research and debug a confusing issue related to urls. Essentially we have /org urls: from django.conf.urls import include, url from django.urls import reverse_lazy from django.views.generic.base import RedirectView from . import views urlpatterns = [ url(r'^', include("project.urls")), url(r'^$', views.frontpage, name="frontpage"), url(r'^org/submit/$', views.org_create_new, name="org-create-new"), url(r'^org/(?P<slug>[-\w]+)$', views.org), # redirect traffic that doesn't match a url to root home url(r'^.*$', RedirectView.as_view(url=reverse_lazy('frontpage')), name='home'), ] and project urls from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), url(r'^accounts/', include('allauth.urls')), url(r'^manage/', include('management.urls')), url(r'^', include('users.urls')), url(r'^', include('common.urls')), url(r'^', include('products.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This configuration works fine locally with no issues. However, when we deploy the application (to AWS EC2) the org.urls and management.urls don't work, but the remaining urls do. Django admin can be accessed, common.urls and users.urls serve fine, but a GET request to "frontpage" view for example simply returns 404 Not Found. There's no error message. if I sh into the EC2 instance and run python manage.py show_urls I see all the urls, including the ones that are returning 404 Not Found: / orgs.views.all.frontpage … -
I am trying to save the profile_picture which came from SignupForm in my user model named UserProfile
i am trying to save the profile picture which has came from SignupForm but intead saving that file, i dont know django is always taking the default.jpg i tried but i am not able to do could you help me to get this resolve however i am trying to save all the credentials of user to the respected UserProfile once they signup, my all the credentials are saving correctly, but i dont know why only the profile_picture is not able to taken from SignupForms instead it is using default.jpg which defined in my models.py i want to save the user profile with what user choosed the image, not default one so please help me to get this issue resolve i am trying to save the profile picture which has came from SignupForm but intead saving that file, i dont know django is always taking the default.jpg i tried but i am not able to do could you help me to get this resolve forms.py of my app from django.core.files.base import ContentFile from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import UserProfile class SignupForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=True) last_name = forms.CharField(max_length=30, required=True) profile_picture = forms.ImageField(required=False, … -
How to cerate unique link for each uuid in django
I am trying to generat ethe unique link for each uuid which are into database. but getting error - 'django.core.exceptions.FieldError: Cannot resolve keyword 'slug' into field. Choices are: id' I have try below code View - def Insert_Record(request, uid): obj_uid = Get_Customer_ID.objects.get(slug=uid) or id=uid URL path('form/<str:id>/<slug:uid>', views.Insert_Record), Model - class Product(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False class Get_Customer_ID(models.Model): class Meta: db_table = "TABLE_NAME" DB - Table Format - UUID is the first column which is primary key. -
Django form data is not saved into database
When I submit my form, I get: [21/Apr/2023 10:35:01] "POST / HTTP/1.1" 200 882 but the data is not saved into the database. I think the issue is in Views.py: @requires_csrf_token def competitors(request): if request.method == "POST": form = CompetitorsReg(request.POST, request.FILES) if form.is_valid(): text = form.cleaned_data['Competitors'] form.save() else: form = CompetitorsReg() return render(request, 'forms.html') Models.py class Competitors(models.Model): flname = models.CharField(max_length=255) Weight = models.IntegerField(validators=[MinValueValidator(50), MaxValueValidator(300)]) rank = models.CharField(max_length=255) I can create and save information in the admin panel, but the information is not saved from the form. I don't receive any error message. Thanks in advance! -
How to solve an unhandled promise rejection . tailwind Css on Ubuntu
hi i am working on django and i am trying to integrate tailwind Css the version of node.js is V12.22.9 and the version of npm is 8.5.1 i have registered tailwind and theme app well in setting .py file j 've defined INTERNAL_APP but when I run the command python manage.py tailwind start I have an unhandled promise rejection . my OS IS UBUNTU since the error seemed to come from the index.js file of myapp/themes/static_src/node_modules/tailwincss/lib/cli/build I positioned myself in this directory and typed node --unhandled-rejection=strict index. js. But that did not work -
Installing Tailwind in a Django application
I have a Django application in which I want to use tailwind to style my templates. To use that module, I have followed the steps mentioned in https://django-tailwind.readthedocs.io/en/latest/installation.html In the error it is mentioned an issue with "self.npm_command("install"). I have npm installed globally though and it is working e.g, when I run npm -v. When I run the command python manage.py tailwind install here's the full traceback: ` Traceback (most recent call last): File "/Users/myuser/Desktop/project/manage.py", line 21, in <module> main() File "/Users/myuser/Desktop/project/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/myuser/Library/Caches/pypoetry/virtualenvs/project-EXN22i-9-py3.11/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/Users/myuser/Library/Caches/pypoetry/virtualenvs/project-EXN22i-9-py3.11/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/myuser/Library/Caches/pypoetry/virtualenvs/project-EXN22i-9-py3.11/lib/python3.11/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/Users/myuser/Library/Caches/pypoetry/virtualenvs/project-EXN22i-9-py3.11/lib/python3.11/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/myuser/Library/Caches/pypoetry/virtualenvs/project-EXN22i-9-py3.11/lib/python3.11/site-packages/tailwind/management/commands/tailwind.py", line 54, in handle return self.handle_labels(*labels, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/myuser/Library/Caches/pypoetry/virtualenvs/project-EXN22i-9-py3.11/lib/python3.11/site-packages/tailwind/management/commands/tailwind.py", line 62, in handle_labels getattr(self, "handle_" + labels[0].replace("-", "_") + "_command")(*labels[1:], **options) File "/Users/myuser/Library/Caches/pypoetry/virtualenvs/project-EXN22i-9-py3.11/lib/python3.11/site-packages/tailwind/management/commands/tailwind.py", line 97, in handle_install_command self.npm_command("install") File "/Users/myuser/Library/Caches/pypoetry/virtualenvs/project-EXN22i-9-py3.11/lib/python3.11/site-packages/tailwind/management/commands/tailwind.py", line 113, in npm_command self.npm.command(*args) File "/Users/myuser/Library/Caches/pypoetry/virtualenvs/project-EXN22i-9-py3.11/lib/python3.11/site-packages/tailwind/npm.py", line 24, in command subprocess.run([self.npm_bin_path] + list(args), cwd=self.cwd, check=True) File "/opt/homebrew/Cellar/python@3.11/3.11.3/Frameworks/Python.framework/Versions/3.11/lib/python3.11/subprocess.py", line 548, in run with Popen(*popenargs, **kwargs) as process: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/homebrew/Cellar/python@3.11/3.11.3/Frameworks/Python.framework/Versions/3.11/lib/python3.11/subprocess.py", line 1024, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "/opt/homebrew/Cellar/python@3.11/3.11.3/Frameworks/Python.framework/Versions/3.11/lib/python3.11/subprocess.py", line 1791, in _execute_child and os.path.dirname(executable) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ … -
How CKEditor can access get_absolute_url of the instance
everyone! I'm using CKEditor in my Django project. To upload images, it generates URLs with get_filename function, based on the request: #utils/utils.py from urllib.parse import urlparse # Будем парсить адрес def get_filename(filename, request): path = request.META.get('HTTP_REFERER', '') parsed_path = urlparse(path) filename = "/".join([parsed_path,filename]) return filename As far as I update my pages through the user interface, everything go smoth. For example, my news has an address /news/2023/04/test, so CKEditor creates a folder /static/images/news/2023/04/test, and puts images there, which is what I want. However, if I edit the same news through the admin panel, the path looks different: /admin/news/new/4/, so CKEditor creates a corresponding folder and puts images there, which is wrong. In other words, the user interface and the admin panel use different paths (and requests) to access the same pages. I'd like to use get_absolute_url of my models, so CKEditor will use it instead of request string, something like this: def get_filename(filename, get_absolute_url): pass How can I pass to CKEditor this parameter? -
Display users assigned to a ticket model without showing duplicates
So I'm creating a bug tracker in django, I want to display all the users that are assigned to a ticket and currently I have a table that displays these users. However, the assigned users are duplicated. How do I show all the assigned users without showing duplicates. here is my template that shows the assigned users <tbody> {% for ticket in page_obj %} <tbody> {% for user in ticket.assignee.all %} <tr> <td><a href="">{{user.username}}</a></td> <td>{{user.email}}</td> <td></td> <td>{{user.get_account_type_display}}</td> </tr> {% endfor %} </tbody> {% endfor %} </tbody> view function class ProjectView(View): def get(self, request, pk): projects = Project.objects.get(id=pk) search_query = request.GET.get('search') tickets = Ticket.objects.filter(project=projects) # Search functionality if search_query: tickets = tickets.filter( Q(assignee__username__icontains=search_query) | Q(category__name__icontains=search_query) | Q(name__icontains=search_query) | Q(status__iexact=search_query) | Q(priority__icontains=search_query) | Q(type__icontains=search_query) ) assignees = assignees.filter(username__icontains=search_query) ticket_assignees = {} for ticket in tickets: # Get the assignees for the ticket and remove duplicates ticket_assignees[ticket] = ticket.assignee.all().distinct() # Store the assignees for this ticket in the dictionary ticket_assignees[ticket] = assignees # Paginate the ticket table paginator = Paginator(tickets, 5) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) # Paginate the assignees table assignees_paginator = Paginator(assignees, 5) assignees_page_number = request.GET.get('assignees_page') assignees_page_obj = assignees_paginator.get_page(assignees_page_number) context = { 'projects': projects, 'tickets': tickets, 'page_obj': page_obj, 'ticket_assignees': ticket_assignees, … -
Do I making a bad request to Graph API Facebook?
I'm developing a Django REST framework app that allow post images and videos on Facebook. I got several failed attempts when I try to post a video using the Graph API, I've all required permissions such as pages_show_list , pages_read_engagement and pages_manage_posts but I can't post anything. This is the ViewSet that I use for upload a video: class FacebookVideoPostViewSet(viewsets.ModelViewSet): queryset = FacebookVideoPost.objects.all() serializer_class = FacebookVideoPostSerializer permission_classes = [permissions.AllowAny] def create(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save() # Obtenemos la ruta base del proyecto ruta_base = os.path.abspath(settings.BASE_DIR) # Obtenemos la ruta relativa en donde está el archivo recién subido ruta_video = serializer.data['file'] # Concatenamos ambas rutas y obtenemos la ruta relativa del archivo que intentaremos subir ruta_abs = ruta_base + ruta_video # Obtenemos el tamaño en bytes del video size_video = os.path.getsize(ruta_abs) print(ruta_abs) print('Tamaño es bytes: ', size_video) try: # ======[ FASE 1 ]====== # 1. Hacemos la petición inicial de la subida reanudable del video init_sesion_subida = requests.post(f'https://graph-video.facebook.com/v16.0/{settings.FACEBOOK_PAGE_ID}/videos?upload_phase=start&access_token={settings.FACEBOOK_ACCESS_TOKEN}&file_size={size_video}') # Comprobamos que la petición se haya hecho de forma correcta if init_sesion_subida.status_code == 200: # Valores obtenidos al iniciar la sesión de subida # Obtenemos el diccionario que se nos retorno dict_valores_subida = init_sesion_subida.json() # video_id video_id = dict_valores_subida['video_id'] … -
Nginx + Django - 404 not found when I try to open files with non-ASCII characters
I have problem with my app (Django + Gunicorn + Nginx) running on Docker. I'm using X-Accel-Redirect header to serve protected files. Serving files with only ASCII characters works fine but when I'm trying to reach files like książka.pdf I'm getting 404. I'v checked media dir and file książka.pdf exist. In browser developer tools I can see that request is converted from /media/książka.pdf to /media/ksi%C4%85%C5%BCka.pdf nginx.conf charset utf-8; location /protected_media/ { alias /var/media/; internal; } views.py @login_required def protected_serve(request, path): response = HttpResponse() response['Content-Type']="" response['X-Accel-Redirect'] = '/protected_media/' + path return response Have anyone idea how to deal with filenames with non-ASCII characters? -
Django - MS Active Directory authentification using django-auth-ldap
I almost broke my mind trying to adjust my test django project to connect with my Active Directory. The goal is to create a simple login page that will check credentials with AD users data. AD located on the same machine as Django. AD users involved into process: admin, bind AD groups involved: django-admins AD has a default structure, with default Users folder where I created my users and a group. My settings.py file is below import os from pathlib import Path import ldap from django_auth_ldap.config import LDAPSearch, GroupOfNamesType AUTH_LDAP_SERVER_URI = "ldap://192.168.149.10" AUTH_LDAP_AUTHORIZE_ALL_USERS = True AUTH_LDAP_PERMIT_EMPTY_PASSWORD = True AUTH_LDAP_BIND_DN = "CN=bind,CN=Users,DC=ATK,DC=BIZ" AUTH_LDAP_BIND_PASSWORD = "Hahalala90!" AUTH_LDAP_USER_SEARCH = LDAPSearch( "dc=ATK,dc=BIZ", ldap.SCOPE_SUBTREE, "(uid=%(user)s" ) AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "dc=ATK,dc=BIZ", ldap.SCOPE_SUBTREE, "(objectCategory=Group)", ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn") AUTH_LDAP_START_TLS = True AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", } AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "cn=active,CN=django-admins,CN=Users,DC=ATK,DC=BIZ", "is_staff": "cn=staff,cn=django-admins,cn=Users,dc=ATK,dc=BIZ", "is_superuser": "cn=superuser,cn=django-admins,cn=Users,dc=ATK,dc=BIZ", } AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_TIMEOUT = 3600 AUTH_LDAP_CACHE_GROUPS = True AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) DRAL_CHECK_DOMAIN = False I followed the official documentation of django-auth-ldap and many others sources. And when I try to login into django-admin panel I receive Please enter the correct username and password for a staff …