Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to convert arraylist into list only
i have response data on the below: [{ "id": "8943832a-94e4-49e9-944f-022b65c9aa4b", "created": "2022-09-10T04:35:49.173268Z", "updated": "2022-09-10T04:35:49.204274Z", "pick_up_address": "pokhara", "drop_off_address": "kathmandu", "price": "120", "status": "REQUESTED", "email": "admin5@gmail.com", "username": "admin5" }, { "id": "16004d18-e0d0-4e35-b147-bb3234403602", "created": "2022-09-10T04:40:40.238071Z", "updated": "2022-09-10T04:40:40.282818Z", "pick_up_address": "kathmandu", "drop_off_address": "pokhara", "price": "200", "status": "REQUESTED", "email": "admin5@gmail.com", "username": "admin5" } ] but i need a response like this on the below { "id": "8943832a-94e4-49e9-944f-022b65c9aa4b", "created": "2022-09-10T04:35:49.173268Z", "updated": "2022-09-10T04:35:49.204274Z", "pick_up_address": "pokhara", "drop_off_address": "kathmandu", "price": "120", "status": "REQUESTED", "email": "admin5@gmail.com", "username": "admin5" }, { "id": "16004d18-e0d0-4e35-b147-bb3234403602", "created": "2022-09-10T04:40:40.238071Z", "updated": "2022-09-10T04:40:40.282818Z", "pick_up_address": "kathmandu", "drop_off_address": "pokhara", "price": "200", "status": "REQUESTED", "email": "admin5@gmail.com", "username": "admin5" } the code of here below serializer.py class NestedTripSerializer(serializers.ModelSerializer): driver = UserSerializer(read_only=True) passenger = UserSerializer(read_only=True) # custom in nested serializer def to_representation(self, instance): #pop passenger and driver data = super().to_representation(instance) is_list_view = isinstance(instance, list) #passenger email and username extra_ret = { 'email': self.context['request'].user.email, 'username': self.context['request'].user.username, } if is_list_view: for item in data: item.update(extra_ret) else: data.update(extra_ret) return data def get_ class Meta: model = Trip fields = '__all__' depth = 1 and the code of views.py below:- class TripView(viewsets.ReadOnlyModelViewSet): lookup_field = 'id' lookup_url_kwarg = 'trip_id' serializer_class = NestedTripSerializer permission_classes = (permissions.IsAuthenticated,) def get_queryset(self): user = self.request.user if user.group == 'driver': trip = Trip.objects.filter(Q(status='REQUESTED')) trip … -
Annotating a query with a foreign key and many-to-many in Django
I have a django operation that I'm performing in 2 steps, but I'd like to see if there's a way to do it with just 1 database query. Say I have these models: class Budget(models.Model): ... class Company(models.Model): budgets = models.ManyToManyField( Budget, related_name="companies" ) class Employee(models.Model): company = models.ForeignKey( Company, on_delete=models.CASCADE, related_name="employees" ) Now I want to get an employee, and find the IDs of the budgets that are associated with this employee, through the company: employee = Employee.objects.get(id=employee_id) allowed_budgets = employee.company.budgets.values_list("id", flat=True) Am I correct that this would perform 2 database queries? Is there a way to add allowed_budgets as an annotation on Employee so only 1 query is performed? employee = Employee.objects .annotate( allowed_budgets=# how do I get employee.company.budgets.values_list("id", flat=True) here? ) .get(id=employee_id) Thanks a lot! -
Getting error when creating access token :- {"error": "invalid_client"}
I perform below steps to create an access token. but getting error {"error": "invalid_client"} go to this link http://<ip_address>:/o/applications/ fill form to register your application enter below command in CMD curl -X POST -d "grant_type=password&username=<user_name>&password=" -u"<client_id>:<client_secret>" http://<ip_address>:/o/token/ Also, I installed required libraries for access token help of this https://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html Image of error attached below Error I am getting -
How to display my own html form instead of doing {{ form.as_p }} with forms.py django?
I have forms.py file with usercreation form inside of it. It works just fine, but the only way I can display fields in it(first_name, last_name, username, email, password and password confirmation is by writing {{ form.as_p }}. I want to display it the way I could style it. Are there any ways to do that? -
aws - beanstalk - how to check path of a file/script?
I am trying to deploy a Django REST framework api and reactjs app to AWS Beanstalk. The api works if I use postman. When I try to load the main.js I get the error: http://django-env1.eba-ispw2cg9.us-west-2.elasticbeanstalk.com/static/frontend/main.js 404 Not Found I have moved the static/frontend folder to the main folder. How can I check the directory structure and where exactly to put the static folder so that the above url will find it and load? -
drf ModelSerializer field level validation
I'm trying to Field-Level validation to validate branch field in ModelSerialzer but this method never called. class UserProfileSerializer(serializers.ModelSerializer): branch = serializers.ChoiceField(choices=Branch.choices) class Meta: model = UserProfile exclude = ['user'] def validate_branch(self, branch): print(branch) return branch.upper() class CustomRegisterSerializer(RegisterSerializer): profile = UserProfileSerializer(source="userprofile") @transaction.atomic def create(self, validated_data): validated_profile_data = validated_data.pop('profile') user = User.objects.create(**validated_data) UserProfile.objects.create(user=user, **validated_profile_data) return user I followed this drf docs. -
pgtrigger to update another tables column with COUNT value
I'm trying to use triggers to track total reactions on a Video model. Whenever the Reaction model gets an INSERT or UPDATE request of reaction, it should update the video's reaction count with the value returned from the COUNT function. I just can't seem to understand how to make a simple update statement/function of the Video. Need Help. Current code: class Video(models.Model): ... reaction_count = models.IntegerField(default=0, null=False, blank=False, unique=False) class VideoReaction(models.Model): class Meta: db_table = "video_reaction" triggers = [ pgtrigger.Trigger( name = "VideoReaction_TRIGGER_count", when = pgtrigger.After, operation = pgtrigger.Insert | pgtrigger.Update, func = "id_video__reaction_count = COUNT(reaction)" ) ] id = models.CharField(max_length=10, primary_key=True, null=False, blank=False, unique=True) id_user = models.ForeignKey(User, db_column="id_user", on_delete=models.CASCADE) id_video = models.ForeignKey(Video, db_column="id_video", on_delete=models.CASCADE) reaction = models.BooleanField(null=False, blank=False) ... -
Django how to copy subset of object values to a new object?
I need to create a new Django DB object by inheriting some values from an existing objects. If I just wanted to create a new copy of an objects I would simply do this: objB =OBJ.objects.get(pk=objA_id) objB.pk = None objB.save() But I want only copy certain values from the object. So I would do something like this and simply override the old values I don't want: objB =OBJ.objects.get(pk=objA_id) objB.pk = None objB.key1 = value1 objB.key2 = value2 objB.key3 = None objB.save() My question is if there is a better or “pythonic” way to do that? -
Can you check the null in django-tables2 and make it not included in the table?
First of all, I am sorry for using a translator because I am not familiar with English. I am currently using django-tables2, and it works. However, the null column is included in the table, and I don't want it. Can you check the null in django-tables2 and make it not included in the table? (Not displayed on the screen) -
Based on Consecutive same Item in Python List ,update the item in other list
p=["stay","stay","stay","onmove","onmove"] o=[21,42,376,458,2455] d=[None,None,None,None,None] In p list we have 3 stays and 2 on moves ,so I need to write conditional for loop so that d list item value is updated.So the condition is when the p list has either same consecutive stays or onmoves for example first 3 indexes has stay values and I need to update 3rd index of d list with subtracted value of 3rd and 1st index from o list and next 2 onmoves are there in p list then I would subtract by taking 5th and 4th index value from o list and update 5th index in d list . result would be : d=[None,None,355,None,1997] Actually above list examples are taken for explanations but d list in my case would be duration and o list would timestamps and p is same as stay on move values in it. -
serializer field not showing up
the trips field in carserializer shows up on the response, however, the field tickets in Tripserializer doesn't, the logic looks pretty identical, what am I missing here? from rest_framework import serializers from .models import Car, Ticket,Trip class TicketSerializer(serializers.ModelSerializer): class Meta: model = Ticket fields = '__all__' class TripSerializer(serializers.ModelSerializer): tickets = TicketSerializer(many=True,read_only=True,required=False,source='ticket_set' ) class Meta: model = Trip fields = '__all__' class CarSerializer(serializers.ModelSerializer): trips = TripSerializer(many=True, read_only=True, required=False, source='trip_set') class Meta: model = Car fields = '__all__' here's my models.py from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Car(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE) model = models.CharField(max_length=100) no_plate = models.CharField(max_length=10) pub_date = models.DateTimeField(auto_now=True) imgUrl = models.TextField() def __str__(self): return self.no_plate class Meta: ordering = ["-pub_date"] class Trip(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE) seats = models.IntegerField() price = models.FloatField() start = models.CharField(max_length=200) finish = models.CharField(max_length=200) pub_date = models.DateTimeField(auto_now=True) def __str__(self): return self.request class Meta: ordering = ["-pub_date"] class Ticket(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE) ticket_by = models.ForeignKey(User, on_delete=models.CASCADE) trip = models.ForeignKey(Trip,related_name='tickets', on_delete=models.CASCADE) pub_date = models.DateTimeField(auto_now=True) def __str__(self): return self.question class Meta: unique_together = ("car", "ticket_by") and the views file from rest_framework import generics,status from .models import Car,Trip,Ticket from .serializers import CarSerializer, TripSerializer,TicketSerializer from rest_framework.response import Response from rest_framework.views import APIView from … -
Can't fetch data using react from django rest framework generated api
http://127.0.0.1:8000/api/additionalskills/?format=json This link provides me an API at my localhost. The API is generated by Django Rest Framework. Now I wish to use the API data in my ReacJS application. To do that I followed the way below: const [additionalSkills, setAdditionalSkills]= useState([]); useEffect(() =>{ fetch('http://127.0.0.1:8000/api/additionalskills/?format=json') .then(res=>res.json()) .then(data=> { setAddSkills(data) }) },[]) The API is getting generated well but when I try to fetch data using the API from my React app, the React app gets collapsed. Help me to slove it. -
Can't get details of logged in user (through otp) of a custom user model
I have created a Django application where I have created a custom user model and using login through otp. I want to get the details of the user from the custom user model after he/she is logged in on the societyadmin home page. I have used user.request.get['member_id] and request.POST.get('member_id') both on the views.py and .html file but without any success. I get error - "Could not parse the remainder: '['member_id']' from 'request.POST.get['member']'" Following is my model-: User = get_user_model() class S_Society_Association_Master(AbstractBaseUser): member_id = models.CharField(verbose_name = "Member_ID", primary_key=True, max_length=100, unique=True) member_name = models.CharField(verbose_name = "Member Name", max_length=100) password = models.CharField(verbose_name = "Password", default=NULL, max_length = 100, null=True, blank=True) member_contact_number = models.CharField(verbose_name="Phone Number", max_length=15) otp = models.CharField(max_length=6, blank=False, default=0) # For HOTP Verification member_role = models.CharField(verbose_name="Member's Role", max_length=100, choices=[("P", "President"), ("T", "Treasurer"), ("S", "Secretary"), ("EC", "EC members"), ("O", "Other members")]) member_email_id = models.EmailField(verbose_name = "Member's Email", max_length=100) member_from_date = models.DateField(verbose_name = "Member From", auto_now_add=True) member_to_date = models.DateField(verbose_name="Member To") created_date = models.DateField(verbose_name = "Created Date", auto_now_add = True, blank=True, null=True) created_by = models.ForeignKey(User, to_field='id', related_name = "assoc_created_by", on_delete = models.SET_NULL, verbose_name="Created By", max_length=100, blank=True, null=True) last_updated_date = models.DateField(verbose_name = "Updated Date", auto_now = True, blank=True, null=True) last_updated_by = models.ForeignKey(User, to_field='id', related_name = "assoc_updated_by", … -
probems: ModuleNotFoundError: No module named 'gTTS'
After writing gTTS in settings I found this error below error I also install Django-Gtts -
How to create Quiz Instance from a m2m Model?
I want to create a Quiz App where user can sign in and solve the Quizes which is related to the specific Subject. And the user's data should be stored in the database. In other word, If the user solves the all questions, I have to create a Quiz Instance for him/her. Here i used M2M relationship where many user can solve one subject or one Subject can be solved by many users. When i create Quiz Instance from admin panel it is not giving me an error, But i couldn't create it from views.py. This is my Quiz Model: from django.contrib.auth.models import User ANSWER_CHOICES = ( ("A", "A"), ("B", "B"), ("C", "C"), ("D", "D"), ) # Create your models here. class Subject(models.Model): name = models.CharField(max_length=150, null=True, blank=True) teacher = models.CharField(max_length=200, null=True, blank=True) description = models.CharField(max_length=250, null=True, blank=True) featured_image = models.ImageField(null=True, blank=True, default='default.jpg') created = models.DateTimeField(auto_now_add=True) def __str__(self) -> str: return str(self.name) class Meta: ordering = ['id'] class Quiz(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE, null=True, blank=True) question = models.TextField(null=True, blank=True) a = models.CharField(max_length=50, null=True, blank=True, unique=True) b = models.CharField(max_length=50, null=True, blank=True, unique=True) c = models.CharField(max_length=50, null=True, blank=True, unique=True) d = models.CharField(max_length=50, null=True, blank=True, unique=True) options = models.CharField(max_length=50, choices=ANSWER_CHOICES, blank=True, null=True, default='A') … -
Slice list in python and write if condition
p=["stay","stay","stay","onmove","onmove","stay","onmove","stay","onmove","stay","stay"] k=[1,2,3,4,5,6,7,8,9,10,11] d=[None,None,None,None,None,None,None,None,None,None,None] So in list p ,I have some consecutive stay values and onmove values and some are like one stay and one onmove.I need to write conditions so I could replace None value in respective index of d list. conditions will be like: 1.as we can see in p list there are first 3 consecutive stay values so I need to pick index of first stay and last stay from k list and subtract them(3-1) and store value 2 from this in last stay index(2) respective to d list [None,None,2,None,None,..........] 2.Same above process goes for onmove 2 consecutive pairs in p list . 3.on fifth,sixth index of p list we have stay,onmove so corresponsing to this index in k list subtract values of 6th index and 5th index and store value in 5th index of d list. 4.same avove 3rd point process goes to next indexes. -
Django - One to One field sometimes not saving the value assign on field after save call without errors
We are currently experiencing an issue with a one-to-one field in Django where the data was not stored after assigning a value and save call is successful without any error. This does not happen to all the records. I'd say 60% of it was not saving and 40% was saving. This only happens on our production server where there are millions of rows for Model1 and Model2 and there are so many processes ongoing. We also assign a value to other fields and call save on other parts of the process after the link_item method is called. models.py class Model2(models.Model): # Some other fields here class Model1(models.Model): field1 = models.OneToOneField(Model2, on_delete=models.SET_NULL, null=True, blank=True, default=None) # Some other fields here def link_item(self, model2_id): logger.info(f'Linking {self.id} to {model2_id}') field1 = Model2.objects.get(id=model2_id) self.field1 = field1 self.save() logger.info(f'Field 1 was set to {self.field1}') views.py import module def my_view(requests): model1_obj = Model1.objects.get(id=model1_id) result = module.another_function(model1_obj, request_data) return result module.py def another_function(model1_obj, request_data): logger.info(f'Request data was {request_data}') if request_data['status'] == 'completed': model1_obj.some_process() # .save() is called here after assigning a value to attribute model1_obj.some_process2() # .save() is also called here after assigning a value to attribute model1_obj.link_item(request_data['model2_id']) # Logs were shown but field1 value was not … -
call functions based on dynamic list from the user
I have a report generating API in my django app which takes name of reports as input from the user, user can multiselect different reports from the dropdown reports = request.GET['reports'].split(',') example: print("selected reports", reports) >>seleceted reports ['AS', 'DD', 'IS', 'LM'] now this reports can vary according to the user and I have a dictionary of all the functions to create these reports master = { 'AS': audit_summary(), 'AH': audit_health(), 'MS': missing_scan(), 'IS': individual(), 'LM': loc_mis(), 'MAS': missing_assets(), 'DD' : dump(), } How can I call the functions from the dictionary based on the dynamic list I get from user? -
Convert string to django query set
I want to make a custom query builder function like, def query_builder(string): return Q() Input might can be, string = "(data eq 2022-09-13) AND ((username eq something) AND ((age lt 20) OR (age gt 10)))" Return value should be, Q(Q(date='2022-09-13') & Q(Q(username='something') & Q(Q(age__lt=20) | Q(age__gt=10))))) Any help will be appriciated. -
Scheduled messages are sent at difference of 5 hours 30 minutes in Twilio and Sendgrid api
I am working on a Django application where I have used twilio to send sms and whatsapp messages and the sendgrid api for sending the emails. The problem occurs in scheduled messages in all three. For example, if I have schedule an email to be sent at 06:24 PM(scheduled time is 06:24 PM), then I am receiving the email at 11:54 PM, hence the difference is of 5 hours and 30 minutes. The same problem also arises in sms and whatsapp. I think the problem might be due to the timezone. I am scheduling the messages from India and twilio account is in USA. And, the time difference of 5 hours 30 mins is due to the UTC format as India is 5 hours 30 mins ahead of UTC. But I am not getting any solution for this. So, is there any specific way to solve this problem ? -
Django - send email as html (django-sesame )
Hy, I don't know how to send email as html. I try every example that can i find but i don't know how to implement in my code. When it's arive in mail show all the html not only the the message. Please help me to implement send as html format in my code below. Thank you def email(request): campanii = Campanie.objects.order_by('-pub_date') if request.method == 'POST': form = EmailLoginForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'].lower() user = UserVot.objects.filter(email=email).first() if user is None: # daca userul nu exista cu acea adresa de email messages.error(request, "adresa de email nu este corecta sau valida") return render(request, 'loginvot/email.html', {'form' : form, 'campanii':campanii , 'error_message' : "adresa de email nu este corecta sau valida"} ) link += sesame.utils.get_query_string(user) user.email_user( subject="Link vot", message="""\ <html > <head> <meta charset="UTF-8"> </head> <body> <p> Salutare, <h4>{{user.username}}</h4></p><br> <p>Acceseaza link-ul de mai jos pentru a intra in sectiunea de vot "Ambasadorii Valorilor Profi"</p><br> {{link}} </body> </html> """ ) return render(request, 'loginvot/email.html', {'campanii':campanii , 'error_succes' : "in maximum 1 minut vei primi pe adresa de email completata un link de accesare sesiune de vot"} ) context = {'form' : EmailLoginForm, 'campanii' : campanii} return render(request, 'loginvot/email.html', context) -
ModuleNotFoundError: No module named '_tkinter' after Heroku Deployment
I am trying to deploy my Django Application on Heroku. After deployment, my app crashed and it gives the No module name _tkinter error. I am not using it, may be it's being used in some library or package. I have deployed a few apps before on Heroku but never got this error. I also went through other answers but they are mostly associated with sudo etc. I am deploying it from windows. Please let me know on how to fix this, as I couldn't find any `_tkinter' package either. -
Django - How do I set default value to primary key
I have made custom User model with AbstractBaseUser. and I'm trying to make the primary key of the class to start from certain numbers as new users sign up to the site. Such as '2022001' - '2022002' - '2022003' and so on. I have searched on stack overflow and other sources, and some people suggest define function within the custom user's class model, but i have failed to do that. is there a simple way to generate auto_increment number starting with the custom number from models.py ? or Is it possible for me to give that certain number in views.py as new users sign up?. here is my register function. from views.py def register_user(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) messages.success(request, ("You have successfully registered.")) return redirect('home') else: form = RegistrationForm() return render(request, 'register/register_user.html', {'form' : form}) Thank you -
how to work with id in postgresql via django
I am learning django, making a video tutorial on creating a site on django + postgresql and ran into the following problem. When working with postgresql through django admin (model), I create products that are automatically assigned an id. At first everything goes correctly - products are created starting from id 1 and further on ascending. But if you delete the first product (which has id=1) through django admin, then the id of the remaining products does not change, that is, the product whose id was equal to 2 does not become a product whose id is equal to 1. Which looks extremely illogical. Tell me , please, how to make it so that when the first product is deleted, the id of all the rest logically changes (i.e. id=2 changes to id=1 and so on)? -
Issue with login endpont for Django REST Framework, The Registration was successful but the login doesn't authenticate, pls check LoginAPIView
views.py - This is my authentication.views file from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from django.contrib.auth import authenticate from authentication.serializers import UserLoginSerializer, UserRegistrationSerializer class UserRegistrationView(APIView): def post(self, request, format=None): serializer = UserRegistrationSerializer(data=request.data) if serializer.is_valid(raise_exception=True): user = serializer.save() return Response( {"msg": "Registration Successful"}, status=status.HTTP_201_CREATED ) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # The issue I'm having is at this point, all code seems write but still getting errors class UserLoginView(APIView): def post(self, request, format=None): serializer = UserLoginSerializer(data=request.data) if serializer.is_valid(raise_exception=True): email = serializer.data.get('email') password = serializer.data.get('password') user = authenticate(password=password, email=email) # This line above and below this comment if user is not None: return Response({"msg": "Login Successful"}, status=status.HTTP_200_OK) else: return Response( { "errors": { "non_field_errors": ["Email or Password is not valid"] } }, status=status.HTTP_404_NOT_FOUND ) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py - This is my authentication.serializers file from rest_framework import serializers from authentication.models import User # Below are the UserRegistrationSerializer and UserLoginSerializer class UserRegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={"input_type": "password"}, write_only=True) class Meta: model = User fields = ["email", "username", "password", "password2"] extra_kwargs = {"password": {"write_only": True}} def validate(self, attrs): password = attrs.get("password") password2 = attrs.get("password2") if password != password2: raise serializers.ValidationError( "Password and Confirm Password does not match" ) return attrs def create(self, …