Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Enforce Django Enum constraints into PostgreSQL Side
While i create Enum and used choices in djagno model.Something like class User(AbstractBaseUser, PermissionsMixin): """User model, all information related to user accounts""" class UserAccountStatus(models.TextChoices): PENDING = "PENDING", "pending" ACTIVATED = "ACTIVATED", "activated" BLOCKED = "BLOCKED", "blocked" status = models.CharField(choices=UserAccountStatus.choices, default=UserAccountStatus.PENDING) Django official link for same implementation If I open the PostgreSQL through pg Admin & update status field with some dummy text the row is updated and saved with dummy text. as shown in image I want to maintain same constraints on the PostgreSQL db side too. In SQLAlchemy we can achieve this behaviour through db.Enum() -
Is there a way for a future 'signer' to trigger a signature request from a template that belongs to a different user? - DocuSign API
Hi everyone I am having troubles with a workflow using the DocuSign eSignature API. I have an object on my website created by User A. User A has attached a templateId that corresponds to a template (in User A's account) containing the required documents to be signed by User B for that object. However User A is unaware of who User B is when creating the object. User B can be anyone. When User B chooses an object that has a template from User A, i would like to generate a signature request with that templateId for User B to sign using Embedded signing. Is this possible or have I completely missed the point? -
AttributeError at / 'NoneType' object has no attribute 'lower'
This is the code below: from instaloader import Instaloader, Profile import sqlite3 loader = Instaloader() connect = sqlite3.connect("db.sqlite3") cursor = connect.cursor() def get_hashtags_posts(num_post, hashtag): print(num_post, hashtag) posts = loader.get_hashtag_posts(hashtag) for post in posts: print(post.owner_username) Used this in a django project. Above mentioned code runs just fine seperately. When i try to use this code in a django project it shows this : Internal Server Error: / Traceback (most recent call last): File "E:\Development\scraper\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "E:\Development\scraper\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\Development\scraper\insta\views.py", line 14, in index sc.get_hashtags_posts(data2, data3) File "E:\Development\scraper\insta\sc.py", line 9, in get_hashtags_posts posts = loader.get_hashtag_posts(hashtag) File "E:\Development\scraper\venv\lib\site-packages\instaloader\instaloader.py", line 938, in get_hashtag_posts return Hashtag.from_name(self.context, hashtag).get_posts() File "E:\Development\scraper\venv\lib\site-packages\instaloader\structures.py", line 1241, in from_name hashtag = cls(context, {'name': name.lower()}) AttributeError: 'NoneType' object has no attribute 'lower' -
How to pass a variable to `gettext_lazy` using in model field?
I am trying to avoid using _() in each model field's verbose_name like this: (example is just for science) from django.db import models from django.utils.translation import gettext_lazy as _ def text_field(verbose_name, *args, **kwargs): return models.TextField(_(verbose_name), *args, **kwargs) class Post(models.Model): text = text_field('Text') And that does not work (strings just ignored by makemessages). Probably, it is expected But, how can it be done? Is it possible somehow to point makemessages to look at custom text_field function? Probably decorate somehow Or maybe there are some alternatives to Django's django.utils.translation that can handle such things? -
Editing user in django views error: The view feedback.views.users_edit didn't return an HttpResponse object. It returned None instead
I have CRUD operations for users. Everything is working well, except my function for edit users. It saves the changes, but when I tried to check if I can change the username to an existing username it gives me: ValueError: The view feedback.views.users_edit didn't return an HttpResponse object. It returned None instead. views.py def users_edit(request, id=0): if request.method == 'GET': if id == 0: form = UserForm() else: users = CustomUser.objects.get(pk=id) form = UserForm(instance=users) return render(request, 'useredit.html', {'form': form}) else: if id == 0: form = UserForm(request.POST) else: users = CustomUser.objects.get(pk=id) form = UserForm(request.POST, instance=users) if form.is_valid(): form.save() return redirect('feedback:users') userdelete.html {% extends 'main.html' %} {% block content %} <p>Are you sure to delete this {{user.email}} ?</p> <form action="{% url 'feedback:userdelete' user.id %}" method="POST"> {% csrf_token %} <a href="{% url 'feedback:users' %}">Cancel</a> <input type="submit" name="Confirm"> </form> {% endblock content %} I'm using django2.2 -
Getting Error while installing psycopg2 in windows
Hi I am working on a Django project and I am getting errors while installing psycopg2 on windows pip install psycopg2 I also tried pip install psycopg2-binary but still getting error ERROR: Command errored out with exit status 1: command: 'c:\users\theuser\appdata\local\programs\python\python39\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\theuser\\AppData\\Local\\Temp\\pip-install-zh83zqbg\\psycopg2\\setup.py'"'"'; __file__='"'"'C:\\Users\\theuser\\AppData\\Local\\Temp\\pip-install-zh83zqbg\\psycopg2\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\theuser\AppData\Local\Temp\pip-pip-egg-info-upmu4r_j' cwd: C:\Users\theuser\AppData\Local\Temp\pip-install-zh83zqbg\psycopg2\ Complete output (23 lines): running egg_info creating C:\Users\theuser\AppData\Local\Temp\pip-pip-egg-info-upmu4r_j\psycopg2.egg-info writing C:\Users\theuser\AppData\Local\Temp\pip-pip-egg-info-upmu4r_j\psycopg2.egg-info\PKG-INFO writing dependency_links to C:\Users\theuser\AppData\Local\Temp\pip-pip-egg-info-upmu4r_j\psycopg2.egg-info\dependency_links.txt writing top-level names to C:\Users\theuser\AppData\Local\Temp\pip-pip-egg-info-upmu4r_j\psycopg2.egg-info\top_level.txt writing manifest file 'C:\Users\theuser\AppData\Local\Temp\pip-pip-egg-info-upmu4r_j\psycopg2.egg-info\SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
Remove app default when migrate in Django
I'm been confused when migrating class models in Django the class name automatically change and it add app_ in the beginning of the table name, for example I have these models class lib_year(models.Model): year = models.CharField(max_length=40) class lib_period(models.Model): period = models.CharField(max_length=40) class lib_semester(models.Model): semester = models.AutoField(primary_key=True) When migrate it the table name change to app_lib_year, app_lib_period, app_lib_semester is there anyway how to remove default app_? when migrate models -
Django model accessing relationship model
How to access Articles through Reporter model with below code? from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) for example in Sqlalchemy we would create realtionship inside Reporter model with: reporter_article = db.relationship('Article', backref='reporter_article ', lazy='dynamic') that would be inside Reporter model and then we can call directly Reporter.query.reporter_article.all() How would I call to get all articles from reporter? -
window.location.href does not redirect
my functions are as follows <a onClick="check_claims(this)" type="button" href="javascript:void(0)" redirurl="www.facebook.com" >Invite</a> function check_claims(ele){ var select_claims = document.getElementById('select_claims').value; if (select_claims == '1') { var result = confirm("do you wish to continue?"); if (!result) { check_email_address(); return; } } check_email_address(); window.location.href = ele.getAttribute('redirurl'); } function check_email_address(){ if ('{{broker.email_address}}' == 'None') { console.log('this worked till here'); window.location.href = 'www.google.com'; } } I just added the second function check_email_address. the function gets called and the log gets printed but the windows.location.href of this function does not get evaluated and the page keeps redirecting to url mentioned in the window.location.href of first function. -
Problem with calling an AJAX modal with Django
Hi am new to django concept . so the problem is I have two pages where i can perform crud operations using AJAX , Product and Server . The problem comes when i create new user for Server , the Product create modal works fine , but server create modal also gives the same modal of Product . with name , id and others and not the field of server . Can anyone help me in this . urls.py urlpatterns = [ path('admin/', admin.site.urls), path('',views.IndexPage,name='IndexPage'), url(r'^products/$', views.product_list, name='product_list'), url(r'^create/$', views.product_create, name='product_create'), url(r'^products/(?P<pk>\d+)/update/$', views.product_update, name='product_update'), url(r'^products/(?P<pk>\d+)/delete/$', views.product_delete, name='product_delete'), url(r'^servers/$', views.server_list, name='server_list'), url(r'^create/$', views.server_create, name='server_create'), url(r'^servers/(?P<pk>\d+)/update/$', views.server_update, name='server_update'), url(r'^servers/(?P<pk>\d+)/delete/$', views.server_delete, name='server_delete'), ] partial_server_create.html <form method="post" action="{% url 'server_create' %}" class="js-server-create-form"> {% csrf_token %} <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true"></span> </button> <h4 class="modal-title">Create</h4> </div> <div class="modal-body"> {% include 'includes/partial_server_form.html' %} </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Create Customer</button> </div> </form> script.js var loadForm1 = function () { var btn1 = $(this); $.ajax({ url: btn1.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#modal-server .modal-content").html(""); $("#modal-server").modal("show"); }, success: function (data) { $("#modal-server .modal-content").html(data.html_form); } }); }; var saveForm1 = function () { var form = $(this); … -
How to validate input from TinyMCE on server side in django?
I am trying to validate text input from tinymce rich text editor on the server side in django. I have created a custom filter to allow those tags which are allowed in tinymce. register = template.Library() _ALLOWED_ATTRIBUTES = { 'img': ['src', 'class'], 'table': ['class'] } _ALLOWED_TAGS = ['b', 'i', 'ul', 'li', 'p', 'br', 'h1', 'h2', 'h3', 'h4', 'ol', 'img', 'strong', 'code', 'em', 'blockquote', 'table', 'thead', 'tr', 'td', 'tbody', 'th'] @register.filter() def safer(text): return mark_safe(bleach.clean(text, tags=_ALLOWED_TAGS, attributes=_ALLOWED_ATTRIBUTES)) This prevents simple tags from going into the database but the problem is arises in case the attacker enters something like <img src=alert(1)></img> or any other javascript inside the src or any other attribute which accepts javascript. Furthermore, the html could be base64 encoded. For example, <script>alert('hi');</script> in base 64 is PHNjcmlwdD5hbGVydCgnaGknKTs8L3NjcmlwdD4= This poses many security issues for the application. Is there any standard library which handles are such potential threats? If not, how can I go about making it secure against such attacks ? -
djnago StreamingHttpResponse showing loading
I am writing api to convert RTSP to HTTP URL I convert it using Django StreamingHttpResponse . I will attach the code below def gen(url): """Video streaming generator function.""" cap = cv2.VideoCapture(url) while (cap.isOpened()): ret, img = cap.read() if ret == True: img = cv2.resize(img, (0, 0), fx=1.5, fy=1.5) frame = cv2.imencode('.jpg', img)[1].tobytes() yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') time.sleep(0.1) else: break @api_view(['GET']) @permission_classes([]) def video_feed(request,cam_id): """ Converting RTSP stream to HTTP stream https://publicurl/api/video_feed/camera_id """ try: camera = Camera.objects.get(pk=cam_id) response = StreamingHttpResponse(gen(camera.CameraUrl), content_type='multipart/x-mixed-replace; boundary=frame') response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Headers"] = "*" return response except Exception as ex: logging.getLogger("error_logger").exception(repr(ex)) return Response({msg: validation["FDP23"]}, status=status.HTTP_400_BAD_REQUEST) also installed Django core headers while calling the api http://127.0.0.1:8000/api/video_feed/1 (my pubic URL is https) in browser I am getting the video but while trying to use in urlstreaming link no video is showing . only showing loading how can I solve this -
Django LDAP auth: simple_bind_s works but authentication fails: Authentication failed for user: user DN/password rejected by LDAP server
I am having a very difficult time implementing authentication in Django using ldap. My Configuration is as follows in the settings.py: AUTH_LDAP_SERVER_URI = "ldap://192.168.10.5" # AUTH_LDAP_BIND_DN = "cn=admin,dc=my,dc=domain,dc=com" # AUTH_LDAP_BIND_PASSWORD = "adminPass" # AUTH_LDAP_USER_SEARCH = LDAPSearch( # "dc=dc=my,dc=domain,dc=com", ldap.SCOPE_SUBTREE, "(cn=%(user)s)" # ) AUTH_LDAP_USER_DN_TEMPLATE = 'sAMAccountName=%(user)s,dc=my,dc=domain,dc=com' AUTH_LDAP_USER_QUERY_FIELD = 'username' AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "dc=dc=my,dc=domain,dc=com", ldap.SCOPE_SUBTREE, "(objectClass=group)", ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn") AUTH_LDAP_REQUIRE_GROUP = "dc=my,dc=domain,dc=com" AUTH_LDAP_USER_ATTR_MAP = { "username": "sAMAccountName", "first_name": "givenName", "last_name": "sn", "email": "mail", } AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "dc=my,dc=domain,dc=com", "is_staff": "dc=my,dc=domain,dc=com", "is_superuser": "dc=my,dc=domain,dc=com", } AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_TIMEOUT = 3600 AUTHENTICATION_BACKENDS = ( "django_auth_ldap.backend.LDAPBackend", "django.contrib.auth.backends.ModelBackend", ) Then a simple test here: def test(request): #1 test authentication obj = LDAPBackend() me = obj.authenticate(request, 'admin', 'adminPass') #2 Test Connection and auth con = obj.ldap.initialize(uri='ldap://192.168.10.5') t = con.simple_bind_s('admin', 'adminPass') # return HttpResponse('Empty') I have noted the following from the above test Test 1 never successds no matter what. I tried changing from sAMAccountName, to cn to principalName whatever seemed unique from AD explorer. The result is consistently the same: Authentication failed for admin: admin DN/password rejected by LDAP server. Test 2 seems to succeed if and only if I suffix the username with "@my.domain.com". Without this suffix it fails dismally with error: {'msgtype': 97, … -
How to get total number of votes for each choice in django Detail view?
I'm working on a django based restaurant review site. When user sends reviews they fill in a form which consists of two choice fields. Currently I can display all reviews for a specific restaurant in a Detailview page. I would like to take the information from the choice fields from the comment form to display this data for the user in both the detail view (1 specific restaurant) as well as the list view (all restaurant listed): Question: I would like to get the total number of "votes" for each choice and display it with for example Chart Js in the detail view. What is the prefered way or doing so in django? I have tried to do this filtering in javascript, however I know that this could be done more efficiently directly in the model or in the view. Code Models.py class Restaurant(models.Model): name = models.CharField(max_length = 100) class Comment(models.Model): STATUS_1 = ( ('one', 'one'), ('two', 'two'), ('three', 'three'), ) STATUS_2 = ( ('cheap', 'cheap'), ('normal', 'normal'), ('expensive', 'expensive'), ) restaurant = models.ForeignKey(Restaurant, on_delete = models.CASCADE, related_name='comments') comment = models.TextField(max_length = 500) status_1 = models.CharField(max_length = 100, choices=STATUS_1) status_2 = models.CharField(max_length = 100, choices=STATUS_2) views.py class RestaurantDetailView(DetailView): model = … -
Django filter products using mulitple stock prices
I have 2 models first store product (Product) and second store product related stock record (Stockrecord). My model class Product(models.Model): """Model to store product""" product_name = models.CharField(...) product_upc = models.CharField(..., unique=True) class Stockrecord(models.Model): """Model to store product""" product = models.ForeignKey(Product, related_name="stockrecords", on_delete=models.CASCADE) price1 = models.DecimalField(...) # required price2 = models.DecimalField(...) # optional price3 = models.DecimalField(...) # optional price4 = models.DecimalField(...) # optional I want to sort the product base on the price (low - high), based on all prices (price1 --- price4) qs = Product.objects.all() qs = qs.order_by('stockrecords__price1', 'stockrecords__price2', ....) the above query is working as expected. I give below o/p 1000, 2000, 300, 4000, 1300, 5000 -
Adding filter in django OrderingFilter
Is there any way to add a filter in OrderingFilter? I want to have this filter for ordering: F('created').desc(nulls_last=True) here is my code: class ProductFilter(filters.FilterSet): ordering = filters.OrderingFilter(fields=['price', 'created']) class Meta: model = Product -
Using other models's attribute as default
Below are some parts of my code from django.db import models from django.contrib.auth.models import User from places.fields import PlacesField class DonorProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) dropoff_location = PlacesField(blank=True, null=True) ... from django.db import models from register.models import DonorProfile from django.contrib.auth.models import User class ResourcePost(models.Model): donor = models.ForeignKey(User, on_delete=models.CASCADE, default=None) dropoff_location = PlacesField(blank=True, null=True, default=###) ... My question is on the ### part. I want to have the value of DonorProfile's dropoff_location be the default value of ResourcePost's dropoff_location. So basically put something like default=DonorProfile.objects.get(donorprofile_id).dropoff_location) as the default value. How can I do this? -
could not find js files in Django project
I used python 3.7 in widows 10 to create a Django project. I used superuser to create some normal user. But the normal user account could not login the website, and in the power shell, the below error occurs: [02/Nov/2020 13:33:03] "POST /login/?next=/ HTTP/1.1" 200 14278 Not Found: /login/vendor/fontawesome-free/css/all.min.css [02/Nov/2020 13:33:04] "GET /login/vendor/fontawesome-free/css/all.min.css HTTP/1.1" 404 19761 Not Found: /login/vendor/jquery/jquery.min.js [02/Nov/2020 13:33:04] "GET /login/vendor/jquery/jquery.min.js HTTP/1.1" 404 19713 Not Found: /login/vendor/bootstrap/js/bootstrap.bundle.min.js [02/Nov/2020 13:33:04] "GET /login/vendor/bootstrap/js/bootstrap.bundle.min.js HTTP/1.1" 404 19777 [02/Nov/2020 13:33:19] "POST /login/?next=/ HTTP/1.1" 200 14278 Not Found: /login/vendor/bootstrap/js/bootstrap.bundle.min.js [02/Nov/2020 13:33:19] "GET /login/vendor/bootstrap/js/bootstrap.bundle.min.js HTTP/1.1" 404 19777 Not Found: /login/vendor/jquery/jquery.min.js Not Found: /login/vendor/fontawesome-free/css/all.min.css [02/Nov/2020 13:33:19] "GET /login/vendor/fontawesome-free/css/all.min.css HTTP/1.1" 404 19761 [02/Nov/2020 13:33:19] "GET /login/vendor/jquery/jquery.min.js HTTP/1.1" 404 19713 Not Found: /login/vendor/jquery/jquery.min.js [02/Nov/2020 13:33:19] "GET /login/vendor/jquery/jquery.min.js HTTP/1.1" 404 19712 Not Found: /login/vendor/bootstrap/js/bootstrap.bundle.min.js [02/Nov/2020 13:33:19] "GET /login/vendor/bootstrap/js/bootstrap.bundle.min.js HTTP/1.1" 404 19776 But I have checked that I do have there files in that folder: enter image description here enter image description here I have tried to run python manage.py collectstatic but error occurs: raise ImproperlyConfigured("You're using the staticfiles app " django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. -
Cannot access django behind traefik v2 in docker swarm
I am trying to deploy my django application on a remote ubuntu server, using docker swarm, but I am unable to view the website. If I type just the servers ip address I get "404 page not found" however if I search the domain name, it just perpetually loads. I am however, able to access the traefik dashboard but this is using the servers ip address. I've checked that all the services are running with "docker service ls" and there are no issues. The traefik dashboard My production docker stack version: "3.7" services: traefik: image: traefik:v2.1 deploy: restart_policy: condition: on-failure placement: constraints: - node.role == manager labels: # enable traefik - "traefik.enable=true" # Swarm Mode - "traefik.http.services.traefik.loadbalancer.server.port=80" # Global redirection - http to https - "traefik.http.routers.http-catchall.rul=hostregexp(`{host:(www\\.)?.+}`)" - "traefik.http.routers.http-catchall.entrypoints=websecure" - "traefik.http.routers.http-catchall.middlewares=redirect-to-https" # Global redirection - https://www to https - "traefik.http.routers.https-catchall.rule=hostregexp(`{host:(www\\.).+}`)" - "traefik.http.routers.https-catchall.entrypoints=websecure" # traefik.http.routers.https-catchall.tls: "true"" - "traefik.http.routers.https-catchall.middlewares=redirect-to-https" # Middleware redirection - "traefik.http.middlewares.redirect-to-https.redirectregex.regex=^https?://(?:www\\.)?(.+)" - "traefik.http.middlewares.redirect-to-https.redirectregex.replacement=https://$${1}" - "traefik.http.middlewares.redirect-to-https.redirectregex.permanent=true" # traefik.http.middlewares.redirect-to-https.redirectscheme.scheme: https command: # Traefik dashboard - "--api=true" - "--api.insecure=true" - "--api.dashboard=true" # Traefik logs - "--log.filePath=/etc/traefik/traefik.log" - "--log.level=DEBUG" # Access Logs - "--accesslog=true" - "--accesslog.filepath=/etc/traefik/access.log" - "--accesslog.bufferingsize=100" - "--accesslog.filters.statuscodes=200,300-302,404" - "--accesslog.filters.retryattempts" - "--accesslog.filters.minduration=10ms" # Docker - "--providers.docker" - "--providers.docker.endpoint=unix:///var/run/docker.sock" - "--providers.docker.exposedByDefault=false" # Docker … -
Run a script everyday in django-rest api on heroku
I want to run a particular script every day in the morning for my rest api deployed on heroku the script itself it's only a database filler. how can that be done? I forgot to mention that i'm using django rest_framework -
Adding manager in django form
I want to create user from extended Profile model , its done using api request , but from form it is not working . In api request body I am passing three fields only name,email,and phone_number, so that password is making through random automatically. class ProfileManager(model.Manager): def create(self, email,phone_number, **kwargs): password=str(random.random())[2:8] user = User(username=phone_number) user.set_password(password) user.save() profile = Profile( auth_user=user, email=email, **kwargs ) profile.save() if am using form like class CustomerCreateForm(forms.ModelForm): name =forms.CharField(label='Name', max_length=32) phone_number = forms.CharField(label='Name', max_length=32) class Meta: model=Profile fields=['email','name','phone_number'] this ,it making error like user (1048, "Column 'user_id' cannot be null") because my profile model look like class Profile(models.model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) email = models.CharField(max_length=50,null=True, blank=True) phone_number = models.CharField(max_length= 15, null=True, blank=True) So from here i understood that ProfileManager is not dependent with form, so i need to make def validate(self,attrs) like function and differet manger for form , but i don't know how to do this due to newbie. Any help is appreciated -
Increasing cooloff time for djano-axes AXES_COOLOFF_TIME
The django-axes docs state you can use a callable as the input for AXES_COOLOFF_TIME. I'm wondering if it's possible to have the cooloff time increase each time a user enters an incorrect password beyond value for the AXES_FAILURE_LIMIT. -
I have to pass the multiple <int:pk> in a single endpoint for django rest api?
Here in the above picture, I have all the packages shown for single destination id ie pk=1. Now, what i want to show is single package of single destination ie my endpoint should be localhost/api/destination/1/package/1 or something like this. My views and serializers are as shown below: class DestinationPackageSerializer(serializers.ModelSerializer): class Meta: model = Package # fields = ['id', 'destination'] fields = '__all__' class DestinationwithPackageSerializer(serializers.ModelSerializer): packages = DestinationPackageSerializer(many= True,read_only=True) class Meta: model = Destination fields = ['id', 'name', 'dest_image', 'packages'] # fields = '__all__' # depth = 1 class DestinationFrontSerializer(serializers.ModelSerializer): class Meta: model = Destination # fields = ['id', 'package'] fields = '__all__' # depth = 1 My views are: class DestinationFrontListAPIView(ListAPIView): queryset = Destination.objects.all().order_by('?')[:4] # queryset = Package.objects.all().order_by('-date_created')[:4] serializer_class = DestinationFrontSerializer class DestinationPackageListAPIView(RetrieveAPIView): queryset = Destination.objects.all() serializer_class = DestinationwithPackageSerializer My urls are: path('api/destinations', views.DestinationFrontListAPIView.as_view(), name='api-destinations'), path('api/destinations/<int:pk>', views.DestinationPackageListAPIView.as_view(), name='api-destinations-packages'), -
How to Make Looping through a Dataframe Faster in my Django Project
I have this code that runs through a model converted to a Dataframe having 7k entries and run some calculations on that, and then i run through another model of 2k entries and do certain calculations and also use the calculations made in the first dataframe run and then return the Output as a response [in Excel File] but that take very long to execute in my django project[4-5 minutes] which is not an acceptable time. Please suggest how do i make this Operation faster? I have tried df.iterrows() also but that doesnt bring about much difference. -
How to access ODBC Driver on Azure App service
I'm trying to run a Django (3.0) app on Azure App Service in Linux, connected to an Azure SQL Database. In my staging App Service instance, this works perfectly, however, when I set up my production instance on a different Azure account, my Django app can no longer access the database. When I hardcoded the ODBC Driver 17 into database settings, I got this error in my Oryx build logs: pyodbc.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)") When I switched to the non-hardcoded version suggested here, I got this error: 'driver': sorted(pyodbc.drivers()).pop(), IndexError: pop from empty list How does one go about installing an ODBC Driver on Azure App Service?