Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
User searching system in Django
I am trying to make user searching system. The idea is to show users in dropbox under the searching field and make them link to their profile. But django template engine can't parse dynamically created tags, so links are incorrect. Hope on you, thanks main.js $.ajax({ type: 'POST', url: '{% url "instagram:search" %}', data: { name: $('#isearch').val(), csrfmiddlewaretoken: getCookie('csrftoken'), action: 'post' }, success: (json) => { search = document.querySelector('#drp') $(search).empty(); // TODO разобраться с поиском json['users'].forEach(element => { arr = ['<li role="presentation"><a role="menuitem" tabindex="-1" href="{% url ', "'instagram:home' username=", element, ' %}">', element, '</a></li>' ] search.insertAdjacentHTML( 'beforeend', arr.join("") ); }); }, error: function (xhr, errmsg, err) { } }); } -
Django why does @action decorator ignore *_classes overrides in some circumstances
I cannot consistently recreate this issue since I cannot pinpoint what causes this. In a few ViewSets we have extra views using the @action decorator. About half of them properly override *_classes arguments (such as permission_classes, renderer_classes, parser_classes), and the other half, just don't. Which can be seen by debugging, or simple setting these arguments to garbage. In half of them, setting permission_classes to the string 'hello world' will blow Django up upon hitting that endpoint since it tries to instantiate an object from the string. Doing the same for the other half, nothing happens. Django doesn't complain or blow up, and in debugging in the view, the *_classes are still set to the parent ViewSet's (either when garbage or validly set to a different list). Haven't been able to find anything in common between the viewsets with @action decorators that don't properly override *_classes arguments. Is there any bit of code that I should look through to figure this out? -
Bootstrap dropdown wont appear
Hey so my bootstrap dropdown menu wont work by clicking on it. Heres my code: <div class="dragArea row fake_input"> <div class="col-md col-12 form-group" data-for="name"> <p class="fake_input_text">{{ password }}</p> </div> <div class="dropdown"> <button class="btn btn-success display-4 dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Choose Length </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" href="#">2</a> <a class="dropdown-item" href="#">4</a> <a class="dropdown-item" href="#">6</a> </div> </div> <div class="mbr-section-btn col-12 col-md-auto"><a href="{% url 'home:passwordgenerator' %}" class="btn btn-success display-4">Generate</a></div> </div> -
ODBC Driver 17 for SQL Server: Client unable to establish connection, macOS, django, odbc
Everything was working until I restarted my laptop. I have this setup: python 3.8.9 django 3.1.1 pyodbc 4.0.30 pyodbc.drivers() shows this: ['ODBC Driver 17 for SQL Server'] SQLServer openssl version shows this: OpenSSL 1.1.1l 24 Aug 2021 isql -v -k "DRIVER=ODBC Driver 17 for SQL Server;SERVER=<my server>,<my port>;UID=<my username>;PWD=<my password>" connects to the database with no issues servername, port, user, and password seems correct also because the jdbc driver works without any issues with them. cat /etc/odbcinst.ini and cat /etc/odbc.ini - both return this: [ODBC Driver 17 for SQL Server] Description=Microsoft ODBC Driver 17 for SQL Server Driver=/usr/local/lib/libmsodbcsql.17.dylib UsageCount=10 odbcinst -j returns this: unixODBC 2.3.9 DRIVERS............: /usr/local/etc/odbcinst.ini SYSTEM DATA SOURCES: /usr/local/etc/odbc.ini FILE DATA SOURCES..: /usr/local/etc/ODBCDataSources USER DATA SOURCES..: /Users/sgalich/.odbc.ini SQLULEN Size.......: 8 SQLLEN Size........: 8 SQLSETPOSIROW Size.: 8 in the django settings: DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASSWORD'), 'HOST': os.environ.get('DB_HOST'), 'PORT': os.environ.get('DB_PORT'), 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } cat ~/.bash_profile shows this: export PATH="/usr/local/opt/openssl@1.1/bin:$PATH" export CPATH="/usr/local/opt/openssl@1.1/include" export LDFLAGS="-L/usr/local/opt/openssl@1.1/lib" export CPPFLAGS="-I/usr/local/opt/openssl@1.1/include" export LIBRARY_PATH="/usr/local/opt/openssl@1.1/lib" export DYLD_LIBRARY_PATH="/usr/local/opt/openssl@1.1/lib" export DYLD_FALLBACK_LIBRARY_PATH="/usr/local/opt/openssl@1.1/lib" I reinstalled the ODBC Driver with this official Microsoft instruction. But it didn't help. I'm still failing to start the django … -
Django-Dramatiq - How to configure dramatiq_abort
I am running: Windows 10 Django 4+ Python 3.9.x Newest version of dramatiq Newest version of dramatiq_abort Newest version of django_dramatiq settings.py ### ### For dramatiq tasks! ### import urllib.parse import dramatiq import dramatiq_abort REDIS_USER = "myuser" REDIS_PASS = "mypassword" REDIS_URL = "redis://%s:%s@localhost:6379/0" % (urllib.parse.quote(REDIS_USER, safe=''), urllib.parse.quote(REDIS_PASS, safe='')) # Frontend DRAMATIQ_BROKER = { "BROKER": "dramatiq.brokers.redis.RedisBroker", "OPTIONS": { "url": REDIS_URL, }, "MIDDLEWARE": [ "dramatiq.middleware.Prometheus", "dramatiq.middleware.AgeLimit", "dramatiq.middleware.TimeLimit", "dramatiq.middleware.Callbacks", "dramatiq.middleware.Retries", "dramatiq_abort.middleware.Abort", #I import Abort "dramatiq_abort.middleware.Abortable", # I import Abortable "django_dramatiq.middleware.DbConnectionsMiddleware", "django_dramatiq.middleware.AdminMiddleware", ], # When I put this here, I get the error __init__() missing 1 required keyword-only argument: 'backend' #"BACKEND": "dramatiq_abort.backends.RedisBackend(client=None).from_url(" + REDIS_URL + ")" } # Defines which database should be used to persist Task objects when the # AdminMiddleware is enabled. The default value is "default". DRAMATIQ_TASKS_DATABASE = "default" # Backend DRAMATIQ_RESULT_BACKEND = { "BACKEND": "dramatiq.results.backends.redis.RedisBackend", "BACKEND_OPTIONS": { "url": REDIS_URL, }, "MIDDLEWARE_OPTIONS": { "result_ttl": 60000 }, #"BACKEND": "dramatiq_abort.backends.RedisBackend(" + REDIS_URL + ")", # When I put it here, I get No module named 'dramatiq_abort.backends.RedisBackend(client=None) "BACKEND": "dramatiq_abort.backends.RedisBackend(client=None).from_url(" + REDIS_URL + ")" } ### ### End of dramatiq tasks! ### I have django_dramatiq configured correctly, consequentially dramatiq configured correctly. The question is how do I configure dramatiq_abort in conjunction with django_dramatiq? -
Force Django to recognize a model field value as a template tag value and escape the curly braces?
I am allowing users to create custom templates, and when doing so they are building off of my own base template with context variables. So my own template that is used as a base will have a line such as.. <h3>1.0: Contract Specifics for {{ first_name }}</h3> Now when the user edits this form I am escaping the curly brackets so they store as actual curly brackets in the form field when the user saves their custom template. Now a user will click save and in the model field there will be raw HTML stored as a TextField and is stored in the database as such... Now I need to render this in my django template later on but, I need {{ first_name }} to be replaced the actual context variable. unfortunately in my django template when I render this specific form field to display the HTML {% autoescape off %} {{ contract_detail }} {% endautoescape %} it displays as.. 1.0: Contract specifics for {{first_name}} Is there anyway to force django to recognize this as a template variable and render this correctly, maybe I need some sort of custom functionality, or templatetag? -
TypeError: Object of type ManyRelatedManager is not JSON serializable in django rest framework
I am trying to add some students to a teacher class using their ids as primary key but I am getting above error. I have models of Teachers and Students like this. class Student(TimeStampAbstractModel): user = models.OneToOneField(User, related_name="student", on_delete=models.CASCADE) college_name = models.CharField(max_length=255, default="", blank=True) address = models.CharField(max_length=255, default="", blank=True) def __str__(self): return self.user.name class Teacher(TimeStampAbstractModel): user = models.OneToOneField(User, related_name="teacher", on_delete=models.CASCADE) address = models.CharField(max_length=255, default="", blank=True) students_in_class = models.ManyToManyField(Student,related_name="teacher") def __str__(self): return self.user.name Here a teacher model can have many students in a class with thier ids. I have used an put api call to add the students to the teacher in one click. My view: from rest_framework import status class AddtoClassView(APIView): def put(self,request,pk,*args,**kwargs): id =pk teacher = Teacher.objects.get(id=id) serializer = TeacherSerializer(teacher,data=request.data) if serializer.is_valid(): serializer.save() print("iam if") return Response({ "message":"Student has been added to class.", "data": serializer.data },status=status.HTTP_200_OK) # else: print("iam else") return Response(serializer.data) My serializer: class TeacherSerializer(serializers.ModelSerializer): students_in_class = serializers.PrimaryKeyRelatedField( read_only= True ) address = serializers.CharField(required=False) # user = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Teacher fields = ["address","students_in_class"] # fields = '__all__' def update(self, instance, validated_data): instance.address = validated_data.get("address") instance.save() stu = validated_data.get("students_in_class") print(stu) if stu is not None: print("iam stu") instance.students_in_class.add(stu) instance.save() super(TeacherSerializer,self).update(instance, validated_data) return instance Here I have … -
Django health check for urls
how can I display the health status of different urls(302,200 etc.) in an html page in my django project? for example; EXAMPLE -
Django Rest framework - how to handle a serializer instance?
I have a API view in place where where I first want to create a new user (already working) and second I want to return the new created user object (Not working). views.py @api_view(['GET',]) @authentication_classes([JSONWebTokenAuthentication]) @permission_classes([AllowAny]) def user(request): if request.method == 'GET': serializer = UserSerializer(request.user) return JsonResponse(serializer.data, safe=False) @api_view(['POST']) @permission_classes([AllowAny]) def user_create(request): exception_handler = UserUnavailable success_handler = UserCreated if request.method == 'POST': creation_serializer = CreateUserSerializer(data=request.data) user_serializer = UserSerializer(data=creation_serializer.instance) try: if creation_serializer.is_valid(raise_exception=True): creation_serializer.save() #print(user_serializer) if user_serializer.is_valid(): return JsonResponse({"status_code": success_handler.status_code, "default_detail": success_handler.default_detail, "default_code": success_handler.default_code, "user_object": user_serializer }, safe=False) except APIException: return JsonResponse({"status_code": exception_handler.status_code, "default_detail": exception_handler.default_detail, "default_code": exception_handler.default_code }, safe=False) please also have a look at my UserSerializer here: class UserSerializer(serializers.ModelSerializer): id = serializers.PrimaryKeyRelatedField(queryset=User.objects.all()) class Meta: model = get_user_model() fields = ('id', 'user', 'avatar_url', 'avatar_tn_url') read_only_fields = ('id', 'user') Error I'm running into: AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>` When I print(user_serializer) I see something like this: UserSerializer(data=None): id = PrimaryKeyRelatedField(queryset=<QuerySet [<User: adasc3f4dvdvddw>, <User: dvsdvsdvsdv>, <User: Uaw3wdvdaw>, <User: pweof55>, <User: 123555>, <User: testuser48>, '...(remaining elements truncated)...']>) user = CharField(label='Username', read_only=True) avatar_url = ReadOnlyField() avatar_tn_url = ReadOnlyField() Internal Server Error: /api/v1/user/create Thanks in advance -
Django Q: Async task re-queuing and re-executing repeatedly after completion
I am working on a small personal Django project that is currently being tested on Heroku and have run into an issue with Django Q (the async task scheduler, not the database related Q library) and Redis (currently using Heroku Redis). https://github.com/Koed00/django-q https://django-q.readthedocs.io/en/latest/ Background The challenge I was trying to solve by using Django Q was to offload a long-running process (in this case a series of GIS queries that are ultimately saved to the database). I used a post_save signal to trigger this event in the following manner: Save "ScreeningA" model (basic site info) Trigger post_save signal to run "screen_by_x" function Within the signal function, run the "async_screening" Django Q task (in an attempt to prevent blocking the User while this runs) When async task is complete, save "ScreeningB" model (more complex site screening info) Everything functions correctly and both models are saved into the database. However once this process has been completed, the task appears to re-queue and re-executes the same task indefinitely. I've tried adjusting the Q_CLUSTER settings in a variety of ways (from the docs and other stackoverflow questions) and the same issue continues to occur. Code Procfile web: gunicorn projectname.wsgi worker: python manage.py qcluster settings.py … -
How to paginate other model in class view?
Is there way to paginate another model in class based view in django? I have code like this. I would like to paginate comments is it possible? class ShopDetailView(VisitCounter, DetailView): model = Item template_name = 'shop/detail.html' context_object_name = 'item' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = Comment.objects.filter(comment_item=self.object) context['form'] = CommentCreationForm() return context -
How do I add a Plotly figure factory annotated heatmap to a PDF without it looking blurry?
Thank you in advance for all the help. I am making a website with Python and Django and using Plotly and ReportLab to display heatmaps. The issue is I am struggling to have the graphs not look blurry when I add them to a PDF file. Currently, the user can choose many heatmaps to be displayed. Once chosen they are then displayed on a webpage where the graphs look perfect. It isn't until the user downloads a PDF of all the graphs. It is in the PDF where the graphs look blurry. I have tried to change the size and scale but have had no luck. This is how I create the heatmap: fig = ff.create_annotated_heatmap( z, annotation_text = well_numbers, text = hover_info, colorscale = colorscale, font_colors = ['black',], hoverinfo = 'text') Here is how I convert the heatmap to an image in order to add them to a pdf file: TrayLayoutView.graph_pdf_list.append(fig.to_image(format='png')) Lastly, here is how to I make the pdf and add all the graph images to it (with ReportLab): height = width = 700 x = 50 y = -30 # creates 'page' where to display the graph page = canvas.Canvas(response, pagesize=landscape(letter)) page.setTitle(pdf_name) # iterates all the graphs … -
Job "WrappedAPIView raised an exception. TypeError: view() missing 1 required positional argument: 'request'
I used apscheduler to run a job that calls the function UserViewSet() every 5 seconds. views.py @api_view(['GET']) def UserViewSet(self): usersData=UserSerializer(UserDetail.objects.all().order_by('name'), many=True) return Response(usersData.data) alerts_scheduler.py from apscheduler.schedulers.background import BackgroundScheduler from .. import views from rest_framework.request import Request def start(): scheduler=BackgroundScheduler() scheduler.add_job(views.UserViewSet, 'interval', seconds=5) scheduler.start() But I keep getting "Job "WrappedAPIView raised an exception.TypeError: view() missing 1 required positional argument: 'request'" everytime I run my application. The project structure is something like this: AppBackend app_scheduler __init__.py alerts_scheduler.py views.py -
Django Pass value from dropdown menu to view
I wrote an password generato and I want that the user can customize the length. How can I pass the value from the dropdown menu in the template to my views so I can create the password in the correct length. Here is my views.py now: def view_passwordgenerator(request): characters = list(string.ascii_letters + string.digits + "!@#$%^&*()") random.shuffle(characters) length = 10 password = [] for i in range(length): password.append(random.choice(characters)) random.shuffle(password) pw = ("".join(password)) context = {'password': pw, 'length': length} return render(request, 'home/passwordgenerator.html', context) -
Django AWS RDS Postgres TTFB too slow
I have a Django app that uses two databases. One database is hosted on AWS, that I use to manage the users (users email and password). Then there is a second db that is using sqlite3 that is stored in the users laptop (local database). The app is ran locally (not hosted on a server). The only query that is done for the database hosted on AWS, is when the user logins. After that, all the queries are down on the local database. The local database has no relation to the database hosted on AWS. I don't know why but when I use the database hosted on AWS I get a high TTFB. Does anyone know how I can reduce this time? Oddly enough if I use a local data instead of the one running on AWS I get way faster TTFB. Thanks! -
Install Django Taggit Inside Another App?
I am using Django taggit. Initially, I created a tags app and customized taggit slightly. It's not a lot of code and doesn't warrant it's own app (in my opinion) so I want to move the tags code to another app (let's call it content). from content.utils import slugifier class Tag(TagBase): """This is a replacement class for the Taggit "Tag" class""" class Meta: verbose_name = _("tag") verbose_name_plural = _("tags") app_label = "tags" def slugify(self, tag, i=None): slug = slugifier(tag) if i is not None: slug += "-%d" % i return slug class TaggedItem(GenericTaggedItemBase, TaggedItemBase): # This tag field comes from TaggedItemBase - CustomTag overrides Tag tag = models.ForeignKey( Tag, on_delete=models.CASCADE, related_name="%(app_label)s_%(class)s_items", ) class Meta: verbose_name = _("tagged item") verbose_name_plural = _("tagged items") app_label = "tags" index_together = [["content_type", "object_id"]] unique_together = [["content_type", "object_id", "tag"]] class Content(PolymorphicModel): ... tags = TaggableManager(through=TaggedItem, blank=True) My Problem When I go to makemigrations, I get this error: (venv) C:\Users\Jarad\Documents\PyCharm\knowledgetack>python manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: content.Content.tags: (fields.E300) Field defines a relation with model 'Tag', which is either not installed, or is abstract. I think this error message is pretty clear and good. My app content has a model named Content which has … -
Django ORM Left Join onto same table
I have a custom permissions system in a django project that can link any user to any specific model instance to grant permission on that object. It is more complex than this, but boiled down: class Permission(models.Model): user = models.ForeignKey(User) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') I want to query for all permissions for any user, that are linked to the same content_object(s) that a particular user has been granted permission(s) on. Phrased differently, the user in question wants to see who else has permissions on any of the same objects that they do. In SQL, the following does the trick: SELECT perm1.* FROM app_permission perm1 LEFT JOIN app_permission perm2 ON perm2.user_id = 12345 AND perm1.content_type_id = perm2.content_type_id AND perm1.object_id = perm2.object_id WHERE perm2.id IS NOT NULL; Is it possible to achieve this in the django ORM? -
How can create/set a celery task to be executed in an unknown moment in the future?
I'm using celert tasks and python in my app. I want set or create a celery task to be excecuted in the future, but I don't know yet the exact moment, and I want to have the task id already. How can I do that? -
Django Formset `extra` field value take huge time to load the page
I have 320 form_cell-s in my webpage. Each form_cell is clickable and associated with a single Django formset. Each of the cells of the routine is acting as a form of the formset. So there are no add form button as you see. User can fill up any form_cell at any time and put necessary information. In views.py I declare the formset like below. ClassFormSet = modelformset_factory( Class, max_num=320, extra=320, can_delete=True ) My Class model has total 5 fields. And in my template I have to render all forms like this. <div hidden id="routineForm" > {{ formset.management_form }} {% for form in formset %} {{ form|crispy }} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endfor %} </div> Problem So, here what I understand is Django is rendering all of my 320 forms at a time and this is hugely slowing down loading my webpage. What steps should I take to save my webpage from loading for long time. -
Couldn't find reference 'path' in imported module
I have tried importing the files but I'm getting the same error,can someone help me out? It does allow to import path from urls. Django version: 3.2.8 Python version: 3.9.2 The ss is attached below. importerror. -
Do Arithmetic Operations in Django Model itself
I want to subtract two model fields in the model itself. Example : class Purchase(models.Model): name = models.CharField(max_length=80, unique=True) quantity = models.IntegerField(max_length=100, null=True) scheme = models.IntegerField(max_length=100, null=True) rate = models.IntegerField(max_length=100, null=True) discountPercent = models.IntegerField(max_length=100, null=True) discount = models.IntegerField(max_length=100, null=True) gst = models.IntegerField(max_length=100, null=True) value = models.IntegerField(max_length=100, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) product_image = models.ImageField(upload_to='product_image/', null=True, blank=True) FinalPrice = .....? class Meta: ordering = ('-date_created',) def __str__(self): return self.name Here I want to subtract field name "rate" and "discountPercent" and store its result in a new field named "FinalPrice". I tried to do it in views but I want to it in model itself. Please Guide me for this. -
DJango: I have an account in the database, but writes about its absence
Django error: django.contrib.auth.models.User.DoesNotExist: User matching query does not exist. Views: def create_child_comment(request): user_name = request.POST.get('author') current_id = request.POST.get('id') text = request.POST.get('text') user = User.objects.get(username=user_name) content_type = ContentType.objects.get(model='post') parent = Comment.objects.get(id=int(current_id)) Comment.object.create( user=user, text=text, content_type=content_type, object_id=1, parent=parent, ) return render(request, 'base.html') Models: class Comment(models.Model): user = models.ForeignKey(User, verbose_name='Author', on_delete=models.CASCADE) text = models.TextField(verbose_name='Text comment') parent = models.ForeignKey( 'self', verbose_name='Parent comment', blank=True, null=True, related_name='comment_children', on_delete=models.CASCADE, ) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() timestamp = models.DateTimeField(auto_now=True, verbose_name='Data create comment') html: data = { user: ' {{ request.author.username }}', parentId: parentId, text: text, id: id, csrfmiddlewaretoken: csrftoken, } $.ajax({ method: "POST", data: data, url: "{% url 'comment_child_create' %}", success: function (data) { window.location.replace('/post-comments') } }) I don't understand what is wrong, I created a parent comment - there are no problems with it, it takes the publisher's account from the database and everything is fine, but when I try to create a child comment, it swears that this account allegedly does not exist. But this is unreal.. -
Filtering by query params in many to many relationship using drf
I have two models: class Book(models.Model): id = models.CharField(verbose_name="unique id", primary_key=True, max_length=256) title = models.CharField(max_length=256) published_date = models.CharField(max_length=128, blank=True, null=True) average_rating = models.IntegerField(blank=True, null=True, default=None) ratings_count = models.IntegerField(blank=True, null=True, default=None) thumbnail = models.URLField(verbose_name="thumbnail url", null=True, blank=True, default=None) class Author(models.Model): name = models.CharField(null=True, blank=True, max_length=256) books = models.ManyToManyField(Book, related_name='authors') What i want to achieve is that i want to filter api queries by using query params like this: 127.0.0.1/books?author='something' So my param is something in that case. I want to filter by names of authors and check if there are books that have relationship with this authors. Also it is important that there could be more than just one param at the time like this: ?author='something1'&author='something2' I have no idea how to achieve this. I'm trying with default filtering using get_queryset function in generic classes of DRF, but have no idea still. -
Django Caching when using @login_required
I'm using the decorator @login_required to only show the pages when a user is authenticated. However, I noticed my DB (hosted on AWS) is a bit slow because of this request. Every time the user goes to a new page and the decorator @login_required is called, it makes a query to the DB. I would like to cache this, so that the it's not necessary to check all the time. How can I achieve this? Thank you! -
Pass Django Choices or Foreign Key data to Vue 3
I have the following code: from django_countries.fields import CountryField .... class Book(models.Model): country = CountryField() authors = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='instances') cover = models.CharField(choices=BOOK_COVER_CHOICES, max_length=64) .... The regular Django serializer would display the fields in the Django API as dropdowns. Is there a way to get that information straight from the same Django API view and use it in Vue 3? Or do I have to perform Vue->Django API request for each field to get the needed information?