Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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, … -
ModuleNotFoundError: No module named 'PIL' For virtual Environment
The Pillow library is installed for my Python environment my_proj still it is throwing the Error PIL module is not there. -
Django(Python),Assign value stay or on_move to the field row in Model
def mark_stay_location(): if TestLocation.objects.filter(processed=None): k = TestLocation.objects.filter(processed=None).order_by("timestamp") p = len(k) list_lat1 = [] list_lat2 = [] list_long1 = [] list_long2 = [] for i in range(p - 1): rowpairs = k[i : i + 2] lat1 = rowpairs[0].latitude list_lat1.append(lat1) lat2 = rowpairs[1].latitude list_lat2.append(lat2) long1 = rowpairs[0].longitude list_long1.append(long1) long2 = rowpairs[1].longitude list_long2.append(long2) lat = abs(lat2 - lat1) long = abs(long2 - long1) a = sin(lat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(long / 2) ** 2 c = 2 * atan2(sqrt(a), sqrt(1 - a)) for rowpair in rowpairs: row_id = rowpair.id po = TestLocation.objects.filter(id=row_id) if lat < 0.0009 or long < 0.0009: po.update(stay="stay") po.update(processed=True) else: po.update(stay="on_move") po.update(processed=True) print(list_lat1) print(list_lat2) print(list_long1) print(list_long2) duration() return Response(status=status.HTTP_200_OK) else: return Response(status=status.HTTP_404_NOT_FOUND) in database,TestLocation model fields are getting stored with values ,In above function k is querying all rows which have processed=None so far example it gives 100,then I'm using for loop using it's range and iterating with each consecutive pair of rows .In this pair I have latitude and longitude in each item of list and I used if condition if either the difference between lat or long between both items of lists is less than 0.0009 then I should set the … -
Using Signals to create data in a Django project once a boolean is changed
I have a question regarding signals. So I have the following model that has a boolean defaulted as False. Once the user clicks on a button to make it true I want to create objects in another model. Here is what I have done but did not create or make any changes: Here is the Initial Model: class Initial_Model(models.Model): active = models.BooleanField(default=False) Here is the model that I want to create objects once the Initial_Model active boolean becomes True: class ActiveSession(models.Model): start_date = models.DateTimeField(auto_now_add=True,blank=True, null=True) end_date = models.DateTimeField(auto_now_add=True,blank=True, null=True) @receiver(post_save, sender=Initial_Model) def create_session(sender, instance, **kwargs): if Initial_Model.active == True: ActiveSession.objects.create() My question is this the correct way of creating the instances in a model. What am I doing wrong and how to fix it. -
request an memory-eating endpoint many times before cache reproduced
I have an endpoint which consume lots of memory, so I use caching to reduce the memory overhead, but the problem is that, if user request it manytimes before the cache produced, it will consume lots of memory and cause oom killer, how can I handle this ? I tried use some limiter like flask-limiter, it just stop request again. the request doesn't use cached results. any help would be appreciated -
How to prevent file corruption/damaging during download from FTP to Django FileField
I have some excel and pdf files that can be opened and viewed correctly. They are probably old versions of both. However, after downloading these files from FTP and saving them to a Django FileField, they become damaged and can no longer be opened. All I need is to maintain the file as is during the transition. Unfortunately, I can't share any of the files as they contain confidential information. Here is the part of the code used to download and save the files: with io.BytesIO() as f: ftplib_connection.retrbinary('RETR ' + filename, f.write) f.seek(0) content_file = ContentFile(f.read(), filename) # Try f.getvalue(), f.getbuffer() return content_file # This will be saved to a Django FileField About the mimetypes, I used python-magic. All the pdf files are application/pdf. The excel files however are mostly application/CDFV2. Please note that I can open and view these files in their original state. The problem is after they are fetched from an FTP server and saved to a Django FIleField. -
Why can't I delete a custom function in django models migration?
I created a custom function to use in another class models.py class DateRangeFunc(models.Func): function = "daterange" output_field = DateRangeField() class Foo(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=256) start_datetime = models.DateField() end_datetime = models.DateField() class Meta: constraints = [ ExclusionConstraint( name="exclude_overlapping", expressions=( ( DateRangeFunc( "start_datetime", "end_datetime", RangeBoundary() ), RangeOperators.OVERLAPS, ), ), ), ] DateRangeFunc is the custom method I created to help write an exclusion constraint. I want to delete the Foo model as well as the DateRangeFunc class because both are not used anymore. When I try to makemigrations after removing both from models.py I get the following error: File "foo/migrations/0012_auto_20220907_1238.py", line 31, in Migration constraint=django.contrib.postgres.constraints.ExclusionConstraint(expressions=((foo.models.DateRangeFunc('start_datetime', 'end_datetime', django.contrib.postgres.fields.ranges.RangeBoundary()), '&&')), name='exclude_overlapping'), AttributeError: module 'foo.models' has no attribute 'DateRangeFunc' because it is still present in the old migration file 0012_auto_20220907_1238.py https://docs.djangoproject.com/en/4.1/topics/migrations/#considerations-when-removing-model-fields I should be able to add a system_check_removed_details if necessary (it is not in my case) and then squash -> remove models -> remove migration file. i.e. "Keep this stub field for as long as any migrations which reference the field exist. For example, after squashing migrations and removing the old ones, you should be able to remove the field completely." However, I can't run a squash because the … -
cannot response 'passenger__email' on the tripview class
i try to response passenger_email field on trip view but cannot response. the code on my program is here below. the main problem is here passenger__email class TripView(viewsets.ReadOnlyModelViewSet): lookup_field = 'id' lookup_url_kwarg = 'trip_id' serializer_class = NestedTripSerializer permission_classes = (permissions.IsAuthenticated,) # call only id and status field of trip model def get_queryset(self): user = self.request.user if user.group == 'passenger': #request to all drivers passenger_trip = Trip.objects.filter(passenger=user) #display only id and status field of trip model and user.email return passenger_trip.values('id', 'status', 'created', 'updated', 'pick_up_address', 'drop_off_address', 'price', 'passenger__email') return Trip.objects.none() the response code on postman is here below:- [ { "id": "412f04aa-3b34-4ee4-a07f-e464cff148c3", "created": "2022-09-12T12:27:31.542074Z", "updated": "2022-09-12T12:27:31.542091Z", "pick_up_address": "pokhara", "drop_off_address": "kathmandu", "price": "20", "status": "REQUESTED" } ] The urls of the code is here below app_name = 'taxi' urlpatterns = [ path('', TripView.as_view({'get': 'list'}), name='trip'), path('<uuid:trip_id>/', TripView.as_view({'get': 'retrieve'}), name='trip'), path('create/', CreateTripView.as_view(), name='create_trip'), ] -
Setting a route for a specific method in Django
I'm working with REST API in django from scratch. I mean, I'm not working with DjangoRestFramework directly, but i am using Class-BasedViews and some things from RestFramework. So, I am trying to return a GET response for all my actors but the problem is that I already have another GET response into my urls.py for the list of movies and Django returns the one who is first. Do you have any idea to solve this? Here is my Models, Views, and urls.py class Actor(models.Model): full_name = models.CharField(max_length=125) role = models.CharField(max_length=125) def __str__(self): return self.full_name @classmethod def find_actors(cls): actors = Actor.objects.all().order_by('pk') actors_list = [] for actor in actors: actors_list.append({ "full_name": actor.full_name, }) return actors_list class Movie(models.Model): ACTION = 'AC' DRAMA = 'DR' COMEDY = 'CM' SCIENCE_FICTION = 'SF' THRILLER = 'TR' RELIGIOUS = 'RG' GENRE_CHOICES = [ (ACTION, 'Accion'), (DRAMA, 'Drama'), (COMEDY, 'Comedy'), (SCIENCE_FICTION, 'Ciencia Ficcion'), (THRILLER, 'Triler'), (RELIGIOUS, 'Religioso') ] title = models.CharField(max_length=155, blank=False) synopsis = models.TextField(max_length=1000, blank=True) genre = models.CharField(max_length=100, choices=GENRE_CHOICES, default='', blank=False) tag = models.JSONField(default=dict, blank=True) actors = models.ManyToManyField(Actor, related_name='movies', blank=True) def __str__(self): return self.title @classmethod def find_all_movies(cls): movies = Movie.objects.filter(actors__isnull=False).distinct().order_by('pk') movie_list = [] for movie in movies: movie_list.append({ "id": movie.id, "title": movie.title, "synopsis": movie.synopsis, "genre": movie.genre, "tag": … -
Automatically create a model when another with ForeignKey is created
I'm trying to create a registration process where a certain model (Member) is automatically created when I create the model UserFields, but I'm unable to find a solution; this is what I tried: Models.py class Member(models.Model): member_id = models.AutoField(primary_key=True) user_creation_date = models.DateField(auto_now_add=True) Forms.py class MemberFieldsForm(forms.ModelForm): class Meta: model = MemberFields fields = [ "social_security_id", "first_name", "last_name", "birth_date", "birthplace", "gender", "admission_date", ] labels = { "social_security_id": "SSN", "first_name": "First name", "last_name": "Last name", "birth_date": "Date of birth", "birthplace": "Place of birth", "sex": "Sex", "address": "Address", "admission_date": "Admission date", } widgets = { "member_type": forms.TextInput(attrs={'class': 'form-control'}), "social_security_id": forms.TextInput(attrs={'class': 'form-control'}), "first_name": forms.TextInput(attrs={'class': 'form-control'}), "last_name": forms.TextInput(attrs={'class': 'form-control'}), "birth_date": forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}), "birthplace": forms.Select(attrs={'class': 'form-control'}), "address": forms.Select(attrs={'class': 'form-control'}), "sex": forms.Select(attrs={'class': 'form-control'}), "admission_date": forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}), "member_type": forms.Select(attrs={'class': 'form-control'}), } Views.py def index(request): if request.method == 'POST': form = MemberFieldsForm(request.POST) if form.is_valid(): c = form.changed_data["Member"] member = Member.objects.filter(name=c).first() if not member: member = Member.objects.create(name=c) MemberFields = form.save(commit=False) MemberFields.Member = Member MemberFields.save() return HttpResponse("Member registered") else: form = MemberFieldsForm() return render(request, 'add-member.html', {'form': form}) -
Postmark Webhook Signature Security
https://postmarkapp.com/developer/webhooks/webhooks-overview https://<username>:<password>@example.com/webhook Looking through the Postmark API, there does not seem to be any information about webhook signatures or tokens or hmac for security. The only security mentioned is basic authentication or firewalls. How do you even set up basic authentication or firewalls to work with Postmark webhooks? Is there anything that needs to be done on nginx or apache? Basic authentication like this? requests.post('url',headers=headers,auth=('username','password'), json=json_data) To me that does not seem as secure than signature verification. Other APIs like Mailgun have signatures and tokens and hmac for verifying webhooks in the request header. Mailgun Example: import hashlib, hmac def verify(signing_key, token, timestamp, signature): hmac_digest = hmac.new(key=signing_key.encode(), msg=('{}{}'.format(timestamp, token)).encode(), digestmod=hashlib.sha256).hexdigest() return hmac.compare_digest(str(signature), str(hmac_digest)) @csrf_exempt def mailgun_webhook(request): body_unicode = request.body.decode('utf-8') body = json.loads(body_unicode) signature = body['signature']['signature'] token = body['signature']['token'] timestamp = body['signature']['timestamp'] webhook_signing_key = 'KEY' if verify(webhook_signing_key, token, timestamp, signature) is True: print('do something') return HttpResponse(status=200) -
How to loop through an array in python
how to loop through this array and display the values en python {"products":[ { "desi":"kakakaka", "price":1400 }, { "desi":"mamama", "price":5000 }, ] } -
How can i enable the agent instance to be available in my agent update form when the agent is connected to the user through a one to one field
models.py class Auto(models.Model): user = models.OneToOneField("User", on_delete=models.CASCADE) def __str__(self): return self.user.username class User(AbstractUser): pass # To categorize users either as an organisor or as an agent is_organisor = models.BooleanField(default=True) is_agent = models.BooleanField(default=False) agent_details = models.TextField(null = True, blank=True) class Agent(models.Model): user = models.OneToOneField("User", on_delete=models.CASCADE) organisation = models.ForeignKey("Auto", on_delete=models.CASCADE) def __str__(self): return self.user.username views.py class Agent_update(ManualLoginRequiredMixin, generic.UpdateView): template_name = 'agent-update.html' form_class = AgentUpdateForm queryset = Agent.objects.all() context_object_name = 'agents' def get_success_url(self): return reverse('reverse url') agent-update.html <form method="post"> {% csrf_token %} {{form|crispy}} <button>Update Agent</button> </form> After running the server the form works but dosen't display the instance of the particular agent being updated. I feel it is because the Agent model is connected to the User model. Any help would be appreciated -
django_celery_beat task one_off=True does not start
django_celery_beat task one_off=True не стартует Я создаю объект задачи celery_beat, но она не срабатывает по времени ClockedSchedule models.py clocked, _ = ClockedSchedule.objects.get_or_create( clocked_time=datetime.utcnow() + timedelta(minutes=1) ) PeriodicTask.objects.create( clocked=clocked, one_off=True, name=f'CERTIFICATE SMS TASK {self.id}', task='apps.discounts.tasks.send_certificate_message', args=json.dumps([self.id]), start_time=datetime.utcnow() + timedelta(minutes=1), expires=datetime.utcnow() + timedelta(days=1) ) tasks.py @app.task(bind=True) def send_certificate_message(self, certificate_id) -> None: """ Task is not running """ ... Help, what does it take to run a celery_beat task once by ClockedSchedule?