Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Detect when user register/Login on Context Proccessor Django
I have to do some checks all the time with the context proccessor.The value must be 'True' as soon as the user logs in.But when navigating the site after logging in, the value should be 'False'. So it should be a one-time True result.I need to do this both for the login process and when registering.And I have to implement them with Context Proccessor in Django. How can I do that? def user_info(request): ctx = dict() user = request.user ... ctx["isRegistered"] = False ctx["isLoggedIn"] = False # if user register website, that moment 'request' : # ctx["isRegistered"] = True return ctx -
understanding try except python/django
I need your help with understanding try-except python/Django. so I have this function: def submit_dept_head_application(request, application_id): cv = request.FILES['cv'] letter = request.FILES['letter'] candidate_id = request.data['candidateId'] rank_id = request.data['requestedRankId'] application_state = { 'candidate_id': candidate_id, 'rank_id': rank_id, 'cv_filename': cv.name, 'letter_filename': letter.name, } creator = Profile.objects.get(user=request.user.id) department = creator.department applicant = Profile.objects.get(user=candidate_id) applicant_profile_id = applicant.id rank = Rank.objects.get(id=rank_id) try: application = Application.objects.get(id=application_id) # TODO - update application except Application.DoesNotExist: application = None if application is None: application = Application(creator=creator, applicant=applicant, desired_rank=rank, application_state=application_state, department=department ) application.save() create_application_directory(application.id) ApplicationStep.objects.update_or_create( application=application, step_name=Step.STEP_1, defaults={'can_update': True, 'can_cancel': True, 'currentStep': True} ) copy_to_application_directory(cv, application.id) copy_to_application_directory(letter, application.id) send_email(settings.SENDGRID_SENDER, ['xxxxxx@gmail.com'], 'new application submitted', 'new application submitted') return Response(application.id, status=status.HTTP_200_OK) right now what is happening is that if there is no open application I create a new one. what I'm trying to do is to add another check, which is Application.objects.filter(applicant=applicant_profile_id) so if I have an opened application for this candidate it won't get to the application.save() but it will send an error. i don't really know how to do so and that's where i need your help please :) -
DRF --405 Method not allowed for update operation
I have done this before and may be it did work properly that time but now suddenly it's not working as it's expected to be. The viewset.py: class ProfileViewSet(ModelViewSet): serializer_class = ProfileSerializer http_method_names = ["post", "get", "put", "delete"] queryset = Profile.objects.all() def get(self, request, format=None): users = Profile.objects.all() serializer = ProfileSerializer(users, many=True) return Response(serializer.data) def put(self, request, pk, format=None): snippet = self.get_object(pk) serializer = ProfileSerializer(snippet, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) models.py class Profile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) full_name = models.CharField(_("Name of User"), blank=True, null=True, max_length=255) phone_number = PhoneNumberField() zip_code = models.CharField(_("Zip Code"), blank=True, null=True, max_length=255) def __str__(self): return self.user.username seralizers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' urls.py router.register("profile/<int:pk>", ProfileViewSet, basename="profile_each") whenever I hit in postman It says "405 Method not allowed". Am I missing anything here please? -
Django. How to get URL by its name?
I want to get url by name specified in urls.py. Like {% url 'some_name' %} in template, but in Python. My urls.py: urlpatterns = [ ... path('admin_section/transactions/', AdminTransactionsView.as_view(), name='admin_transactions'), ... ] I want to something like: Input: url('admin_transactions') Output: '/admin_section/transactions/' I know about django.urls.reverse function, but its argument must be View, not url name -
Speech recognition suddenly detects "at" instead of "@"
usually when I say "at" for mail name speech recognition detects "@", but today when ı try the program it shows "at" instead of "@" . How can I solve this problem? -
DJANGO custom import CSV
I have a model with multiple fields. I want to make an importer (possibly with the django import-export library) that only takes two fields and with that calculates the rest of the fields that the model has. I wanted to listen and ask if you know of ways to do this. Since the documentation does not mention much. Thank you all! -
Django project located out of Apache ServerRoot
Got some problems trying to include Django-app in my already configured httpd2 apache server. I'd successfully installed mod_wsgi and set some configuration using the deployment manual: https://docs.djangoproject.com/en/4.0/howto/deployment/wsgi/modwsgi/ I added the following settings in httpd.conf WSGIScriptAlias /djangosrv/ /app/djangosrv/djangosrv/wsgi.py WSGIPythonPath /app/djangosrv <Directory /app/djangosrv/djangosrv> <Files wsgi.py> Require all granted </Files> </Directory> The project has the following structure and runs the only app named 'searchpage' /app/djangosrv -- djangosrv -- searchpage The URLs defined in /app/djangosrv/djangosrv/urls.py : urlpatterns = [ path('searchpage/', include('searchpage.urls')), path('admin/', admin.site.urls) ] When I try to open http://localhost/djangosrv/ I get 404: Page not found (404) Request Method: GET Request URL: http://localhost/djangosrv/ Using the URLconf defined in djangosrv.urls, Django tried these URL patterns, in this order: searchpage/ admin/ The empty path didn't match any of these. And when I try to access http://localhost/djangosrv/searchpage/ I get: Forbidden You don't have permission to access this resource. How can I configure routing in Django-project to make it work with non-server-root URLs ? Should I use some extra directory settings in httpd.conf and configure mod_rewrite ? CentOS 8 Apache/2.4.37 python3-mod_wsgi-4.6.4-4.el8.x86_64 python3-django3-3.1.7-1.el8 Any help would be greatly appreciated! -
Django: (fields.E300) Field defines a relation with 'Class' model , which is either not installed, or is abstract
Class model is a foreign key in File model I have no idea what causes the error above,I searched it and it mostly occurs when working with models in different apps, but that is not case in this situation, since both models are in the same models.py file. models.py from asyncio.windows_events import NULL from http.cookiejar import FileCookieJar from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractBaseUser,PermissionsMixin, BaseUserManager class Class (models.Model): name=models.CharField(max_length=256); def __str__(self): return self.name; class File (models.Model): file=models.FileField(); name=models.CharField(max_length=255); class_name=models.ForeignKey(Class,on_delete=models.CASCADE) def __str__(self): return self.name; class Class (models.Model): name=models.CharField(max_length=256); def __str__(self): return self.name; class CustomUserManager(BaseUserManager,): def create_superuser(self,email,name,surname,password,**other_fields): other_fields.setdefault('is_staff',True) other_fields.setdefault('is_superuser',True) other_fields.setdefault('is_active',True) if other_fields.get('is_staff') is not True: raise ValueError('super user must be assigned to is_staff= True') if other_fields.get('is_superuser') is not True: raise ValueError('Super user must be assigned to is_super_user=True') return self.create_user(email,name,surname, password,**other_fields) def create_user(self,email,name,surname,password,**other_fields): if not email: raise ValueError(('You must provide an email address')) email=self.normalize_email(email); #for example ignore the case sensitivity user=self.model(email=email,name=name,surname=surname,**other_fields) user.set_password(password) user.save() return user; class NewUser(AbstractBaseUser,PermissionsMixin): email=models.EmailField(max_length=255,unique=True,default=NULL,) name=models.CharField(max_length=255) surname=models.CharField(max_length=255) is_staff=models.BooleanField(default=False) is_active=models.BooleanField(default=True) is_teacher=models.BooleanField(default=False) classes=models.ManyToManyField(Class) objects=CustomUserManager(); USERNAME_FIELD='email' REQUIRED_FIELDS=['name','surname','is_teacher'] def __str__(self) : return self.name class Request(models.Model): requested_class=models.ForeignKey(Class,on_delete=models.CASCADE) requesting_student=models.ForeignKey(NewUser,on_delete=models.CASCADE) def __str__(self): return self.requesting_student.name # Create your models here. -
Django Authentification with class based views login() method
as I am trying to build a login/registration form, I came into a problem. I am building my form with class based views, and I want to use the login() method for the auth. The problem is that it won't work, even if I have followed the same example as the docs had. Here is my code: views.py: def login(request): if request.method == 'POST': form = MyLoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect("/home") else: messages.error(request, 'There Was An Error Logging In, Try Again...') else: form = MyLoginForm() return render(request, 'users/firstAction/login.html', {'form': form}) My template: <body> <div class="limiter"> <div class="container-login100" style="background:black;"> <div class="wrap-login100"> <span class="login100-form-logo"> <i class="zmdi zmdi-landscape"></i> </span> <span class="login100-form-title p-b-34 p-t-27"> Login </span> {% if messages %} <ul class="red"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} {% if form %} <form method="POST" novalidate class="login100-form validate-form"> {% csrf_token %} {% if form.non_field_errors %} {% for error in form.non_field_errors %} <div class="red"> <p>{{error}}</p> </div> {% endfor %} {% endif %} {% for field in form %} <div class="wrap-input100 … -
AttributeError at /account/oidc/callback/ '_RSAPrivateKey' object has no attribute 'verify'
AttributeError at /account/oidc/callback/ '_RSAPrivateKey' object has no attribute 'verify' Request Method: GET Request URL: http://localhost:8000/account/oidc/callback/?code=0.AQwA2kdaUAbvNU-5Y653jiyu-YHq0RPhP-9Cu3wqKQekVioMAJA.AQABAAIAAAD--DLA3VO7QrddgJg7Wevr6SStf98KkAv7heodBmkUKzmyvPGA7xsbND57p5XO-w3Cdn_KSw8Pbvcz5A1oB_i7zyj2emCgFtsFIlY-wI2MmRKmDBv0ZTJ07SUw_qJigWlRQeA5eXcCiE_f9WjU7qolelJFjA2GxgUXxH_7Fv7GMns1mXDPSicVwt_wBVzTDX-ONGIGqoR8tmsLMKOGBZtDKM9wy46LbXH3TOTR8ZwlyNZZDInpOuIWc2-RYyR73_fhjc57o07bVEJb7GT7sgzQ6Usp9a7pGAdLd3zaXZdPa-y3Dt71dlmLTqNkLi_COaTikBdzYRQEDRMMIjIKaLcSJXbCNRXd2pcPqDadXyS3_iZnhdfdFEK0-52vz-8pJUzZVGghTTiyTWojNd851369lriYC6SKn4qA7tcfLjqoHSJ71CkPVTD_dv1S_YZCPjzEBjuQ9FaKqJ6_EjhsQbwp1mrr6iJQg5fb-oGPEV21twaNvhppiApzhi_d7wKU-qRDv9xARGCuQ8R_w2smNNOrBamaSqQKph0pBVbq-N-04nT9ghp-83vhRCCrmPiCLRJfGb3xq-Pp2jwe4qBnoNhb2XNjZbtypPtel-EVY4XcqSAA&state=1TepMIKbpC2BHhWd0PpJJcBifzHqPrF6&session_state=bbe01820-0187-4e1e-9982-9431dc7bd273 Django Version: 1.9.7 Exception Type: AttributeError Exception Value: '_RSAPrivateKey' object has no attribute 'verify' Exception Location: C:\Users\hp\AppData\Local\Programs\Python\Python36\lib\site-packages\josepy\util.py in getattr, line 81 Python Executable: C:\Users\hp\AppData\Local\Programs\Python\Python36\python.exe Python Version: 3.6.5 -
How allow to fit read_only field for new record in TabularInline class in Django
I want to have a field readonly when record already saved but if admin adds a new record field must to be editable. Red arrows - read only; Blue arrow - edited. How I can achieve it? -
How to force a page-break on weasyprint?
I wonder if its possible to create a force break that splits the table rows? I think weasyprint does this in a sense but I want to break the rows in to specific counts (e.g 6 rows per page). Is that possible? I tried something like this: <table> <tr> <th>Header1</th> <th>Header2</th> </tr> {% for d in data %} {% if forloop.counter == 6 %} <p style="page-break-before: always;"></p> {% endif %} <tr> <td>{{ d.name }}</td> <td>{{ d.age }}</td> </tr> {% endfor %} </table> but it just break each row in different pages. Any help would be appreciated. -
Can I somehow combine columns into array of objects (list of dicts) by Django ORM?
I use PostgreSQL as a DB. And I have the following situation: Say, we have the following data (we got it joining two tables - orgs and markers). What I want to get by SELECT is Using raw SQL I would do something like this SELECT orgs.org_id, json_agg( json_build_object( 'id', markers.marker_id, 'name', markers.name ) ) as markers_data FROM orgs INNER JOIN markers ON orgs.org_id = markers.org_id GROUP BY orgs.org_id; But I want to combine those columns this way using Django ORM. Is it possible to do on SQL level not Python? So I don't have to just extract data from the DB and modify it to a desired format on Python level. -
How do I remove unused CSS when using Django, Sass and a frontend framework?
I am using a SCSS-based frontend framework (namely cirrus-ui) with my Django project. For compiling the CSS stylesheet with Sass, I use webpack to compile the static files (Presently only CSS stylesheets but I'm sure some JavaScript will probably work its way in there eventually). In the Python project, I use django-webpack-loader. My compiled, minified CSS stylesheet is a whopping 265 KiB. This is not ideal. I know about PurgeCSS and uncss. While I have not used them before, I think I understand how to call these from the webpack.config.js. What I don't know is how to utilize these or something similar with Django and its templates. Notes: I use Yarn to manage packages. main.scss (example excerpt). @use "cirrus-ui/src/cirrus-all" as *; I actually do provide a custom configuration map, but I don't see how that's relevant to the question. Relevant Django Configuration Details (settings.py) WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, 'STATS_FILE': BASE_DIR / 'frontend/webpack-stats.json', 'POLL_INTERVAL': 0.1, 'IGNORE': [r'.*\.hot-update.js', r'.*\.map'], } } STATICFILES_DIRS = [ './frontend/static', ] Project layout PROJECT ROOT/ - djangoproject/ - settings.py - templates (TEMP)/ - manage.py - frontend/ - .yarn/ - static/ - (Compiled Static Files Here) - assets/scss/main.css - webpack.config.js - webpack-stats.json - package.json … -
how to link a div using <a href> to appear in the middle of the screen instead of top?
this is to go back to home page that has a listview of posts and to keep the screen at where the post is located after clicking go back button in the post details page. <a href="/users/home#post{{ post.id }}"><button class="button" style="float: right; margin-right: 5px;">Go back</button><br></a> However, since there is a sticky nav bar at the top, it covers the post after clicking go back button. I want to make the post appear in the middle of the screen instead of at the top. -
DRF ModelSerializer meta extra_kwargs not working for related fields
I am designing API in DRF and have stumbled upon one issue that hopefully you can help me to solve. Let's assume I have the following model and a serializer: class SomeModel(models.Model): property = models.ForeignKey( Property, on_delete=models.PROTECT, ) name = models.CharField() address = models.OneToOneField(null=True, blank=True) ...more class SomeModelSerializer(serializer.ModelSerializer): class Meta: model = SomeModel fields = "__all__"" extra_kwargs = { "name": {"required": True}, "address": {"required": True}, "property": {"required": True}, } As you can see I am trying to add field kwargs by using extra_kwargs. The issue is that it won't work for a related field e.g. property or address field. I know I can just override it by defining a field manually and passing required=True, and that works but it's too long for my use case. Do you have any idea why this happen? Thanks. -
A problem with django using DefaultRouterWithNest
router2 = DefaultRouterWithNest() ( router2.register(r'eva',eval.Evadetail, basename='eva') .register(r'evand',eval.Evand,basename='eva-evand',parents_query_lookups=['eva_id']) .register(r'evard',eval.Evard,basename='eva-evard',parents_query_lookups=['eva_id','eva_nd_id']) ) problems: NameError: name 'DefaultRouterWithNest' is not defined what packeages should I import? -
Replacement in python package in Docker
GraphQL is still not supported in Django 4, so to use it I need to change the line: "from django.utils.encoding import force_text" to "from django.utils.encoding import force_str as force_text" in package "VENV/lib/PYTHON_VERSION/site-packages/graphene_django/utils/utils.py" The problem occurs when using Docker, how could I replace this line when building the container? -
Url decoding problem on deployment with IIS and FastCGI on windows server
I realized an app front Angular, back-end Django, deployed on Windows server using IIS and FastCGI. This app serves media files on a certain URL. It works fine locally on dev server. I can access all my files correctly on path "medias/myfilepath". The problem is in production on IIS. Special characters are encoded in a different way. I think it is FastCGI that does it. I cannot find the encoding rules, and my Django app is not able to decode properly so my requests end up with a 404 error. Here are some examples of the difference of encoding between local server and production server : à | local : %C3%80 | prod : %25C0 ù | local : %C3%99 | prod : %25D9 É | local : %C3%89 | prod : %25C9 I can't find any documentation on the subject, I don't have access to configurations on CGI side. I could update decoding on Django side to fit it, but I can't find which one applies ... Someone would have some ideas on that subject ? -
WARNING: autodoc: failed to import module 'upload_data_to_server' from module 'manual';
I'm trying to document a Django project using Sphinx's autodoc extension. I have two main problems: It's documenting excessivelly in some modules (importing documentation that I don't want from django) It's not documenting one of the packages at all. Here is my django tree: |main_app | core | migrations | static | templates | consumers.py | forms.py | models.py | routing.py | serializers.py | urls.py | views.py | main_app | asgi.py | settings.py | urls.py | wsgi.py | manual | upload_data_to_server.py | manage.py | docs | _build | _static | _templates | conf.py | index.rst | make.bat | Makefile The docs file is the one I created to host the files created by sphinx-quickstart. Then, I changed the conf.py file adding this lines: import os import sys import django sys.path.insert(0, os.path.abspath('..')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main_app.settings") django.setup() extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon'] And I changed index.rst adding modules: Welcome to yourProject's documentation! ==================================== .. toctree:: :maxdepth: 2 :caption: Contents: modules Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` I executed sphinx-apidoc -o . .. and ./make html. I get something similar to what I want, but I said before, I get too many comments for django files, and no comments at all … -
How to optimize the downlaod big file problem in Django?
My Django project gives an download interface as def download_item_vector(request): return HttpResponse(np.load('item_vector.npy')) I want to return a big numpy array to the client. But it is very slow. Is there any good idea to do that? -
Testing UX with random IO?
So I've found a error in my UX that wasn't cought by test if I press besides a popup it goes into deadstate # they press ok btn = self.browser_adam.find_element(By.ID, "closeBtnMod").click() How do I catch things like reloading a page or this special case? -
Django model default value in response
I want to have a default value in my django model response value Sample model query myModel.objects.filter().values("username", "user_gender") I want to have a default value in response It must be like Select username, user_gender, 'delhi' as country from mytable Please let me know if any suggestions -
How to create a persigned url for a private s3 bucket using django rest framework
models.py def upload_org_logo(instance, filename): ts = calendar.timegm(time.gmtime()) filepath = f"Timesheet/org_logo/{ts}" if instance: base, extension = os.path.splitext(filename.lower()) filepath = f"Timesheet/org_logo/{instance.org_id}/{instance.org_name}{extension}" return filepath class Organisation(models.Model): """ Organisation model """ org_id = models.CharField(max_length=50,default=uuid.uuid4, editable=False, unique=True, primary_key=True) org_name = models.CharField(unique=True,max_length=100) org_code = models.CharField(unique=True,max_length=20) org_mail_id = models.EmailField(max_length=100) org_phone_number = models.CharField(max_length=20) org_address = models.JSONField(max_length=500, null=True) product = models.ManyToManyField(Product, related_name='products') org_logo = models.ImageField(upload_to=upload_org_logo, null=True, blank=True,) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I am saving the Org_logo in the private s3 bucket, I need to get the Image from the s3 bucket using a presigned url. I checked out some solutions but I am not sure how to use it specifically on where like in models or views or other? Can you please help me with how to use it and where to use based on my above code. AWS Settings.py AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = '' AWS_STORAGE_BUCKET_NAME = '' AWS_QUERYSTRING_AUTH = True AWS_S3_FILE_OVERWRITE = True AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_REGION_NAME = '' AWS_DEFAULT_ACL = None AWS_S3_VERIFY = True DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
how can i filter data between two time i am using date time field for it in django rest framework
I am trying to filter my data with date time field but in my case its not working so please someone suggest me how can i filter my date with time start_time = 2022-05-13 02:19:19.146009 end_time = 2022-05-13 02:20:19.146009 parser_order_mi = ParserOrderMenuItem.objects.filter(menu_item_id=menu_item_id, created_at__range=[start_time,end_end_time])