Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to resend verification email django restframework?
I can send a verification email upon registering the user so that the account can be activated. But how would one go about resending another verification email on an API? Here, I am making an activation link with a token in it and when the user opens the link it takes the token and verifies the user. But how would resending the verification email work? class RegisterUser(APIView): serialzer_class = RegisterSerialzer def post(self, request): user = request.data serializer = self.serialzer_class(data = user) serializer.is_valid(raise_exception = True) serializer.save() user_data = serializer.data # user = User.objects.get(username=serializer.data['username']) # print(user.id) # token = Token.objects.create(user=user) user = User.objects.get(email = user_data['email']) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relativeLink = reverse('email-verify') absurl = 'http://'+current_site+relativeLink+"?token="+str(token) email_body = 'Hi '+ user.username + 'user the link below to verify your email \n' + absurl data = {'email_body':email_body,'to_email':user.email, 'email_subject':'Verify your email'} Util.send_email(data) class VerifyEmail(APIView): def get(self, request): token = request.GET.get('token') try: payload = jwt.decode(token, settings.SECRET_KEY) user = User.objects.get(id=payload['user_id']) user.is_verified = True # user.is_authenticated = True user.is_active = True # if not user.is_verified: user.save() return Response({'email':'successfuly activated'}, status=status.HTTP_200_OK) # except jwt.ExpiredSignatureError as identifier: except jwt.ExpiredSignatureError: return Response({'error':'Activation Expired expired'}, status=status.HTTP_400_BAD_REQUEST) # except jwt.exceptions.DecodeError as identifier: except jwt.exceptions.DecodeError: return Response({'error':'invalid token'}, status=status.HTTP_400_BAD_REQUEST) -
I can't figure out what to write in HTML?
Help write html code to display video posts on the site I am new to Django I don't know what to write in HTML to display the post I added in django-admin Tried adding a form and this way to add the post didn't work I would be glad to get any help -
how to convert group by(values) to json - django
i'm trying to convert my grouped by (values in django) data into JsonResponse but it raise this error : AttributeError: 'dict' object has no attribute 'f_type' this is my function of loadding json data def load_cate(request): lists = Room.objects.values('f_type','room_type', 'beds', 'balcon').annotate(total=Count('pk')).order_by('-total') data = [] for i in lists.values(): item = { 'wc_type':i.f_type, 'room_type':i.room_type, 'beds':i.beds, 'balcon':i.balcon, 'total':i.total } data.append(item) return JsonResponse({'success':True,'data':data}) is there something i did wrong ? or its different for group by values ?! thanks in advance .. -
How to channel data thru Django's URL from third party URL without using redirecting?
What kind of existing options there is to make the client's GET "myserver://api/download/12345.jpg" to download from some_cloudfront_server://files/12345.jpg without redirecting the client to that CloudFront-path? Ie. I want the client see only myserver://api/download/12345.jpg all the time. It should be some kind channeling solution, as downloading a full file first to Django-server and then sending it to the client is not applicable (takes so much time that the client will see timeout before a response to its query comes). Any existing libraries for this? If I have to create one myself, I welcome even just tips where to start from as Django's communication layer is not too familiar to me. Problem here is that we are creating CloudFront signatures with wildcards to certain set of files, in format files/<object_id>*, thus allowing access only to certain object's all files. This works fine as long as file access traffic from clients is low. But if we start creating separate access signatures for hundred different files at same time, CloudFront starts throttling our requests. Solution I came up is to create and store to Django-server one generic allow-all signature for files/*, which is used only by Django-server and never given to any client, and then … -
How user can send a from to another user in my platform - django
I m working on a web app with django, it's actually like a platform that contains a lot of registered users. One user have to send like a form to another user through the app. And that user when he gonna open a page he can see a table that contains all forms sent by users. -
Display data from two different models in one html table using Django
I have two models namely StudentInfo & StudentAdmission. student_id is foreign key in StudentAdmission model. I want to display the values of both models together in one html table. How could I do that. models.py file: from django.db import models from datetime import datetime # Create your models here. class StudentInfo(models.Model): gender_choice = ( ("male", "Male"), ("Female", "Female"), ) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) gender = models.CharField(choices=gender_choice, max_length=10) dob = models.DateField(default=datetime.now, blank=True) address = models.CharField(max_length=100) email = models.EmailField(max_length=100) phone = models.CharField(max_length=100) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') def __str__(self): return self.firstname class StudentAdmission(models.Model): class_choice = ( ("one", "one"), ("two", "two"), ("three", "three"), ) section_choice = ( ("A", "A"), ("B", "B"), ("C", "C"), ) transport_choice1 = ( ("abc", "abc"), ("bcd", "bcd"), ("def", "def"), ) transport_choice2 = ( ("ab", "ab"), ("bc", "bc"), ("de", "de"), ) admission_no = models.CharField(max_length=100) admission_date = models.DateField(default=datetime.now, blank=True) roll_no = models.CharField(max_length=100) email = models.EmailField(max_length=100) username = models.CharField(max_length=100) password = models.CharField(max_length=100) class_name = models.CharField(choices=class_choice, max_length=10) section_name = models.CharField(choices=section_choice, max_length=10) transportation = models.CharField(choices=transport_choice1, max_length=10) transport_vehicle = models.CharField(choices=transport_choice2, max_length=10) student_name = models.ForeignKey(StudentInfo, on_delete=models.CASCADE) def __str__(self): return self.username I want to display related class_name and section_name in following table -
Django's infinite streaming response logs 500 in apache logs
I have a Django+Apache server, and there is a view with infinite streaming response def my_view(request): try: return StreamingHttpResponse(map( lambda x: f"{dumps(x)}\n", data_stream(...) # yields dicts forever every couple of seconds )) except Exception as e: print_exc() return HttpResponse(dumps({ "success": False, "reason": ERROR_WITH_CLASSNAME.format(e.__class__.__name__) }), status=500, content_type="application/json") When client closes the connection to the server, there is no cleanup to be done. data_stream will yield one more message which won't get delivered. No harm done if that message is yielded and not received as there are no side-effects. Overhead from processing that extra message is negligible on our end. However, after that last message fails to deliver, apache logs 500 response code (100% of requests). It's not getting caught by except block, because print_exc doesn't get called (no entries in error log), so I'm guessing this is apache failing to deliver the response from django and switching to 500 itself. These 500 errors are triggering false positive alerts in our monitoring system and it's difficult to differentiate an error due to connection exit vs an error in the data_stream logic. Can I override this behavior to log a different status code in the case of a client disconnect? -
How to solve this django query problem without using the for loop?
I have a query containing a list of submissions by users. Models are below, but here's the gist: Each submission belongs to one problem that user tried to solve. However, user can make as many submission as they want for a single problem. There are several problems. submissions are ordered by time of creation (descending) I need to get a list of all the final submissions by users. final submission is the last submission of user for a specific problem. Naturally, if user solves several problems then they would have as many final submissions. How can I get this? Here is what I got so far but I dont know how to go on: all_users = list_users(contest_id) #query of all users in contest problems = list_problems(contest_id) #query of all problems in contest final_submissions = Submission.objects.none() for user in all_users: for problem in problems: query = list_problem_user_submissions(contest_id, user.id, problem.id)[:1] if query.exists(): final_submissions.union(query) This doesnt work, but I also cant think of anything without a for loop. Is there a way to remove that loop and do it straight in query? Here are the models: **User**: default django user model Contest: name = models.CharField(max_length=50) holder = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.DateTimeField() finish_time … -
How to get the user associated to another model DRF. ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing
I want to check that the card number is exists and then get the associated user to that card number. A user can have multiple card numbers. How do I filter to get the user from the card number entered? Models: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name="Email Field", max_length=60, unique=True) dateJoined = models.DateTimeField( verbose_name="Date Joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="Last Login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_verified = models.BooleanField(default=False) # Parameters that we want to know about the user first_name = models.CharField(verbose_name="First Name", max_length=100) last_name = models.CharField(verbose_name="Lasst Name", max_length=100) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = CustomUserManager() def __str__(self): return self.email def tokens(self): refresh = RefreshToken.for_user(self) return { 'refresh': str(refresh), 'access': str(refresh.access_token) } def has_perm(self, perm, obj=None): return self.is_superuser def has_module_pers(self, app_label): return True class cardModel(models.Model): user = models.ForeignKey(CustomUser, related_name='card_numbers',null = True, blank=True, on_delete=models.CASCADE) card_number = models.IntegerField( verbose_name="Card Number", blank=True, null=True, default=None, unique=True) def __int__(self): return self.card_number Serializer: class CheckCard(serializers.Serializer): card_number = serializers.IntegerField(write_only=True) class Meta: fields = ['card_number','user'] read_only_fields = ['user'] Views: class CheckCardAPI(APIView): permission_classes = [AllowAny] serializer_class = CheckCard def post(self,request,*args,**kwargs): serializer = self.serializer_class(data=request.data) card_number = request.data.get('card_number','') if cardModel.objects.filter(card_number=card_number).exists(): user = User.objects.filter(card_numbers=card_number) tokens, created = Token.objects.get_or_create(user=user) return Response({'token':tokens.key},status=status.HTTP_200_OK) else: … -
how to install python packages locally inside virtual environment
I am trying to install packages from my requirements.txt file but I am getting this error, it's interesting because I don't have any project dependency as such and I have already ran pip install -r requirements.txt error I am getting File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django_sass' I want to install these dependencies such that they should be local only to the project I am working on, any idea how to achieve that ? -
Django run durable transaction via gunicorn
I have a django (3.2v) application with an atomic based transaction which uses durable option @transaction.atomic(durable=True) def get_account(): ... I'm able of running my project via python manage.py runserver and everything works fine. But when I run my project via gunicorn --bind :8000 --workers 3 myapp.wsgi:application I get the following error: TypeError: atomic() got an unexpected keyword argument 'durable' after removing durable=True param from atomic decorator like the code below, everything works like a charm. @transaction.atomic def get_account(): ... why this happens? how can I make this work? -
linebreaks not working properly in djagno
My linebreaks are not working when i try to use a custom filter and safe in my web site for publishing post. html: <p>{{ text|striptags|linebreaks|mention|safe }}</p> mention is my custom filter and my templatetags is: @register.filter(name='mention',is_safe=True) @stringfilter def mention(value): res = "" for i in value.split(): if i[0] == '#': if len(i[1:]) > 1: i = f'<a href="/recommendation/?q=%23{i[1:]}&submit=Search">{i}</a>' res = res + i + ' ' return res at the end i am using 'safe' so that the user can see the link.it is working but when i type linebreaks i am not seing the linebreaks inside my html.What am i doing wrong ? do i have problem in ordering my filter ? -
How to show Language code in field label in Django translated fields
i used django translated fields to create some monolingual fields in my models. It works good, but in admin page, in add page, there is two same fields for every translated fields i created. How can i show language code for each field? What it is showing now What i want it to be -
Select a valid choice. 6da87c51321849bdb7da80990fdab19b is not one of the available choices
I'm using answers field in form for just test purpose to see if it is returning the selected id of the value in post request when form is submitted, also I'm passing choices dynamically to the from views using get_form_kwargs(), On frontend it shows me proper choices but when one selected and submitted it shows me the error mentioned in Subject of this question Also FYI i have not included "answerss" field in models because i just wanted to test if it returns correct id on POST request. This is my Dynamically passed List from views.py to forms.py to fill the choices of "answerss" field created in init . This list keeps changing after every submission Also FYI this is a Quiz app so after every submission i redirect it into the same page where next question is rendered and different options are rendered in choice field [('d5730fbb3b1742d183d0968802859c7d', 'Africa'), ('6da87c51321849bdb7da80990fdab19b', 'Asia'), ('e0d084ff6e7544478523149186835132', 'North America')] This is my model.py class userAnswer(models.Model): answer_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user_id= models.ForeignKey(CustomUser,on_delete=models.CASCADE) question_id = models.ForeignKey(question,on_delete=models.CASCADE) text_ans = models.CharField(max_length=100) remaining_time = models.TimeField(default='23:00:00') correct_Answer_id = models.ForeignKey(correctAnswer,on_delete=models.CASCADE) This is my views.py class Start_Game(FormView): model = userAnswer template_name = 'test_template.html' form_class = Useranswer success_url = 'game' context_object_name = 'questions' … -
Foreign Key field is not registering in Database
I add a new foreign key in my model but it gives an error once I migrate. Field 'id' expected a number but got 'XD'. MODEL: item_tool= models.ForeignKey(Tools,default='XD', on_delete=SET_DEFAULT) CLASS: class Tools(models.Model): name = models.CharField(max_length=200) class Meta: verbose_name_plural = 'Tools' def __str__(self): return self.name -
как сохранить картинку через URL в модель django
Необходимо разработать сервис, на основе фреймворка Django, который позволит загружать изображения с компьютера пользователя, или по ссылке, а затем изменять их размер используя библиотеку Pillow. Изображения должны сохраняться на диск. У меня получилось реализовать загрузку с компьютера, а вот по ссылке URL не получается. Моя модель: from django.db import models class Image(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='images') def __str__(self): return self.title Моя форма: from django import forms class ImageForm(forms.Form): title_image = forms.CharField(max_length=200, label='Заголовок') url_image = forms.URLField(max_length=255, label="URL файла", required=False) image_image = forms.ImageField(label='Файл ', required=False) Моя вьюха: from urllib.request import urlopen import requests from django.core.files.base import ContentFile, File from django.core.files.temp import NamedTemporaryFile from django.shortcuts import render, redirect from .forms import ImageForm from .models import Image def image_upload_view(request): """ Загрузка файлов пользователем и обработка""" if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): if request.POST['url_image']: print('НЕ ПУСТАЯ УРЛА!') url = request.POST['url_image'] img_temp = NamedTemporaryFile(delete=True) img_temp.write(urlopen(url).read()) img_temp.flush() print(img_temp) resp = requests.get(url).raw print(ContentFile(resp)) # all_data['image'] = File(img_temp) image_save = Image(title=request.POST['title_image'], image=resp) image_save.save() img_obj = image_save return render(request, 'upload_app/index.html', {'form': form, 'img_obj': img_obj}) # # url = request.POST['url_image'] # # # # # try: # # resp = requests.get(url) # # result = urllib.request.urlretrieve(url) # # print(result) # # image_save = Image(title=request.POST['title_image'], image=ContentFile(resp.content)) … -
Declare Name/Variable with Docker Compose
Currently I am experimenting with Docker Compose but I want to declare a variable or something and some parts of my code and my Foldername get changed when I run docker-compose run ... Is that even possible with Docker? I cannot find something in the Web or on Stackoverflow. Thank you! -
Django .defer() for removing value from queryset
def get_client_queryset(query=None): queryset = [] queries = query.split(' ') for q in queries: details = clients.objects.filter( Q(name__icontains=q) | Q(number__icontains=q) | Q(email__icontains=q) ).distinct().defer(unique_num) for client in details: queryset.append(client) return list(set(queryset)) the .defer('unique_num') is still being returned and displayed in the queryset. The provided function is a search function -
django celery shows the error -- Process "ForkPoolWorker-1" pid:41 exited with "exitcode 70"
I have a celery scheduled task in my django which runs at 4 PM. After the implementation of this scheduled task it worked smoothly and doesn’t shows any error. Yesterday my celery task was failed due to below error Process "ForkPoolWorker-1" pid:41 exited with "exitcode 70" Task handler raised error: WorkerLostError('Worker exited prematurely: exitcode 70 Job: 1.')` I don’t know why this error is coming. I am using Django==3.2.4 celery==5.1.2 Some depreciation warning is also showing version 6.0.0. Use the accept_content instead The 'CELERY_TIMEZONE' setting is deprecated and scheduled for removal in alternative=f'Use the {_TO_NEW_KEY[setting]} instead') can any one help me to solve the above.My celery task is not a long running task. -
Export data from mongodb collection to excel with openpyxl
I want to export my mongodb collection to excel file using openpyxl but I can not figure out how to do this... I want to have something like the picture below can anyone help me? -
How would you design django app with multiple alerts
I have an app that tracks bitcoin and other cryptocurrencies, now let's say that each user can create multiple alerts against that price, for example buy cryptocurrency A when it reaches price X or sell B when it reaches price Y, and the database must be a SQL most likely Postresql. Now I had some architectures in my mind but all of them are non efficient means they use more resources than they should so I'm looking at the most optimum design for that kind of apps. -
How to change forms datefield from Gregorian calendar to Persian calender in django forms?
I want to get date from user with form without using models, But django DateField only have Gregorian calender. How can i change that to Persian(Jalali, Farsi, Solar) calender? forms.py class filterForm(forms.Form): month = forms.DateField(widget=forms.widgets.DateInput(attrs={'type': 'date'})) -
I am having a problem with Django logging in a user
I am getting a problem with the login, I am following a tutorial class from Dennis on Django and for some reason I have getting this type error? What does it mean. Thank you TypeError at /login/ 'bool' object is not callable Request Method: GET Request URL: http://127.0.0.1:8000/login/ Django Version: 3.2.6 Exception Type: TypeError Exception Value: 'bool' object is not callable Exception Location: C:\Users\inter\OneDrive\Django_Course\devsearch\users\views.py, line 48, in loginUser Python Executable: C:\Users\inter\OneDrive\Django_Course\devsearch\env\Scripts\python.exe Python Version: 3.9.6 Python Path: ['C:\Users\inter\OneDrive\Django_Course\devsearch', 'c:\users\inter\appdata\local\programs\python\python39\python39.zip', 'c:\users\inter\appdata\local\programs\python\python39\DLLs', 'c:\users\inter\appdata\local\programs\python\python39\lib', 'c:\users\inter\appdata\local\programs\python\python39', 'C:\Users\inter\OneDrive\Django_Course\devsearch\env', 'C:\Users\inter\OneDrive\Django_Course\devsearch\env\lib\site-packages'] Server time: Sat, 11 Sep 2021 17:25:14 +0000 Traceback Switch to copy-and-paste view C:\Users\inter\OneDrive\Django_Course\devsearch\env\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▼ Local vars Variable Value exc TypeError("'bool' object is not callable") get_response <bound method BaseHandler._get_response of <django.core.handlers.wsgi.WSGIHandler object at 0x000002CD3D1F8F10>> request <WSGIRequest: GET '/login/'> C:\Users\inter\OneDrive\Django_Course\devsearch\env\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\Users\inter\OneDrive\Django_Course\devsearch\users\views.py, line 48, in loginUser if request.user.is_authenticated: … ▶ Local vars -
How does gevent ensure that the same thread-local variables are not shared between multiple coroutines
I have a Python 2 django project, which was started with gunicorn, and write a lot of threading.currentThread().xxxxxx ='some value' in the code. Because the coroutine reuses the same thread, I am curious how gevent guarantees that the currentThread variable created in coroutine A(Thread 1) will not affect coroutine B (same Thread 1). After all, the writing on the code is: import threading threading.currentThread().xxxxx ='ABCD' Instead of import gevent gevent.currentCoroutine().xxxxx ='ABCD' (simulate what it looks like) thanks for your help -
Dynamic menu from database in Django
I am looking to store my nav links from a standard navigation menu in my database. Ideally, this would allow some specific (non-technical) users the ability to maintain links on the webapp. Today, my nav menu is a 'static' page included into my base.html and is the same across all pages served up. Any changes requires me to manually update the nav static file and re-deploy. My struggle (and it could be my limited django experience) is how to be able to generate the data and render it from within the base.html/nav include without having to literally generate the menu items on every single rendering of a page (e.g. getting the menu list and sending to all rendering calls). I have dozens of pages so this isn't really an option to do manually. I've searched for this and it looks like i'm not the only one, but the closest solution is from like 2006 and I'm sure there's been some likely advancements in this area over the past 15 years. Appreciate any info that can point me in the right direction. Cheers!