Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pymongo + DJango admin panel
Is it possible to use the admin panel in combination with django + pymongo? error django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. this is because DATABASES is commented out in settings.py, but in the pymongo documentation it says that it needs to be commented I searched the Internet for information and couldn’t find a solution. -
python Nonetype check on custom exception handling not working
I have been running this simple code for exception handling. It runs correctly in every scenario except when there need to check for Nonetype. I have used every line of code but nothing worked for me. Below I just kept simple, can you please help me here why it is not going inside if condition.? [updated] : Placed more print statements to give more insight on the issue. It is being called like "raise CustomExcpetion(excep=e)" in django class CustomExcpetion(PermissionDenied): def __init__(self, excep, status_code=status.HTTP_400_BAD_REQUEST): message={"message": "error observed"} print ("Inside custom exception") print (excep) excepType = type(excep) print ("exception type found : ") print(excepType) if excep is None: print ("none exception found") self.detail = message print ("none exception NOT found") -
Implementing an Abstract User Class in django implemented similarly to C++?
I am sorry but since I am not really experienced with py/django that much i will be making a parallel on c++ classes. I am trying to make a User Abstract class with two childs classes User_A and User_B, I want to call a User be it A or be without differentiating between them. a c++ equivalent to that would be: User *new_user = new User_A; new_user.send_user_data(); (send_user_data being the abstract fonction) But from what i found this doesn't seem to be possible, so my next idea was to make a User model and have a field referencing either User_A or User_B, but this doesn't seems to be possible either as I would need to seperate fields for each of them, which isn't what i want. I welcome any ideas, Thank you. -
"detail": "Authentication credentials were not provided." when trying to access list view as admin. Django REST framework
I have this simple view I built using Django REST framework: class ProductListCreateAPIView( StaffEditorPermissionMixin, generics.ListCreateAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer def perform_create(self, serializer): print(serializer.validated_data) name = serializer.validated_data.get('name') description = serializer.validated_data.get('description') or None if description is None: description = name serializer.save(description=description) here is the StaffEditorPermissionMixin: class StaffEditorPermissionMixin(): permission_classes = [permissions.IsAdminUser, IsStaffEditorPermission] and here is the ProductSerializer: class ProductSerializer(serializers.ModelSerializer): edit_url = serializers.SerializerMethodField(read_only=True) url = serializers.HyperlinkedIdentityField( view_name='product-details', lookup_field='pk', ) class Meta: model = Product fields = [ 'url', 'edit_url', 'name', 'description', 'price', 'sale_price', ] def get_edit_url(self, obj): # return f"/api/v2/products/{obj.pk}/" request = self.context.get('request') if request is None: return None return reverse("product-edit", kwargs={"pk": obj.pk}, request=request) and just in case here's products.url: from django.urls import path from . import views urlpatterns = [ path('', views.ProductListCreateAPIView.as_view(), name='product-list'), path('<int:pk>/update/', views.ProductUpdateAPIView.as_view(), name='product-edit'), path('<int:pk>/delete/', views.ProductDestroyAPIView.as_view()), path('<int:pk>/', views.ProductDetailAPIView.as_view(), name='product-details'), ] and just in case here's the source urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), path('api/products/', include('product.urls')), path('api/v2/', include('rest_practice.routers')), ] so when I am logging in as admin to http://127.0.0.1:8000/admin/ and I head to http://127.0.0.1:8000/api/products/ I cannot access the product list and receiving HTTP 401 Unauthorized Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: Bearer { "detail": "Authentication … -
Django bad choice for microservices
Spring boot is considered as the most suitable choice for microservices due to it's scalability, performance and bla.. bla.. bla.. but to create microservices we have to create a new project in spring boot for each microservice. On the other hand, django consists apps (which can be used as microservices) where each app can be configured to different databases and I think django is more structured on the projects based on microservices architecture. Then why django isn't considered most suitable choice for microservices architecture compared to spring boot ?? -
I created a view for search function but it is not working. It is not filtering products
I created a search function for my Website In views.py: def search_view(request): query=request.GET.get("q") if query: products=Product.objects.filter(title__icontains=query,description__icontains=query).order_by("-date") else: products = Product.objects.none() context={ "products":products, "query":query } return render(request, 'core/search.html',context) I created a template for search products in my website and in search.html <form action="{% url 'core:search' %}" method="GET" class="search-form"> <input type="text" name="q" placeholder="Enter your product name..." class="search-input"> <button type="submit" class="search-button">Search</button> </form> But the search function is not working. I mean it is not finding product from my database Please tell me what is wrong here? -
Genetic Algorithm designed to solve a specific usecase of tsp not working
I know this is pretty vague, but im pretty much lost at this point. I've been stuck on this project for a few months now and i dont know whats the issue. Am i doing something wrong? Is GA a bad idea for this problem? Is python a bad a idea for this problem? Is it even possible? Its not even that unique, I have seen about a dozen solutions doing the exact same thing I'm doing. class Generation: class Individual: class Chromosome: def __init__( self, dates, external_id=0, zip=None, date=None, felmero: Salesmen | None = None, ): self.external_id = external_id self.dates: List[datetime] = dates self.date: datetime = date self.zip: str = zip self.felmero: Salesmen = felmero def random_date(self): if not self.dates: return None if len(self.dates) == 1: return self.dates[0] available_dates = [d for d in self.dates if d != self.date] return random.choice(available_dates) if available_dates else None def __init__(self, outer_instance, data=None): if data: self.data = [ self.Chromosome(**i.__dict__) for i in data if i is not None ] else: self.data = None self.outer_instace: Generation = outer_instance def __eq__(self, other): self.sort_route() other.sort_route() for i in range(len(self.data)): if ( self.data[i].date != other.data[i].date or self.data[i].felmero != other.data[i].felmero ): return False return True def sort_route(self): def … -
Deployed django application on nginx problems with fetching
I have a django application that deployed on ubuntu 20. It doesn't have certificate yet. When javascript fetches the backend i guess it just throws error JSON.parse: unexpected character at line 1 column 1 of the JSON data That's what i get in Chrome, but in Arc Browser everything works fine and without any errors Here is my code JS: const country_icons = document.querySelectorAll(".country-icon"); country_icons.forEach((icon)=>{ icon.addEventListener("click", (e)=>{ let id = e.target.id fetch(`get-country-info/`,{ method: "POST", body: JSON.stringify({ id : id }), headers:{"X-CSRFToken": getCookie('csrftoken') } }) .then(response => response.json()) .then(data => { let text = data[e.target.id] let modal_body = document.querySelector("#modal-body"); modal_body.innerHTML = text }) }) }) views.py def get_country(request): data = json.loads(request.body) country_name = data.get("id") response_data = {country_name : get_country_info(country_name)} return JsonResponse(response_data) everything works if i run the server with python3 manage.py runserver though I am using Django 5.0.2, DRF 9.14.0, nginx, gunicorn, ubuntu 20 -
Are RunPython function in django migrations required when squashing commits if they are only modifying existing data?
I have a django project that needs migration squashing. All of the RunPython functions are moving data from one column to another after making some change. If it was just for moving old data and does not affect newly created records, do I need it or not while squashing migrations or creating them from scratch? Here is an example: # Adding the new field migrations.AddField( model_name='approvalrequest', name='club', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='members.club'), ) # RunPython function call migrations.RunPython(migrate_membership_to_enrollment, reverse_code=reverse_migration) # RunPython function def migrate_membership_to_enrollment(apps, schema_editor): ApprovalRequestModel = apps.get_model('approval_requests', 'approvalrequest') db_alias = schema_editor.connection.alias with transaction.atomic(): requests = ApprovalRequestModel.objects.using(db_alias).all() for request in requests: club = request.membership.club request.club = club request.save() # Deleting memberhsip field migrations.RemoveField( model_name='approvalrequest', name='membership', ), You can see we are making a change and moving existing data according to it. Now that it has been done and everyone is on the latest versions of migrations, can this method be removed altogether? -
How to implement 2FA using the django-two-factor-auth package for a specific admin site within a project containing multiple independent admin sites?
As stated in the title, I am trying to implement Twilio SMS 2FA only for one of the multiple independent admin sites that I have, but I have not found any relevant documentation for this scenario and the implementation guide does not provide any info. Has anyone successfully implemented this scenario? Thank you in advance! I tried following the steps indicated in the documentation as well as following some online tutorials but they all point to how it is implemented for the default admin site and my attempts have been unsuccessful so far. -
How to deploy a django backend?
I'm very new to web development! Might be a silly question, but I have to ask.... I have a full stack web app which can run locally. The backend is in django and front end is React. May I ask how to build and deploy this project on any websites? I have tried on railway as this said, but it shows the error message like: Nixpacks was unable to generate a build plan for this app. I guess the front end is not a problem so might be the backend. Our configuration steps are a bit confusing I'll put it below: Screenshot After all these mysterious steps I can start my backend locally. Please Help!! -
Pass data to template from Database
I am learning django. My views.py is like below which is inside student app folder. from django.shortcuts import render # from .models import Student from student.models import Student # Create your views here. def home(request): student_data = Student.objects.all() context = { 'student_data': student_data } return render(request, 'index.html', context ) I am trying to get values in index.html template which is inside template folder. My code in index.html is like below. <p> {{ student_data }} </p> My code of models.py which is inside student app is like below. from django.db import models class Student(models.Model): first_name=models.CharField( max_length=100 ) last_name=models.CharField( max_length=100, blank=True, null=True ) age=models.IntegerField() But I can't see any Data in HTML using browser. -
Django error : "auth.User.groups" and "auth.User.user_permissions"
I have an Error in my Django app I have created a CustomUserModel: class CustomUserManager(UserManager): def create_student(self, username, email, password, **extra_fields): extra_fields.setdefault('is_student', True) return self._create_user(username, email, password, **extra_fields) def create_teacher(self, username, email, password, **extra_fields): extra_fields.setdefault('is_teacher', True) return self._create_user(username, email, password, **extra_fields) def _create_user(self, username, email, password, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(username=username, email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, username=None, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self.create_student(username, email, password, **extra_fields) def create_superuser(self, username=None, email=None, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_teacher(username, email, password, **extra_fields) And I have two types of users Teacher and Student: Student class Student(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = models.CharField(max_length=10) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField(max_length=254, blank=True, default='') age = models.IntegerField() student_class = models.ForeignKey(StudentClass, on_delete=models.CASCADE, related_name='students') is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_student = models.BooleanField(default=True) is_teacher = models.BooleanField(default=False) # Other fields .. objects = CustomUserManager() Teacher class Teacher(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = models.CharField(max_length=10) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) … -
Why is an "id" not from Mongodb automatically created, and how to disable it
{ "_id": { "$oid": "65ea05dbaa907e05219c0934" }, "id": 6, "title": "asd", "content": "asd", "author": "asd", "category": "asd", "createdAt": { "$date": "2024-03-07T20:21:52.000Z" } } I couldn’t find the answer to the question on the Internet and gpt -
Python ORM Mongo attribute with name containing "__"
One of developer is trying to query a Mongo document that has name containing __. Example Document { "name":"someName" "Identifiers": { "Identifier01": [ "Value1", "Value2"], "__identntifier2__" : ["value3", "value4"] } } When he is trying search in python using something like [ for a new enhancement] filter(Identifiers____identntifier2__) in python ORM , for obvious reasons , it is throwing errors. Any idea on how __ in the name of the attribute can be escaped and not interpreted an operator? NOTE: We cannot change the attribute name as this is a legacy code and there are quite bit of documents with such named attribute. Tried __ , tried f() , tried F() [ suggestion from chatGpt] -
Do I need the confirm_delete.html template inorder to use the _delete template?
Here is my error: django.template.exceptions.TemplateDoesNotExist: blog/post_confirm_delete.html this is the url in mu urls.py file path('post/<int:pk>/delete/', BlogDeleteView.as_view(), name='post_delete'), Here is my views.py code: class BlogDeleteView(DeleteView): model = Post template = "post_delete.html" success_url = reverse_lazy('home') Even when I do make the post_confirm_delete.html template, nothing changes. -
Unknown issue with Celery and Pandas (Modin), Task Execution stuck and no error
Description: I have set up a Django project with Celery and RabbitMQ in Docker. I am trying to execute a Celery task from my API viewset, and I can see the task being received in the Celery container logs. However, the task seems to get stuck when I use Pandas with Modin. Observation: Print statements above the Pandas Modin usage work fine. No error or exception is raised. Print statements after the Pandas line are not executed. Code Example: @shared_task def test_pandas_df(): print("Start task") test_df = pd.DataFrame({"A": [1, 2, 3], "B": ["a", "b", "c"]}) logger.info("Df Data :") print(test_df) # In my viewset: test_pandas_df.delay() Celery Container Log: My end goal is to use Pandas Modin to read a CSV Data and perform some aggregations. I have created a simple test function to understand celery task execution, But I'm unable to debug the cause of task getting stuck. I will be trying on separate Machine and using Pandas in place of Modin (although it should fallback). I'm trying to understand, Why no error or progress is shown. Kindly guide me, If I have missed something. -
Stripe split payment Django
I am working on a project where i have to split the payments for that i have connected the customer to the stripe and retrieved the stripe account number for the same class AuctionPayment(View): def get(self, request, *args, **kwargs): if not request.user.is_authenticated: return redirect('/') else: user = request.user customer_id = user.stripe_customer_id if customer_id == "": customer_id = stripe.Customer.create(email=user.email)["id"] user.stripe_customer_id = customer_id user.save() mode = request.GET.get('mode', 'auction') auction_id = self.kwargs["auction_id"] courier_id = self.kwargs["courier_id"] if mode == 'auction': auction = Auction.objects.get(pk=auction_id) seller_id = auction.user seller_account_id = seller_id.stripe_connect_id print("-------------------------------------------------", seller_id , seller_account_id) referrals = Referral.objects.filter(referred_user=seller_id).first() referred_by = referrals.referred_by print("----------------------------------------------------refered_by ", referred_by) courier = CourierService.objects.get(auction=auction, courier_id=courier_id) if auction.current_bid is not None: price = int(round(float(auction.current_bid) * 100.0)) if auction.auction_status == "Ongoing": price = int(round(float(auction.product.nail_buy_now_price) * 100.0)) buyer_address = auction.buyer_address else: event = SpecialEvent.objects.get(pk=auction_id) courier = CourierService.objects.get(event=event, courier_id=courier_id) seller = event.selected_seller seller_request = SellerRequest.objects.get(event=event, user=seller) price = int(round(float(seller_request.price) * 100.0)) buyer_address = event.buyer_address taxes = 0 if buyer_address.state.lower() == 'alabama' or buyer_address.state.lower() == 'al': taxes = int(round(float(price * 0.08))) shipping_charges = courier.price total_charges = price + shipping_charges + taxes # if referrals: admin_amount = int((total_charges - shipping_charges) * 0.2) seller_amount = total_charges - admin_amount referral_amount = int(admin_amount * 0.02) stripe.api_key = "api_key" session = stripe.checkout.Session.create( success_url=my_domain … -
run django project on new computer
I developed a project on django for years and deployed it on heroku. Now my Computer crashed and i try to get my running django project from heroku run on my new laptop in pycharm. -i cloned my project from heroku -installed all dependencies -created new venv -set system variables secret key etc... seems like i have multiple issues... tried everything and read for hours and days but cant get it working .... any tip would be usefull Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\schno\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\schno\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\schno\PycharmProjects\ers-heatscreen-app\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\schno\PycharmProjects\ers-heatscreen-app\venv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\schno\PycharmProjects\ers-heatscreen-app\venv\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\schno\PycharmProjects\ers-heatscreen-app\venv\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\schno\PycharmProjects\ers-heatscreen-app\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\schno\PycharmProjects\ers-heatscreen-app\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\schno\PycharmProjects\ers-heatscreen-app\venv\lib\site-packages\django\urls\resolvers.py", line 416, in check for pattern in self.url_patterns: File "C:\Users\schno\PycharmProjects\ers-heatscreen-app\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\schno\PycharmProjects\ers-heatscreen-app\venv\lib\site-packages\django\urls\resolvers.py", line 602, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\schno\PycharmProjects\ers-heatscreen-app\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\schno\PycharmProjects\ers-heatscreen-app\venv\lib\site-packages\django\urls\resolvers.py", line 595, in … -
Can't figure out why my DRF login test is not working as expected
I have the following test case: class CustomUserViewSetTests(APITestCase): @classmethod def setUpTestData(cls): cls.user = get_user_model().objects.create( email="test@email.com", password="testpass123" ) def test_login_with_correct_data(self): url = reverse("knox_login") resp = self.client.post( url, data={ "email": "test@email.com", "password": "testpass123", }, format="json", ) respJson = resp.json() self.assertEqual(resp.status_code, status.HTTP_200_OK) The test always fails since "resp" has a 400 status code with body {'non_field_errors': ['Unable to log in with provided credentials.']}. When I check the test database via get_user_model().objects.all(), I can see that the user exists. Also, when I call the url via Postman, I get status code 200 with token and user details returned in body. -
Add javascript to rendered html streamfields
I am using streamfields in my wagtail project and I want to add js to rendered templates I tried like this: enter image description here But it does not append to the end of the body like in page templates, any ideia how can i enter image description here I have tried this and also StructBlockAdapter but none of that works, StructBlockAdapter only adds JS to backoffice -
I am getting multivalue key error in views in django
I created a Review System When I am going to submit the review there is an error In my views.py: def ajex_add_review(request,pid): product=Product.objects.get(pk=pid) user=request.user review=ProductReview.objects.create( user=user, product=product, review=request.POST['review'],#1 rating=request.POST['rating'],#2 ) context={ 'user':user.username, 'review':request.POST['review'],#1 'rating':request.POST['rating'],#2 } average_reviews=ProductReview.objects.filter(product=product).aggregate(rating=Avg("rating")) return JsonResponse( { 'bool':True, 'context':context, 'average_reviews':average_reviews, } ) I think that the error coming from here. Because if I comment out review(#1) or rating(#2) any of this it is working perfectly well In case if you need my js file then In function.js: console.log("working"); $("#commentForm").submit(function(e){ e.preventDefault(); $.ajex({ data: $(this).serialize(), method: $(this).attr("method"), url: $(this).attr("action"), dataType: "json", success: function(response){ console.log("Comment Saved"); } }) }) and In my product-detail.html <div class="add-review"> <h3>Add Your Review</h3> <form action="{% url 'core:ajex_add_review' p.id %}" method="POST" id="commentForm"> {% csrf_token %} {{review_form.rating}} </form> <br> <form action="{% url 'core:ajex_add_review' p.id %}" method="POST" id="commentForm"> {% csrf_token %} {{review_form.review}} <button type="submit" class="btn">Submit</button> </form> <div class="rating-bar"> <div class="bar"> <div class="fill" style="width: 80%;"></div> </div> <div class="bar-label"><i>{{average_rating.rating|floatformat:1}} out of 5.0</i></div> </div> </div> So please help me out from this problem. And my Indentation are correct. And at last My error is: System check identified 2 issues (0 silenced). March 08, 2024 - 01:45:45 Django version 4.1.13, using settings 'ecomprj.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. … -
A Profile to make Detailed changes in Django Rest-Framework API. I have created Serializered File and View file but Detail is not saved
Actually, I am working on a project and I have to modify the authentication system so that I am able to log in using username and password. I have Login Successfully and I have Change Detail but Don't Change Detail. Please Solve This Code and give me a Code. My serializrs.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ("first_name", ) def create(self, validated_data): user_id = Token.objects.get(key=validated_data.auth.key).user_id user = User.objects.get(id=user_id) first_name = validated_data.get('first_name') user.first_name = first_name user.save() return user My views.py class ProfileAPIView(APIView): serializer_class = ProfileSerializer permission_classes = [permissions.AllowAny] authentication_classes = [TokenAuthentication] def post(self, request): serializer = ProfileSerializer(data=request.data) if serializer.is_valid(raise_exception=True): return Response({"msg":"Profile Update"}, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_401_UNAUTHORIZED) Solve this Serialize File And View File and Give me a Code. -
How to customize lockout mechanism in Django Axes?
I am new to Django Axes. I need to customize the lockout of Django Axes so that the user is locked out when the number of login attempts reaches the AXES_FAILURE_LIMIT within a 10 minute period. I tried creating a custom handler for the signal user_login_failed that: Gets the list of Access Attempts of the username Gets the time difference of the oldest and the latest login attempt If the login attempts count are less than or equal to the AXES_FAILURE_LIMIT, and if the time difference is more than 10 minutes, It will delete the oldest attempt to prevent the lockout. Else, it will continue the lockout process. However, when the login attempt reaches the AXES_FAILURE_LIMIT, the user_login_failed signal is not triggered and the user is locked out. Is there a better way to handle this? Is this just a configuration on Django Axes? -
MIME type error with css file and load static showing in plain text - Django on PyCharm IDE
In my HTML template, when I pass it to debug mode, gets the following errors: Refused to apply style from its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.; MIME Error {% load static %}` shows in plain text; Pics and css files are in YouTrade1/static/YouTrade1 Template is in YouTrade1/templates/YouTrade1 I tried several solutions for the documentation of my static files and none seem to work. All documentation according to Django best practices. I don't manage to understand whether there's something wrong with either my django project setup (which looks fine), my testing environment (I click debug/run on pyCharm IDE and they said it's all fine on their side) or my HTML script. Css File HTML page Settings1 Settings2 URLs Views