Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
'NoneType' object is not iterable - pyModbusTCP.client
I am making a program in django python that reads tags from a plc by modbus, the program reads a table where the ip addresses and the addresses of registers are found, it makes a loop and in each turn it inserts an address of a new register. Everything works perfectly in the first round when reading the first record, but the problem occurs when it analyzes the second record in the table with the loop, it returns 'None', which I do not understand since those records have already been individually validated and if they have as such a value, even running the same code and reading an individual tag if it works, the error occurs when I want to read several tags at the same time from a table with a loop. I use read_holding_registers to read the records and I use the library: from pyModbusTCP.client import ModbusClient This is my code: while True: try: queryset_modbus = tagopc_link_device.objects.filter(tag_type='MODBUS').values_list('id', 'tag_name', 'tag_type', 'source_ip_address', 'source_ip_port', 'register_len', 'modbus_type', 'device_id', 'digitalinput_id') if queryset_modbus: utility.logInfo('modbus', 'Reading Tags from model - modbus', "INFO") try: for row in queryset_modbus: #Parameters ... tag = row[1] modbusAddress = int(tag) - 1 longitud = row[5] # Parameters Modbus ... modbus … -
Cannot access the foreignkey data in datatables
I have provided the javascript below. Please note the one with name "teacher". This teacher is basically a foriegn key. However when I try to console.log the row, it doesnt show me that particular array value as an object or the data returned as an object and instead it returns a string since it uses def __str__ on django models. Hence im not able to get the particular value, i.e teacher.first_name or in this case data.first_name P.S. Im using django-datatables-view for providing the ajax url. $(document).ready( function () { $('.table').DataTable({ "columnDefs": [ { name: 'date_created', orderable: true, searchable: true, targets: [0], }, { name: 'name', orderable: true, searchable: true, targets: [1], }, { name: 'email', orderable: true, searchable: true, targets: [2], }, { name: 'phone', orderable: true, searchable: true, targets: [3], }, { name: 'course', orderable: true, searchable: true, targets: [4], }, { name: 'remarks', orderable: true, searchable: true, targets: [5], }, { name: 'teacher', orderable: true, searchable: true, targets: [6], render: function(data, type, row){ return data.first_name + "<br>(" + data + ")" } }, { name: 'is_enrolled', orderable: true, searchable: true, targets: [7], render: function(data, type, row){ if (data === "True"){ return "<i class='fa fa-check text-success text'></i>" } else{ … -
JOIN ILLUMINATI SECRET SOCIETY +27710571905
JOIN ILLUMINATI SECRET SOCIETY +27710571905 in South Africa, Uganda, Zambia, Zimbabwe, UK, USA, Canada, Malawi,Botswana, Swaziland, South Sudan and in cities like Sasolburg,Limpopo,Witbank,Standarton,Secunda,Middelburg,Johannesburg,Vanderbijlpark,Secunda,Soweto Cape Town,Burgersfort, Polokwane,Thohoyandou, phalaborwa, mokopane, bochum, lebowakgomo, mankweng, Seshego, dendron, Giyani, Lephalale, musina,Alexandra Johannesburg,New york,Ohio,California,New mexico,London,Manchester,Liverpool,Kampala,Kigali,Lenasia, Midrand, Randburg, Roodepoort,Sandton, Alberton ,Germiston, Benoni, Boksburg ,Rakpan Daveyton, Duduza ,Edenvale, Impumelelo, Isando Katlehong, Kempton Park, KwaThema ,Nigel Reiger,Park Springs, Tembisa, Thokoza, Tsakane, Vosloorus ,Wattville ,Atteridgaeville,Centurion,Hammanskraal, Irene, Mamelodi ,Pretoria,Soshanguve,Boipatong, Bophelong,Evaton,Sebokeng, Sharpeville,Vereeniging, Meyerton,Heidelberg,Ratanda,Bronkhorstspruit,Ekangala,Kungwini,Bronberg,Cullinan,Refilwe,Zithobeni,Carltonville,Khutsong,Kagiso,Kromdraai,Krugersdorp,Magaliesburg, Muldersdrift, Mohlaken,Randfontein,Bekkersdal,testonaria,Kimberley,Upington,Kuruman,Sprinbok,Kathu Ritchie Pietermaritzburg,Bellville,Bloemfontein. If you're ready to join the great brotherhood of illuminati secret society kingdom today the door is open for new members. Headquarters at South Africa and USA kindly inbox the Great brotherhood illuminati Prof Bob. Email address now bobspells96@gmail.com Or contact him on whats-app mobile now +27710571905 for more information. https://illuminatiwithprofbob.blogspot.com/ A cash price reward of $100 million US dollars after your initiation. 2. A new sleek dream car will be given to you after you have received your benefit. 3. A dream House bought in the country of your own choice. 4. One Month holiday (fully paid) to your dream tourist destination. 5. One Year Golf Membership Package. 6. A V.I.P treatment in all Airports in the world. 7. A total lifestyle change. 8. … -
How to serve WASM files in Django
I compiled my C file to wasm using: emcc main.c -s USE_SDL=2 -O3 -s WASM=1 -o main.js I'm only using WASM to manipulate a canvas. There is no JS code other than the "glue" js code. I now have a directory (outside of Django, just somewhere in my Documents folder) with these files: - home.hml - main.c - main.js - main.wasm Which I can serve using whatever webserver eg python3 -m http.server 8000 --bind 127.0.0.1 And view the animation in the browser. And it works. No problems so far. I want to serve home.html from Django now. My URLs.py has: path('', views.home, name='home'), and views.py has: def home(request): context = {} return render(request, 'app/home.html', context) I have copied home.html to app/templates/app I then copied main.js to app/static/app Then I modified home.html to replace: <script src="main.js"></script> With <script src="{% static 'app/main.js' %}" type="text/javascript"></script> I don't know what to do with main.wasm. Should this also go into the static folder or into the project root? Do I need to add an explicit import somewhere for this? How can I get my home.html to behave the same as it was with a simplehttpserver, but when being served from Django? Please note that all … -
Why isn't my page redirecting after I submit the form or refresh the page in Django?
I am working on a Django application but I am not getting the desired results. The create_job page is not rendering after I submit the the form or refresh the entire page. This is the create_job_page view def create_job_page(request): current_customer = request.user.customer if not current_customer.stripe_payment_method_id: return redirect(reverse('customer:payment_method')) # return render(request, 'customer/create_job.html') # Filtering create_job = Job.objects.filter(customer=current_customer, status=Job.CREATING_STATUS).last() step1_form = forms.JobCreateStep1Form(instance=create_job) if request.method == 'POST': if request.POST.get('step') == '1': #If it's form one step1_form = forms.JobCreateStep1Form(request.POST, request.FILES) if step1_form.is_valid(): creating_job = step1_form.save(commit=False) # Adding current customer to the form creating_job.customer = current_customer creating_job.save() return redirect(reverse('customer:create_job')) return render(request, 'customer/create_job.html', { "step1_form": step1_form }) This is the HTML code <b>Create a Job</b> <div class="tab-content" id="pills-Content"> <div class="tab-pane fade" id="pills-info" role="tabpanel" aria-labelledby="pills-info-tab"> <h1>Item Info</h1> <form method="POST" enctype="multipart/form-data"> <b class="text-secondary">Item Information</b></br> <div class="card bg-white mt-2 mb-5"> <div class="card-body"> {% csrf_token %} {% bootstrap_form step1_form %} </div> </div> <input type="hidden" name="step" value="1"> <button class="btn btn-primary" type="submit">Save & Continue</button> </form> </div>