Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When I filter I need to request.GET.value to be selected
I have to filter some data so I need to use a select field but when I submit the form the result disappears. I have to selected the value that is choice previous ` <label class="text-secondary">Discount Type</label> <select name="discount_type" class="form-control" > <option value="" class="text-center" >Select Type</option> {% for i in type %} <option {% if i.0 == request.GET.status %} selected {% endif %} value="{{ i.0 }}" >{{ i.1 }} </option> {% endfor %} </select>` -
Django Heroku deployment not serving static image files with Whitenoise
My css and js static files are working but my images are not loading. whitenoise==6.2.0 works in development but not with debug off.. MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] DEBUG = False STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" django_heroku.settings(locals()) URLS.PY if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) some template {% load static %} <center><img class="rounded" src="{% static 'images/sm_logos/about-1.png/'%}" style="height:300px; width:300px;"></center> C:\Users\Boss Chris\Desktop\Projects\CBlog\CBlog_project\blog\static\images\sm_logos\about-1.png appreciate your help.. been at this since yesterday and maxed out on pushups.. cant do anymore.. tried putting my static files in S3 too.. doesn't work but i'll try again tmrw if there's no solution -
Search in multiple models in Django
I have many different models in Django and I want to search for a keyword in all of them. For example, if you searched "blah", I want to show all of the products with "blah", all of the invoices with "blah", and finally all of the other models with "blah". I can develop a view and search in all of the models separately, but it's not a good idea. What is the best practice for this situation? -
DjangoCMS - Render database data to html
I'm testing out the DjangoCMS but I cannot understand how to create custom plugins that enable rendering data out of the database. I'd like to create a plugin that shows all the users for example but I can't understand how to pass the data into the HTML file. I followed the DJangoCMS documentation to create a custom plugin that shows the guest name, I've already tried to add users = User.objects.all() and then pass it to the render function but I receive an argument exception because the render function does not allow so many arguments, so what's the approach in DJangoCMS? models.py from cms.models.pluginmodel import CMSPlugin from django.db import models class Hello(CMSPlugin): guest_name = models.CharField(max_length=50, default='Guest') cms_plugins.py from cms.plugin_base import CMSPluginBase from cms.plugin_pool import plugin_pool from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import User from .models import Hello @plugin_pool.register_plugin class HelloPlugin(CMSPluginBase): model = Hello name = _("Hello Plugin") render_template = "hello_plugin.html" cache = False def render(self, context, instance, placeholder): context = super().render(context, instance, placeholder) return context -
Additional borders and wrong display when using class="d-none d-sm-block d-md-block" bootstrap
I need to hide some of the columns of my table on mobile. I use d-none d-sm-block d-md-block to do that on small and medium screen sizes. This is my code: <table border="1px" class="table table-hover"> <thead class="thead-dark"> <tr> <th class="d-none d-sm-block d-md-block">Fund</th> <th>Why them</th> <th>How to donate</th> </tr> </thead> {% for fund in funds_list %} <tr> <td class="d-none d-sm-block d-md-block"> <a href={{ fund.url }} target="_blank" rel="noopener noreferrer">{{ fund.name }}</a></td> <td> {{ fund.description|safe }}</td> <td> <a href={{ fund.bank_details }} target="_blank" rel="noopener noreferrer" class="btn btn-primary stretched-link">Go to website</td> </tr> {% endfor %} </table> When I'm not additing these classes, my table looks fine: However, after I add this class="d-none d-sm-block d-md-block", some strange border appears around a column I want to hide: -
Django rest-framework , Serializer returning assertion Error
I'm extending my current model to have some common properties from other base classes. Before extending the model, everything was working fine. But after extending, I'm getting the assertion error while performing put and post Operation. I tried my best to resolve it by my own. But not getting where it is going wrong. Can anyone help me on this? Please find my model and serializers below. basemodel.py from django.db import models class BaseModel(models.Model): created_at=models.DateTimeField(auto_now=True) updated_at=models.DateTimeField(auto_now=True) class Meta: abstract = True softdelete.py from django.db import models class SoftDeleteModel(models.Model): is_deleted = models.BooleanField(default=False) def delete(self): self.is_deleted = True self.save() def restore(self): self.is_deleted = False self.save() class Meta: abstract = True movies.py from django.db import models from cinimateApp.models.comman.softdelete import SoftDeleteModel from cinimateApp.models.comman.basemodel import BaseModel # Create your models here. class Movies(SoftDeleteModel,BaseModel): name=models.CharField(max_length=250) description=models.CharField(max_length=250) active=models.BooleanField(default=False) def __str__(self): return self.name movieSerializer.py #Model Serializer from rest_framework import serializers from cinimateApp.models.movies import Movies class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movies fields = '__all__' # fields=['id', 'name', 'description', 'active'] # exclude=['name'] # field Level Validation def validate_name(self,value): if(len(value)<3): raise serializers.ValidationError('name is too short') return value #Objectlevel validation def validate(self,data): if(data['name']==data['description']): raise serializers.ValidationError('name and description should be different') return #custome serializer field name_length=serializers.SerializerMethodField() def get_name_length(self,object): return len(object.name) viws.py from … -
Combining annotation and filtering in Django for two different classes
Hi I am trying to query and count marketplaces for every infringement only for the logged in user. Essentially trying to combine these two. mar_count = Marketplace.objects.annotate(infringement_count=Count('infringement')) inf=Infringement.objects.filter(groups__user=request.user) I found a below example but this is for the same class. I have two separate classes. I am a beginner. swallow.objects.filter( coconuts_carried__husk__color="green" ).annotate( num_coconuts=Count('coconuts_carried') ).order_by('num_coconuts') -
Logic for different leave types in django rest framework for Leave management system
Actually I'm working on Hrms application in django rest framework. I've created employee details module now next part is leave management system. Actually my company policy has different leave policies like cl,sl,ml,compo off, and permissions.I'm unable to understand how to make the logic for it and and don't know where to write the logic in serializers or views? Since a newbee i find somewhat difficult. Also when a employee apply a leave it should be requested to T.L. and then should be visible to hr and manager. T.l would give permission and it all should be in application and also in email process. How to make request and approval in rest api also how to send mail using django rest api? Can anyone guide me This is the code tried class LeaveRequest(models.Model): options = ( (Cl', 'cl), (Sl', 'sl), (Ml, 'ml), (Compoff,compoff) ) choices = ( ('Approved', 'Approved'), ('Rejected', 'Rejected'), ('Pending', 'Pending'), ) user = models.ForeignKey(User, related_name="leaverequest_user", on_delete=CASCADE) employee = models.ForeignKey(Employee, related_name="leaverequest_employee", on_delete=CASCADE) type = models.CharField(choices=options, max_length=50) status = models.CharField(choices=choices, max_length=50) text = models.CharField(max_length=500) date_time = models.DateTimeField(auto_now_add=False, -
what is charset=ibm037 in http
I am new to bug bounty & StackOverflow. I watched a presentation called ''WAF Bypass Techniques Using HTTP Standard and Web Servers ' Behavior - Soroush Dalili." I need help understanding something about IBM037 and IBM500 encoding. What is 'charset =ibm037' What is 'boundary=blah' Does anyone know any encoder for IBM037 & IBM500? I googled it, but I couldn't find anything. -
How to convert string with any date format to %m/%d/$Y in Python
I have a csv with with dates. The dates have inconsistent formatting and I want it all to change to mm/dd/yyyy upon importing. Is there a way to do it? I know about strptime but that requires a second argument for the format of the given date. -
Django Rest Framework: Upload file to another server via Django
I am building an API with DRF. The purpose of this API is to take user input and post the input to a different server via that servers API. There is also an option for users to upload file e.g. image. But the problem I am facing is that the second server is receiving the file as a blob of text like ����\x00\x10JFIF\x00\x01\x01\x01\x01,\x01,\x00\x00��\x0cXICC_PROFILE\x00\x01\x01\x00\x00\x0cHLino\x02\x10\x00\x00mntrRGB XYZ \x07�\x00\x02\x00\t\x00\x06\x001\x00\x... The second server is also build with Django. Here is the code for the first server that user has direct interaction with: requests.patch( f"https://second-server.com/api/user-upload/{self.kwargs.get('user_id')}/", data=request.data, ) The request.data contains the form data including the file that user is uploading. How can I save image to second server through the first server that user has direct interation with. -
Unable to find locate folder in python directory. Getting the error: ModuleNotFoundError: No module named 'config'
I am trying to import a .py file in my project using relative paths but I'm having some issues. This is my project structure: django_misinfo -config --init.py --definitions.py -scripts --scraper.py This is my definitions.py: import os ROOT_DIR = os.path.realpath(os.path.join(os.path.dirname(__file__), '..')) and this is my scraper.py: import os from config.definitions import ROOT_DIR However, I get an error: ModuleNotFoundError: No module named 'config'. I'm not sure what could be causing this, I've tried everything I can think of, including moving the structure of the folders around. It seems like a simple solution but I'm not sure what I'm doing wrong. Thank you for your help. -
Robots.txt returns 404 instead of displaying text
Problem When trying to request my robots.txt file at website.com/robots.txt, I always receive a 404 error. Files config > urls.py from django.conf import settings from django.contrib import admin from django.urls import path, include, re_path from django.views.generic import TemplateView from django.conf.urls.static import static from config import views from django.conf.urls import handler404, handler500, handler403, handler400 handler404 = views.handler404 handler500 = views.handler500 urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('accounts/', include('django.contrib.auth.urls')), path('', include('pages.urls')), path('plants/', include('plants.urls')), path('robots.txt',TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), ] config > views.py from django.http import JsonResponse, Http404, HttpResponse from django.shortcuts import render def handler404(request, exception=None): return render(request, '404.html', status=404) def handler500(request): return render(request, '500.html', status=500) templates > robots.txt User-Agent: * Disallow: /admin/ Disallow: /accounts/ Parts of my folder structure that may be helpful to know project | |---config | | | |---urls.py | |---views.py | |---templates | |---pages | |---about.html | |---contact.html | |---404.html |---robots.txt I've also tried using only exception instead of exception=None inside of my handler404. I've tried to move the robots.txt views and urls into my pages app with the robots.txt within the pages template folder. I've tried removing the content_type=text/plain from the url pattern. I've read through several different tutorials and I'm not sure what I'm doing wrong. -
Django: managing permissions, groups and users during data migrations
Problem During a data migration, I'm trying to create a django.contrib.auth.models.Group and some Users and then attaching said group to one of the users. Problem I'm finding (other than the permissions still not being created, but I've already found a solution to that), is that for some reason the many-to-many manager doesn't seem to be working as it should (?). Basically what I'm trying to do is something like: group = Group.objects.create(name="manager") # user creation... user.groups.add(group) However, I get the following error: TypeError: Group instance expected, got <Group: manager> Whenever I try to replicate this in the Django shell, it works no problem. It only fails when in a migration. Any ideas? Things I've tried and other information I've tried both populating the m2m relation through the User related manager and the Group related manager, that is, user.groups.add(group) and group.user_set.add(user). Both give me a similar error. Just partially related, but just so I have the permissions needed, I have this first in my migration: for app_config in apps.get_app_configs(): app_config.models_module = True create_permissions(app_config, verbosity=0) app_config.models_module = None The group is supposedly created properly. Given that I create the groups and the users in different helper functions, I actually grab the group … -
How to handle FileNotFound error when using img tag using mark_safe in django admin
I am importing images into AWS S3 using django-storages. However, if Django admin does not have the corresponding image in S3, Admin would like to issue a FileNotFoundError to correct the S3BotoStorage object or fix the underlying problem to handle the error. admin/hospital.py class HospitalAdmin(OrderedInlineModelAdminMixin, IdFieldIncludedModelAdmin): list_display = ("name", "tags_comma_separated", "created_at") list_display_links = ("name",) list_filter = [TagFilter] fieldsets = ( (None, {"fields": ("user",)}), ( None, { "fields": ( "logo_image", "logo_image_width", "logo_image_height", "logo_image_preview", "name", "description", "address", "longitude", "latitude", "near_station_name", "phone_number", "sms_phone_number", ) }, ), ( None, { "fields": ( "created_at", "updated_at", ) }, ), ) readonly_fields = [ "logo_image_width", "logo_image_height", "logo_image_preview", "created_at", "updated_at", ] ... # FileNotFound Error occurs in the lower part @display(description="preview log image") def logo_image_preview(self, obj): return mark_safe( '<img src="{url}" width="{width}" height="{height}" />'.format( url=obj.logo_image.url, width=obj.logo_image.width, height=obj.logo_image.height, ) ) I added a try/except statement to the error part to generate a correct error, but it doesn't seem to solve the fundamental problem try: return mark_safe( '<img src="{url}" width="{width}" height="{height}" />'.format( url=obj.logo_image.url, width=obj.logo_image.width, height=obj.logo_image.height, ) ) except FileNotFoundError as e: return str(e) -
Django NoReverseMatch Error while testing: 'testapp' is not a registered namespace
Hii i try to test my url easily with TestCase and reverse, but i get NoReverseMatch error. urls.py from django.urls import path from . import views app_name = "testapp" urlpatterns = [ path("", views.index, name="index"), ] tests.py from django.test import TestCase from django.urls import reverse class BasicTests(TestCase): def test_index(self): response = self.client.get( reverse('testapp:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "Hello World") And the error: ERROR: test_index (mysite.tests.BasicTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "django\myvenv\lib\site-packages\django\urls\base.py", line 71, in reverse extra, resolver = resolver.namespace_dict[ns] KeyError: 'testapp' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "django\mysite\mysite\tests.py", line 7, in test_index reverse('testapp:index')) File "django\myvenv\lib\site-packages\django\urls\base.py", line 82, in reverse raise NoReverseMatch("%s is not a registered namespace" % key) django.urls.exceptions.NoReverseMatch: 'testapp' is not a registered namespace What am I missing here? -
Django PasswordResetView does not work for inactive users
I have a simple django app where users can create and login to their accounts. When a user is registering for a new account, the user object is created and saved in the database with the is_active flag set to false. Once the user clicks the confirmation email, the user object has its is_active flag set to true. I have built out a password reset flow using Django's views: PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, and PasswordResetCompleteView. Everything works as expected unless I am trying to reset the password for an account which has not yet been activated (is_active == False), in which case, the reset password email is never sent to the user. The edge case I am considering here is for a user who created an account, and never clicked the registration link which expires after 72 hours, and thus have a user account which exists but is not active. Then the user wants to get a new registration link, and to do so I require a user to enter their username and password (so that no malicious actors can spam a random users email inbox with new registration link emails). If the user has since forgotten their password, they are … -
Displaying Countdown in Django Loop not working properly when clicked
Hi I have the following Countdown in Javascript, which is inside a Django for loop and it is showing more than once. In my current situation when I click on any of the countdown start button only the first one works. I want to be able to click on any of them and each on of them work separetly when clicked not simultaneously. here is the Script: <button id="myBtn" onclick="myFunction()" type="button" class="btn btn-warning"> <i class="fa-solid fa-play" style="margin-right:2px"></i> <span id="demo" class="countdown-live" style="text-align:center;"></span> </button> <script type="text/javascript"> var countDownDate = new Date(Date.now() + 45000).getTime(); var x = setInterval(function() { var now = new Date().getTime(); var distance = countDownDate - now; var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); document.getElementById("demo").innerHTML = minutes + " : " + seconds + " "; if (distance < 0) { clearInterval(x); document.getElementById("demo").innerHTML = 'Done'; } }, 1000); </script> My question: How to click on any of the countdown buttons inside the django … -
How to show all the tags related to a publication in a list of publications filtered by a tag in Django?
Consider following models: # models.py from django.db import models class Tag(models.Model): name = models.CharField() number_of_publications = models.PositiveIntegerField() class Publication(models.Model): text = models.TextField() tags = models.ManyToManyField(Tag) # urls.py from .views import publications_tagged urlpatterns = [ path('/questions/tagged/<str:name>', publications_tagged) ] # views.py from .models import Tag, Publication from django.shortcuts import get_object_or_404, render def publications_tagged(request, name): tag = get_object_or_404(Tag.objects.prefetch_related('tags_set'), name=name) return render(request, 'myapp/tagged_questions.html', {'tag': tag}) Ok, so when we'd go to a template and make a for-loop that will create a representation of every publication and show appropriate tags of it, Django would make a database call for every publication to fetch all the tags the publication has, meaning: Iteration x of tag.tags_set -> check what tags match with publication X. Of course, we can just not show tags and everything will work like magic (utilizing prefetch_related), but that's not what we want :) How could we do something similar in Django? What we want is some kind of optimized way to achieve such a result, because stackoverflow renders 15 items really fast, which makes me think they do not do it the monkey way that Django does by default. This is what html might look like P.S. My problem doesn't quite sound like … -
How can I prevent row duplicates in Django when no field is unique?
Upon saving an object, is there a simple way to prevent duplication when the combination of all the fields together have the same data? The unique=True parameter doesn't seem to help here, because individually any of the data could be duplicated, but never all of them at the same time. If statement with several and conditions does not seem to me like a smart way so I'm looking for a better approach. Does Django provide it? All I could find was related to one field or other being duplicated. Ex.: if Model.objects.filter(field_A=source_A).exists() == True and Model.objects.filter(field_B=source_B).exists() == True and Model.objects.filter(field_C=source_C).exists() == True: continue else: *save object* -
Django rest framework write / update nested serializer
How to write and update nested serializer in drf. I have two models. Just an example below. Class Account (AbstractBaseUser): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=100, unique=True Class USerProfile(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) address_line_1 = models.CharField(max_length=100) address_line_2 = models.CharField(max_length=100) phone = models.IntegerField(null=True) already have an AccountSerilaizer for Registration view class AccountSerializer(ModelSerializer): confirm_password = CharField(write_only=True) class Meta: model = Account fields = ["first_name", "last_name", "email", "password", "confirm_password"] extra_kwargs = { "password": {"write_only": True}, } def validate_email(self, value): qs = Account.objects.filter(email__iexact=value) if qs.exists(): raise ValidationError("Email already exists") return value def validate(self, attrs): if attrs.get("first_name") == "" or attrs.get("last_name") == "": raise ValidationError("Names cannot be blank") return attrs def validate_password(self, data): if len(data) < 8: raise ValidationError( "Password should be atleast 8 digits or characters or letters" ) return data def validate(self, data): if data["password"] != data.pop("confirm_password"): raise ValidationError({"error": "Passwords donot match"}) return data def create(self, validated_data): user = Account.objects.create_user(**validated_data) return user def update(self, instance, validated_data): instance.first_name = validated_data.get("first_name", instance.first_name) instance.last_name = validated_data.get("last_name", instance.last_name) instance.email = validated_data.get("email", instance.email) instance.save() return instance So UserProfile is FK to Account, how to update/write UserProfile and how to get request.user inside serializer during create/update method and I'm using JWT Authentication. There is a third … -
STL viewer on web browser?
I developing a Django application that can upload STL. How to view the STL on a web browser? Does anyone know of anything that may be able to help? -
Django rest_framework : count objects and return value to serializer
i need to count all supporters in model and return value to serializer models.py class Supporters(models.Model): name = models.CharField(max_length=255) img = models.ImageField(upload_to="Supporters", blank=True, null=True) serializers.py class SupportersSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() supporters_count = serializers.SerializerMethodField() class Meta: model = Supporters fields = ("id", "name", "img", "supporters_count") def get_supporters_count(self, obj): return obj.supporters_count.count() views.py class SupportersViwe(generics.RetrieveAPIView): queryset = Supporters.objects.all() def get(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = SupportersSerializer(queryset, many=True) return Response(serializer.data) -
My function to check for ajax on a page is not working
I am making a django project where there is a search/filter dropdown for a form. I am using select2 and ajax. It isn't working, and when I try to debug with print statements, it seems that the is_ajax(request) function is not returning true. I know the is_ajax() function was deprecated in JQuery, which is why I defined it myself. However, mine doesn't seem to work either. Here is the portion my view that filters objects: @login_required def job_application_create(request): form = JobApplicationForm() if is_ajax(request): print('TESTING TESTING TESTING TESTING TESTING TESTING TESTING TESTING ') term = request.GET.get('term') companies = Company.objects.filter(name__icontains=term) response_content = list(companies.values()) return JsonResponse(response_content, safe=False) and here is the is_ajax(request) definition: def is_ajax(request): return request.headers.get('x-requested-with') == 'XMLHttpRequest' I also tried this function: def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' Here is the JS in the page that has my form: <script> $(document).ready(function () { $('#id_company').select2({ ajax: { url: "{% url 'homepage' %}", dataType: 'json', processResults: function (data) { return { results: $.map(data, function (item) { return {id: item.id, text: item.name}; }) }; } }, minimumInputLength: 1 }); }); </script> -
Making a functional contact form using django
I'm created a website for a friend. I have created a contact form which he would like people to use and the messages will directly be sent to his own personal email address. I can't seem to get it working. I'm currently testing using my own outlook account and eventually would like to be using his Gmail account. please see my code below. Any input would be greatly appreciated. I did end up getting it working using mailtrap, but as far as im aware i would need to pay to redirect to an email address of my choosing? Settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp-mail.outlook.com' EMAIL_HOST_USER = 'email@email.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 Contact.html {% extends 'portfolio/main.html' %} {% block content %} {% load crispy_forms_tags %} <!--Section heading--> <h2 class="h1-responsive font-weight-bold text-center my-4"> Contact vstheworld </h2> <!--Section description--> <p class="text-center w-responsive mx-auto mb-5"> Do you have any questions? Please do not hesitate to contact us directly. Our team will come back to you within a matter of hours to help you. </p> <!-- Wrapper container --> <div class="container py-4"> <form method="POST"> {% csrf_token %} {{form|crispy}} <div class="d-grid"> <br> <button class="btn btn-dark btn-lg" id="form-submit" type="submit"> Submit </button> …