Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Free online solutions for testing python frameworks on web
I'm looking for a free online solution to test python frameworks like django and flask. From what I have searched so far, I have not found any that do not involve additional expenses. -
Failed to lock Pipfile.lock
when I am trying to install mysqlclient on my Django project, I am facing this error. since I am a complete beginner on python-django, could someone help me out on solving this issue? ''' (demoproject) chandanm@Chandans-MacBook-Air demoproject % pipenv install mysqlserver Installing mysqlserver... Resolving mysqlserver... Added mysqlserver to Pipfile's [packages] ... ✔ Installation Succeeded Pipfile.lock (e35515) out of date, updating to (8070c0)... Locking [packages] dependencies... Building requirements... Resolving dependencies... ✘ Locking Failed! ⠹ Locking...False CRITICAL:pipenv.patched.pip._internal.resolution.resolvelib.factory:Could not find a version that satisfies the requirement mysqlserver (from versions: none) [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pipenv/resolver.py", line 645, in _main [ResolutionFailure]: resolve_packages( [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pipenv/resolver.py", line 612, in resolve_packages [ResolutionFailure]: results, resolver = resolve( [ResolutionFailure]: ^^^^^^^^ [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pipenv/resolver.py", line 592, in resolve [ResolutionFailure]: return resolve_deps( [ResolutionFailure]: ^^^^^^^^^^^^^ [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pipenv/utils/resolver.py", line 908, in resolve_deps [ResolutionFailure]: results, hashes, internal_resolver = actually_resolve_deps( [ResolutionFailure]: ^^^^^^^^^^^^^^^^^^^^^^ [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pipenv/utils/resolver.py", line 681, in actually_resolve_deps [ResolutionFailure]: resolver.resolve() [ResolutionFailure]: File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/pipenv/utils/resolver.py", line 442, in resolve [ResolutionFailure]: raise ResolutionFailure(message=str(e)) [pipenv.exceptions.ResolutionFailure]: Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies. You can use $ pipenv run pip install <requirement_name> to bypass this mechanism, then run $ pipenv graph to inspect the versions actually installed in the virtualenv. Hint: … -
Getting error': 'Invalid date format. Please provide the date in the format dd/mm/yyyy' working perfectly on ubuntu but show this error on windows
' def subscription_detail(request): user = request.user if request.method == 'POST': try: data = json.loads(request.body) if data and 'subscriptionData' in data: subscription_data = data['subscriptionData'] if subscription_data: try: current_platform = sys.platform if current_platform == "win32" or current_platform == "cygwin": # Windows-based system print("Using Windows system format") print("Payment Date:", subscription_data['paymentDate']) payment_date = datetime.strptime(subscription_data['paymentDate'], '%d/%m/%Y').date() payment_time = datetime.strptime(subscription_data['paymentTime'], '%H:%M:%S').time() elif current_platform == "darwin": # macOS print("Using macOS system format") payment_date = datetime.strptime(subscription_data['paymentDate'], '%m/%d/%Y').date() payment_time = datetime.strptime(subscription_data['paymentTime'], '%H:%M:%S').time() elif current_platform =="linux": # Unix-based system print("Using Unix-based system format") payment_date = datetime.strptime(subscription_data['paymentDate'], '%m/%d/%Y').date() payment_time = datetime.strptime(subscription_data['paymentTime'], '%H:%M:%S').time() except ValueError as e: print("ValueError: ", e) return JsonResponse({'error': 'Invalid date format. Please provide the date in the format dd/mm/yyyy'}, status=400) exam_instance = Exams.objects.get(id=subscription_data['examName']) if subscription_data['subscriptionType'] == "monthlyRadio": expiry_date = payment_date + timedelta(days=30) elif subscription_data['subscriptionType'] == "quarterlyRadio": expiry_date = payment_date + timedelta(days=122) elif subscription_data['subscriptionType'] == "yearlyRadio": expiry_date = payment_date + timedelta(days=365) else: return JsonResponse({'error': 'Invalid subscription type'}, status=400) instances = Subscriptin_details.objects.create( amount=subscription_data['amount'], card_type=subscription_data['payment_method_details']['card']['funding'], payment_date=payment_date, payment_time=payment_time, subscription_type=subscription_data['subscriptionType'], user_name=user, expiry_date=expiry_date, exam_name=exam_instance, ) instances.save() return JsonResponse({'Success': 'Payment successful'}, status=200) else: return JsonResponse({'error': 'Subscription data not found'}, status=400) else: return JsonResponse({'error': 'SubscriptionData key not found'}, status=400) except Exception as e: return JsonResponse({'error': str(e)}, status=500) else: return JsonResponse({'error': 'Invalid request method'}, status=400) ' here … -
Django redirect error unexpected keyword while returning to previews view
I have searched and have not found any answers related to my specific problem. When I submit a form from my index view to an up_load view and try to have the up_load view redirect back to the index view while including the page number as an argument, I get an error, I have tried using a context dictionary and still nothing. url.py from django.urls import path from . import views app_name = 'myApp' urlpatterns = [ path("", views.index, name="index"), path("", views.index, kwargs={'cliente_id': None}, name="index"), path("<int:cliente_id>/", views.index, name="index"), path("<int:cliente_id>/<str:page>", views.index, name="index"), path('up_load/', views.up_load, name='up_load'), ] views.py def index(request, cliente_id=None): paginator = Paginator(client_list, 15) page_number = request.GET.get("page") page = paginator.get_page(page_number) context = {'cliente_id': cliente_id, 'page': page, 'paginator': paginator } return render(request, 'myApp/index.html', context) def up_load(request): if request.method == 'POST': form = ExpeditensForm(request.POST, request.FILES) cliente_id = request.POST.get('cliente_id', '/') page = request.POST.get('page', '/') if form.is_valid(): form.save() return redirect('myApp:index', cliente_id=cliente_id, page=page) else: pass Django returns the following error. Exception Type: TypeError at /Expedientes/4/1 Exception Value: index() got an unexpected keyword argument 'page' The browser shows the following URL: http://127.0.0.1:8000/Expedientes/4/1 When it should be: http://127.0.0.1:8000/Expedientes/4/?page=1 Thank you -
Django ManyToMany creations and cascading deletions
Django ManyToMany creations and cascading deletions Django newbie here. I have looked under several threads and I have not found anything related so I hope you can help me out on this. I am working on a ManyToMany model involving Doctors and Patients, that is, both can have multiple relationships between them. I have the following model definition: class Patient(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True) (other fields definitions) class Doctor(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True) (other fields definitions) … patients = models.ManyToManyField(Patient) The doctor is the main user that should be able to visualize all related patients (no problem there). When adding a new patient though, I would like to know how to create the relationship in the app_doctor_patients join table. I’ve read the documentation regarding the Related objects reference (https://docs.djangoproject.com/en/4.2/ref/models/relations/#django.db.models.fields.related.RelatedManager) but I do not know which is the best way to apply these functions. For starters, I visualized the following: def add_new_patient(request, doctor_id=None, curp=None): doctor = Doctor.objects.get(id=doctor_id) try: patient = Patient.objects.get(curp=curp) # Associates Patient 'patient' with Doctor 'doctor'. doctor.patients.add(patient) except Patient.DoesNotExist: # Creates a new patient object, saves it and puts it in the related object set. Returns the newly created … -
How can I create a views.py that allows a registered user to create, amend and delete a appointment?
I am developing a barber booking service using Django/Python. I want to create a view for an authenticated user to create a booking, amend and/or delete their booking. I am a student developer and this particular issue is not covered in the lessons and I am a little overwhelmed by it all, I have done many searches online but have not had any luck with finding anything I am able to work with. So far I have managed to create the models.py code but have hit a brick wall when it comes to creating the views.py, any help or advice is greatly appreciated! My current models.py file from django.db import models from datetime import datetime from django.contrib.auth.models import User SERVICE_CHOICES = ( ("Classic Cut", "Classic cut"), ("Cut & Beard", "Cut & Beard"), ("Skin Fade", "Skin Fade"), ("Skin & Beard", "Skin & Beard"), ("Buzz Cut", "Buzz Cut"), ) TIME_CHOICES = ( ("9 AM", "9 AM"), ("10 AM", "10 AM"), ("11 AM", "11 AM"), ("1 PM", "1 PM"), ("2 PM", "2 PM"), ("3 PM", "3 PM"), ("4 PM", "4 PM"), ("5 PM", "5 PM"), ) class Appointment(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True) service = models.CharField( max_length=50, choices=SERVICE_CHOICES, default="Classic Cut") day … -
Weird error produced when quering sqlite databased using a model
I'm getting a very weird decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>] when trying to query a table in my Django application. I suspect it may be related to the virtual environment. This is the view. It is an endpoint that will receive some JSON data (at the moment I'm using Postman to send data to it). def handleRawMarketData(request): if request.method=='POST': data = json.loads(request.body) print(data) for item in data: new_data = rawMarketData(duration=item['duration'], is_buy_order=item['is_buy_order'], issued = item['issued'], location_id = item['location_id'], min_volume = item['min_volume'], order_id = item['order_id'], price = item['price'], range = item['range'], typeID = InvTypes.objects.get(typeID = item['type_id']), volume_remain = item['volume_remain'], volume_total = item['volume_total']) new_data.save() return JsonResponse({'message': 'Data saved successfully'}) return JsonResponse({'message': 'Failed'}) This is the data being sent in the body of the POST request by Postman: [{"duration":90,"is_buy_order":true,"issued":"2023-10-03T10:21:32Z","location_id":1038457641673,"min_volume":1,"order_id":6512967679,"price":17720000,"range":"region","type_id":19255,"volume_remain":2,"volume_total":3},{"duration":90,"is_buy_order":true,"issued":"2023-10-17T20:31:19Z","location_id":1038457641673,"min_volume":1,"order_id":6616121350,"price":500.2,"range":"station","type_id":24509,"volume_remain":198250,"volume_total":200000}] These are the two models being used. class InvTypes(models.Model): typeID = models.IntegerField(db_column='typeID', primary_key=True) groupid = models.IntegerField(db_column='groupID', blank=True, null=True) typename = models.CharField(db_column='typeName', blank=True, null=True, max_length=10000) description = models.TextField(blank=True, null=True) mass = models.IntegerField(blank=True, null=True) volume = models.IntegerField(blank=True, null=True) capacity = models.IntegerField(blank=True, null=True) portionsize = models.IntegerField(db_column='portionSize', blank=True, null=True) raceid = models.IntegerField(db_column='raceID', blank=True, null=True) baseprice = models.DecimalField(db_column='basePrice', max_digits=10, decimal_places=5, blank=True, null=True) published = models.BooleanField(blank=True, null=True) marketgroupid = models.IntegerField(db_column='marketGroupID', blank=True, null=True) iconid = models.IntegerField(db_column='iconID', blank=True, null=True) soundid = models.IntegerField(db_column='soundID', blank=True, null=True) graphicid … -
Authorize.net Unsettled Transaction List returning nothing, No error, No response
I have copy pasted this code from Authorize.net no errors are raised by this code, and the Authorize.net response is empty. There are no entries in the transaction list, and there are no errors either. Just empty response This my code:- def get_unsettled_transaction_list(location, limit=20, offset=1): """get unsettled transaction list""" locationAuth = AuthorizeDotNetServices._get_location_auth(location) # set sorting parameters sorting = apicontractsv1.TransactionListSorting() sorting.orderBy = apicontractsv1.TransactionListOrderFieldEnum.id sorting.orderDescending = True # set paging and offset parameters paging = apicontractsv1.Paging() # Paging limit can be up to 1000 for this request paging.limit = limit paging.offset = offset transactionrequest = apicontractsv1.getUnsettledTransactionListRequest() transactionrequest.merchantAuthentication = locationAuth transactionrequest.refId = "Sample" transactionrequest.sorting = sorting transactionrequest.paging = paging unsettledTransactionListController = getUnsettledTransactionListController(transactionrequest) unsettledTransactionListController.execute() # Work on the response response = unsettledTransactionListController.getresponse() -
Unable to log user in
This is my code: from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from django.contrib.auth import authenticate, login @api_view(["POST"]) def user_login_api_view(request): username = request.data.get("username") password = request.data.get("password") user = authenticate(username=username, password=password) print(user, password, username) if user is not None: login(request, user) return Response(status=status.HTTP_200_OK) else: return Response(status=status.HTTP_401_UNAUTHORIZED) This is my request body for login: { "username": "testuser111@test.test", "password": "testpassword111" } Here's the print result: None testpassword111 testuser111@test.test I register a user like so: from django.contrib.auth.models import User from ..serializers import UserSerializer class UserCreateApiView(generics.CreateAPIView): def get_queryset(self): return User.objects.create_user(self.request.data) serializer_class = UserSerializer with this request body: { "username": "testuser111@test.test", "password": "testpassword111" } User serializer from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = "__all__" password = serializers.CharField(write_only=True) And in response I get 401. How do I log a user in properly? -
Django Rest Framework SimpleJWT - Removing a variable refrencing 'request.body' Causes 'RawPostDataException' Error
I have a Django 4.2.6 project using Python 3.10 and the rest_framework_simplejwt library. I've implemented a signin function, and it works fine when I include the line body = request.body, even though I'm not using body anywhere in the function. However, when I remove this line, it throws the following error: “RawPostDataException at /auth/signin/ - You cannot access the body after reading from the request's data stream.” I've tried to understand why this is happening, but I couldn't figure it out even after reading the docs. Can someone help me understand why this line is needed and if there's a cleaner or better way to write this function? Here's my code: @api_view(['POST']) def signin(request): body = request.body token_view = jwt_views.TokenObtainPairView.as_view() token_response = token_view(request._request) if token_response.status_code == status.HTTP_200_OK: data = request.data user = User.objects.filter(username=data['username']).first() data = { "access_token": str(token_response.data['access']), "refresh_token": str(token_response.data['refresh']), "user_access": { "is_staff": user.is_staff, "is_admin": user.is_superuser } } return Response(data, status=status.HTTP_200_OK) return token_response -
Is it dangerous that request.user is exposing user' s password?
I am new to DRF and django. I noticed that request.user.password is exposing logged in user password (hashed) and I thought that this might be dangerous. Can a third party have access to request? I create a serializer that exclude password. I tried to write a middleware for this and i have this message when a user log in : rest_framework.request.WrappedAttributeError: 'ReturnDict' object has no attribute 'is_active' Middleware.py from users.serializers import RequestUserSerializer def RemovePasswordFromUser(get_response): def middleware(request): if request.user.id is not None: request.user = RequestUserSerializer(request.user).data print(request.user) response = get_response(request) return response return middleware RequestUserSerializer.py class RequestUserSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() exclude = ["password"] Log In Class in views.py class LoginAPI(APIView): def post(self, request): username = request.data["username"] password = request.data["password"] user = authenticate(username=username, password=password) if user is None: return Response( status=status.HTTP_404_NOT_FOUND, data={"message": "Wrong Crendentials"} ) login(request, user) request.user = RequestUserSerializer(request.user).data print(type(request.user)) return Response( status=status.HTTP_200_OK, data={"message": "User Login"}, ) i tried to write a middleware for this. -
Django Upvote & Downvote help please
I am working on a project for my course that users can vote items either up or down. I'm using Django and have just begun learning it recently. I am having an issue to get past clicking and activating the buttons separately as my downvote button just activates the upvote. My template: <div class="row"> <div class="col-1"> <strong> {% if user.is_authenticated %} <form action="{% url 'post_vote' post.slug %}" class="d-inline" method="POST"> {% csrf_token %} {% if liked %} <button type="submit" name="blogpost_id" value="{{post.slug}}" id="btn-like" class="btn-like"><i class="fa-solid fa-circle-up" style="color: #1ea427;"></i></button> {% else %} <button type="submit" name="blogpost_id" value="{{post.slug}}" id="btn-like" class="btn-like"><i class="fa-regular fa-circle-up"></i></button> {% endif %} </form> {% else%} <span class="text-scondary"><i class="fa-regular fa-circle-up"></i></span> {% endif %} <span class="text-secondary">{{ post.number_of_up_votes}}</span> </strong> </div> <div class="col-1"> <strong> {% if user.is_authenticated %} <form action="{% url 'post_vote' post.slug %}" class="d-inline" method="POST"> {% csrf_token %} {% if disliked %} <button type="submit" name="blogdownpost_id" value="{{post.slug}}" id="btn-like" class="btn-like"><i class="fa-solid fa-circle-down" style="color: #ff0000;"></i></button> {% else %} <button type="submit" name="blogdownpost_id" value="{{post.slug}}" id="btn-like" class="btn-like"><i class="fa-regular fa-circle-down"></i></button> {% endif %} </form> {% else%} <span class="text-scondary"><i class="fa-regular fa-circle-down"></i></span> {% endif %} <span class="text-secondary">{{ post.number_of_down_votes}}</span> </strong> </div> <div class="col-1"> {% with comments.count as total_comments %} <strong class="text-secondary"><i class="far fa-comments"></i> <!-- Our total_comments variable goes before the closing strong tag --> {{ … -
HTTP_HOST Stripping via Firewalls and VPNs
I have an issue that's presenting as a CORS-related issue from a frontend (React) making API calls to a backend (Django). However, looking at the logs, I'm seeing things like this: django.core.exceptions.DisallowedHost: Invalid HTTP_HOST header: '123.456.789.101:8007'. You may need to add '123.456.789.101' to ALLOWED_HOSTS. The site works fine from my PC, several friends, and mobile devices, via my VPN, but fails to make API requests when behind certain firewalls (corporate) or via online VPN services that let one type in a website, visit it via an in-browser window (not naming names b/c that's beside the point here). What seems to be the issue is a security measure whereby the firewalls are stripping out the HTTP_HOST specified by the site and adding in the actual IP to avoid e.g. HTTP_HOST-based spoofing. Is there any way(s) to address this that doesn't involve assigning a static IP to my host and hard-coding that into the ALLOWED_HOSTS? For example, I like testing new apps on easy 1-click deploy type services like Digital Ocean, Railway, Netlify, etc. that are great but don't always provide the option for a static IP (not focusing on a specific service here). Am I stuck hoping my PaaS provider exposes … -
Having trouble with PUT request in React with Django backend: the Props can update State in DevTools but the State doesn't update the Props
I've probably made a stupid error I'm brand new at React; I'm building a POC for a class assignment and need to demonstrate a GET and PUT request in react on existing data in a django backend. The GET method works, and the API works. It's all very simple code, so I don't know where I went wrong: import React, { Component } from 'react' import './App.css'; import axios from 'axios' import Temperature from "./components/Temperature" import BootstrapSwitchButton from 'bootstrap-switch-button-react' class App extends Component { constructor(props) { super(props); this.state= { deviceEnabled: false, viewActivated: true, deviceList: [] }; } componentDidMount() { this.refreshList(); } refreshList = () => { axios .get("http://localhost:8000/api/devices/") .then(res => this.setState({ deviceList: res.data })) .catch(err => console.log(err)) }; handleSubmit = device => { if (device.id) { axios .put(`http://localhost:8000/api/tasks/${device.id}/`, device) .then(res => this.refreshList()) } axios .post("http://localhost:8000/api/devices/", device) .then(res => this.refreshList() ) } // Checks if device is activated or not displayActivated = status => { if (status) { return this.setState({ viewActivated: true }) } return this.setState({ viewActivated: false }) } displayEnabled = status => { if (status) { return !this.state.deviceEnabled; } return this.state.deviceEnabled; } // Renders activated and inactive devices under proper heading renderDeviceList = () => { return ( <div … -
index our of range in django template
I'm beginner in django and i'm trying to create a website and in its blog page there is a section that shows prev post and next post. I gave them the url of posts using a for loop that gives the id of posts from data base but in the first post it gives me the "index out of range" error here is the views.py and that section of blog template: views.py: def blog_single(request, pid): posts = get_object_or_404(Post, id=pid, status=1) ls = list(Post.objects.filter(status=1)) lis = [] for i in ls: lis.append(i.id) indpid = lis.index(pid) index_prev_post = indpid + 1 id_prev_post = lis[index_prev_post] index_next_post = indpid - 1 id_next_post = lis[index_next_post] name_prev_querry = Post.objects.filter(id=id_prev_post) name_prev_list = list(name_prev_querry) name_prev = name_prev_list[0].title name_next_querry = Post.objects.filter(id=id_next_post) name_next_list = list(name_next_querry) name_next = name_next_list[0].title context = {'post':posts, 'prev':id_prev_post, 'next':id_next_post, 'name_prev':name_prev, 'name_next':name_next} return render(request, 'blog/blog-single.html', context) template: </div> <div class="navigation-area"> <div class="row"> <div class="col-lg-6 col-md-6 col-12 nav-left flex-row d-flex justify-content-start align-items-center"> <div class="thumb"> <a href="#"><img class="img-fluid" src="{% static 'img/blog/prev.jpg' %}" alt="" /></a> </div> <div class="arrow"> <a href="#"><span class="lnr text-white lnr-arrow-left"></span></a> </div> <div class="detials"> <p>Prev Post</p> <a href="{% url 'blog:single' pid=prev %}"><h4>{{name_prev}}</h4></a> can you please tell me what's wrong with my code? I have tried changing the name_prev … -
Should I inherit from User model
I have two other models that should have all the functionalities that User model have. That's why in those two models, I am inheriting from User model. default_role = "admin" class User(AbstractBaseUser): ... image = models.ImageField(upload_to=user_directory_path, blank=True, null=True) role = models.CharField(max_length=20, choices=ROLE_CHOICE, default=default_role) .... class Student(User): ... some_fields_related_to_student ... def save(): self.role = "student" class Teacher(User): ... some_fields_related_to_teacher ... def save(): self.role = "teacher" def user_directory_path(instance, filename, role): extension = filename.split('.')[-1] return f"{role}/{instance.id}.{extension}" When I try to put the image pictures for Teacher and Student models, I want to put them in: ".../teachers/{teacher.id}.{extension}" ".../students/{student.id}.{extension}" these folders. How I can pass the role field to user_directory_path function? Also, my another question is that should I inherit from User at all? Whenever I create Student or Teacher it is also creating that model in User too, but for me it looks like not optimal, since we are kinda duplicating the information -
VSCode DJLint extension formats python files
My DJLint extension for VSCode recognizes problems in python files however it is not supposed to. It is supposed to run only in html files. DJLint error in python File Now my settings tell me that this extension is only running in the default file formats that do not include .py as seen here. What am I missing? -
Why aren't my serializer method fields being called?
I have the following django model: class HelpItem(TimeStampMixin): user = models.ForeignKey(User, related_name='help_items', on_delete=models.DO_NOTHING) description = models.TextField() support_choice = models.PositiveSmallIntegerField( choices=SubscriptionPlan.SUPPORT_CHOICES, default=SubscriptionPlan.EMAIL ) parent_entity = models.ForeignKey(ParentEntity, related_name='help_items', on_delete=models.DO_NOTHING, null=True) Im sending a post request to create a HelpItem through this view: class HelpItemView(CreateAPIView): permission_classes = (IsAuthenticated, ) serializer_class = HelpItemSerializer def post(self, request, *args, **kwargs): help_item = self.serializer_class(data=request.data, context={ 'user': request.user, 'selected_parent_entity': request.selected_parent_entity }) help_item.is_valid(raise_exception=True) help_item = help_item.save() return Response(self.serializer_class(help_item).data, status=status.HTTP_201_CREATED) And this is my serializer: class HelpItemSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField() parent_entity = serializers.SerializerMethodField() support_choice = serializers.SerializerMethodField() class Meta: model = HelpItem fields = ['description', 'support_choice', 'parent_entity', 'user'] def get_user(self, obj): return self.context['user'].id def get_parent_entity(self, obj): return get_parent_entity_for_configurations(obj.user, self.context['selected_parent_entity']) def get_support_choice(self, obj): try: return Subscription.objects.get(parent_entity=obj.parent_entity).subscription_plan.support except Subscription.DoesNotExist: print('No subscription exists.') Shouldn't the method fields be called before the serializer tries to save the HelpItem object? I get the following error: null value in column "user_id" of relation "smartsign_helpitem" violates not-null constraint DETAIL: Failing row contains (22, 2023-10-27 14:57:23.696476+00, 2023-10-27 14:57:23.696497+00, need help, null, null, 1). So basically the description is accessed but support choice sets to default value (1) and the user and parent entity columns are null. Why? -
Django Updatign Fields in views.py not working
I have a Django Application for clients home data, I want to Change the password of user and editing other fields, I can change all the data in my console but when I use views.py and forms, the data does not save without any errors. I paste my codes here, please help me :) views function: `@login_required def profile_home(request): user = request.user home = Home.objects.filter(user=user).first() if request.method == 'POST': if request.POST.get('password2'): form_change = ChangePasswordForm(request.POST) if form_change.is_valid(): data = form_change.cleaned_data user.set_password(data['password2']) user.save() else: form_edit = HomeEditForm(request.POST) if form_edit.is_valid(): data = form_edit.cleaned_data user.first_name = data['first_name'] user.last_name = data['last_name'] user.email = data['email'] home.national_code = data['national_code'] home.mobile = data['mobile'] home.province = data['province'] home.city = data['city'] home.address = data['address'] home.zip_code = data['zip_code'] user.save() home.save() messages.success(request, 'با موفقیت ذخیره شد', 'success') form_edit = HomeEditForm( initial={'first_name': user.first_name, 'last_name': user.last_name, 'email': user.email, 'national_code': home.national_code, 'mobile': home.mobile, 'province': home.province, 'city': home.city, 'address': home.address, 'zip_code': home.zip_code}) form_change = ChangePasswordForm() return render(request, 'panel/profile_home.html', context={'home': home, 'form_edit': form_edit, 'form_change': form_change})` The Model: `class Home(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='User') national_code = models.CharField(max_length=10, verbose_name='National Code') mobile = models.CharField(max_length=13, verbose_name='Mobile', validators=[MinLengthValidator(11)]) province = models.CharField(max_length=20, verbose_name='Province') city = models.CharField(max_length=50, verbose_name='City') address = models.TextField(verbose_name='Address') zip_code = models.CharField(max_length=10, verbose_name='Zip Code', validators=[MinLengthValidator(10)]) score = models.IntegerField(verbose_name='Score', default=0, validators=[MinValueValidator(0), MaxValueValidator(20000)]) … -
Unresolved attribute reference 'objects' for class '_ _'- in pycharm
Project information i was work with a small project name - Web_applications. where i simply make a django website project I was making a website that take a topics & And write about for that topics } What error i was encountering in my** pycharm ide** i was encountering error in my pycharm terminal error - { Unresolved attribute reference 'objects' for class 'Topic' }. When i was adding a function - Topic section in my view.py file. **code ** def topics(request): """Show all the topics""" all_topics = Topic.objects.order_by('date_added') context = {'topics': all_topics} return render(request, 'Web_applications_apps/topics.html', context) -where the error happen In this objects attribute section , was highlighted in yellow color and show error in terminal. error - Unresolved attribute reference 'objects' for class 'Topic' i was copy the code and error, ask with CHATGPT & BARD but they not able to give extact answer about this error 2.Then i search this error in stackoverflow and i get some over view why i was get this error -
django and react routing integration
I'm a python Django newbie, and I'm coding for a React Django app. My question is about routing or integration of Django and React, until now I have made a view for Django to send React app (index.html) to client and set the URL for it on home page "www.domain.com/". Client can get app in that URL and app works, but there is a problem client can just get app from home page and other URLs will show a 404 error, means client must first go to home page then go to other pages this can be lead to a problem. For example if client when it don't have the app, and then directly type a URL that is for inside of react routing it says error 404 , so Django dont send the app , do I need to put view for every page of React app ? Because i dont think it must be like this i know Django and react routing are separate and React have its own routing because its a single page app (SPA). I have searched in GitHub projects and find a TemplateView in Django URLs do i need to fix the problem with … -
Django-filters how to use BooleanFilter to range or else
Good day, a question about "django-filters", "rest framework" How to make a filter to -1 option took up to 50% (in the decimal model), -2 option after 50%, -3 option equal 50 I did it with Boolean Filter and an additional "method" function - two fields, if true, then output the corresponding queryset. However, they are tied through one field and, accordingly, use one queryset, which makes them mutually exclusive when called at the same time, and not complementary as I need. I'm still looking at "ChoiceField", but I don't know if it's possible. p.s. I tried to unite use union method in functions but get error "ORDER BY not allowed in subqueries of compound statements." MY code from filter class: ` class ProductsFilter(filters.FilterSet): type_one = filters.BooleanFilter(field_name='percentage_field', method='filter_one') type_two = filters.BooleanFilter(field_name='percentage_field', method='filter_two') type_half = filters.BooleanFilter(field_name='percentage_field', method='filter_half') def filter_one(self, queryset, name, value): if value is True: return queryset.filter(percentage_field__range=(50.1, 100)) else: return queryset def filter_two(self, queryset, name, value): if value is True: return queryset.filter(percentage_field__range=(0, 49.9)) else: return queryset def filter_half(self, queryset, name, value): if value is True: asd = queryset return Product.objects.filter(percentage_field=50) else: return queryset class Meta: model = Product fields = ['name','price'] ``` Filtering by one and by several at once … -
Django translations of path **kwargs values in urls.py
How can I translate the values passed to **kwargs within the urls.py file in Django, based on the language selected by the user? Translations in templates are working, and the language is determined by the Accept-Language header set by the Nginx server. However, this language selection doesn't have any effect within the urls.py file, and instead is determined by LANGUAGE_CODE in settings.py file. Here is an example urls.py: from django.urls import path from main.views import IndexView from django.utils.translation import pgettext app_name = 'some_site' urlpatterns = [ path('', IndexView.as_view(), {'SITE_SEO_title': pgettext('home', 'SITE_SEO_title')} ] My question is, how can I translate the **kwargs values passed to the path method according to the user's selected language, and not according to LANGUAGE_CODE? Is there a different approach I could use to achieve this? -
How to connect django to an infomix database? [duplicate]
I want to connect my django project with an informix database without using ODBC. Is there any way to connect to my informix database throught my django application. what approuch should i follow i would be very greatfull if you could help me. -
Django Rest Framework Query Optimization
I need to remove these extra similar queries into database. Can you optimize this to remove similar queries: models.py: class Comment(BaseModel): description = models.TextField() article = models.ForeignKey( Article, on_delete=models.CASCADE, related_name="comments" ) author = models.ForeignKey( Author, on_delete=models.CASCADE, related_name="comments" ) reply_to = models.ForeignKey( "self", on_delete=models.CASCADE, related_name="replies", null=True ) serializers.py: class CommentSerializer(serializers.ModelSerializer): replies = serializers.SerializerMethodField(read_only=True) class Meta: model = Comment fields = ["id", "description", "author", "replies"] def get_replies(self, comment): return CommentSerializer(comment.replies, many=True).data views.py: class ArticleViewSet(ModelViewSet): queryset = ( Article.objects.select_related("category").prefetch_related("images").all() ) serializer_class = ArticleSerializer pagination_class = DefaultLimitOffsetPagination permission_classes = [IsAdminOrReadOnly] @action(detail=True, permission_classes=[IsAuthenticated], serializer_class=CommentSerializer) def comments(self, request, *args, **kwargs): self.queryset = ( Comment.objects.filter(article_id=self.kwargs["pk"], reply_to=None) .prefetch_related("replies") .all() ) return self.list(request, *args, **kwargs) I need to remove these extra similar queries into database.