Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issues in validating Image file passed through post request in django
I want to validate 2 things in my django project: Is the Image passed is valid Image or not (having proper extension, nonempty etc.) I have a function isCovering70p which returns bool, depending on whether the object in the image is covering 70% area or not. Now I have to check this also before saving the data to the db. If the image posted by user fails any of these 2, 400 response code should be sent. This is my models.py: def user_image_dir_path(instance, filename): return f"uploads/users/{instance.email}/{filename}" class UserDetail(models.Model): email = models.EmailField(max_length=80) registration_time = models.DateTimeField(auto_now_add=True) image_path = models.ImageField(upload_to=user_image_dir_path) image_meta = models.CharField(max_length=100) @property def filename(self): return os.path.basename(self.file.name) This is my serializers.py: class UserDetailsSerializer(serializers.ModelSerializer): class Meta: model = UserDetail fields = ['full_name', 'email', 'org_id', 'image_path'] From the DRF docs, I understood that my #1 validation condition will be taken care by DRF/django. But, how and where should I take care of #2 condition? Also, I want to update my image_meta field based on isCovering70p. How and where should I put the logic for that update? -
Changing the video format in Django
What's the best way to change video format from any to mp4 in Django? models.py class Post(models.Model): video = models.FileField(validators=[FileExtensionValidator(allowed_extensions=['mp4', 'mov', 'wmv', 'avi', 'flv', 'webM', 'mkv'])]) views.py if request.method == 'POST' in request.POST: form = NewVideo(request.POST, request.FILES) if form.is_valid(): obj = form.save() else: form = NewVideo() All the answers on the forum that I found are from many years ago, either require Celera or don't work. Is there a library, an option in Python that will change eg MOV to MP4? The preferred place of use is models.py or views.py -
How to make complex query to Db in Django
I would like to get data from my SQLite DB. My models: class Group(models.Model): groupName = models.CharField(max_length=100) description = models.CharField(max_length=255) inviteKey = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) createdAt = models.DateTimeField(auto_now_add=True) updatedAt = models.DateTimeField(auto_now=True) deletedAt = models.DateTimeField(auto_now=True) class Members(models.Model): userId = models.ForeignKey(User, on_delete=models.CASCADE) groupId = models.ForeignKey(Group, on_delete=models.CASCADE) isAdmin = models.BooleanField(default=False) And also build in Users. I need to display all Groups where currentUser is member. For that i need to build query. To avoid many-to-many relationship i created "Members" table to manage Group's members. What i've tried def getGroups(request): currentUserId = request.user.id # 1. Get all groups where currentUser is member. groups = Members.objects.filter(userId_id = currentUser.id) # this always return 3 object which is wrong. # by that filter doesn't work # other steps .. return render(request, 'group/allGroups.html') My members table: -
How to implement simple notifications in drf?
Normally in django with templates I implement basic notifications like this. For example. class Article(models.Model): name = models.CharField() owner = models.ForeignKey(User) class Comment(): article = models.ForeignKey(Article) txt = models.CharField() user = models.ForeginKey() datetime = models.DateTimeField(auto_now_add=True) class ArticleNotification(): article = models.ForeignKey(Article) msg = models.CharField() is_seen = models.BooleanField(default=False) datetime = models.DateTimeField(auto_now_add=True) If someone commented on article the owner will see notifications. @transaction.atomic def post_comment(request, article_id): comment = Comment.objects.create(article_id=article_id, txt="Nice Article", user=request.user) ArticleNotification.objects.create(article_id=article_id, msg=f"User {request.user} commented on your post") Now to show the notifications I normally make a context processor: # context_processor: def notifcations(request): notifs = Notfication.objects.filter(article__owner=request.user).order_by("-datetime") return {"notifs":notifs} In this way I can normally implement basic notification system with refresh. Now in (drf + react) what will be the preferred way for this type of task. Instead of context processor should I have to make an get api to list notifications And call this api on every request from react frontend ? -
Can I build MindMaps in Python?
I am working on my web app. I want to be able to create mind maps on my website. Can I do it in Django with python or do I need to use other languages to build this function of creating Mind Maps? -
Pass JSON data to Shopify using Add to cart button
I am new to Shopify so please pardon my ignorance, if I ask a stupid question. So far I have setup an external Django website, which let's user enter their details. When the user press "Add to cart" button, I want all of these details to be passed onto Shopify and product added to Cart. I have gone through some posts, and I understand I can do "Add to cart" quite easily just by using webstore.shopify.com/cart/product_id:quantity But I have not been able to figure how to pass the attributes. I need to pass 12 different attributes. If it's possible to pass JSON file, with "Add to Cart" button what would be great. Research done so far: Shopify - Loading data from an External REST API in a Liquid template Shopify public JSON URLs https://shopify.dev/api/ajax/reference/cart#post-cart-add-js If this user completes the transaction, I want all of these details returned to my Django website. Could anyone please guide me how I can do this. Thank you in advance, Kind regards, Shashank -
how to deploy django channels app on azure?
I want to deploy django channels app on azure but I did not found any tutorial. I tried to deploy it but server is not accepting web socket connections. -
(Django aggregate) how to get average spent time and the dates of them
my model class UserRetention(models.Model): user = models.ForeignKey('users.User', on_delete=models.PROTECT,null=True, blank=True,related_name='user_retention') in_date = models.DateTimeField(auto_now_add=True) out_date = models.DateTimeField(blank=True, null=True) @property def duration(self): try: return self.out_date - self.in_date except: pass class Meta: get_latest_by = 'in_date' my goal I need to do something like this UserRetention.objects.all().aggregate(..... to get a dictionary object with avg_weekly_duration calculated by number of hours? [ { "avg_weekly_duration": "3", }, { "avg_weekly_duration": "10", }, { "avg_weekly_duration": "8", }, { "avg_weekly_duration": "15", } ] -
DRF SOCIAL OAUTH 2
The problem is to get another access token from refresh token. I can't find the url to send refresh token to get fresh access token. -
Récupérer les valeurs d'un champs foreign key dans createview
Bonjour, je découvre Django et je bloque sur le problème suivant (en simplifieé je ne mets pas tous les champs) Models.py class Produit(models.Model): nom = models.CharField(max_length=255, unique=True) type = models.CharField(max_length=255) class ProduitBordereau(models.Model): nom = models.Charfields(max_length=255) type = models.CharField(max_length=255) prix_achat = models.DecimalField(max_digits=8, decimal_places=2, default=0) forms.py class ProduitBordereauNewForm(BSModalModelForm): produit = forms.ModelChoiceField(queryset=Produit.objects.all(), widget=forms.Select(attrs={'class': 'form-select'})) class Meta: model = ProduitBordereau fields = {'prix_achat '} widgets = { 'prix_achat': forms.NumberInput(attrs={'class': 'form-control'}), } views.py #----------PRODUIT BORDEREAU---------- class ProduitBordereauCreateView(BSModalCreateView): form_class = ProduitBordereauNewForm template_name = 'produitbordereau/produitbordereau_nouveau.html' success_message = "Success: le produit a été ajouté." success_url = reverse_lazy('bordereau_list') def form_valid(self, form): form.instance.nom = self.request.produit.nom form.instance.type = self.request.produit.type return super(ProduitBordereauCreateView, self).form_valid(form) Comment puis-je lors de la validation du formulaire donner à mes champs 'nom' et 'type' de mon modèle produitbordereau les valeurs des champs 'nom' et 'type' de mon modèle produit? -
How to set retry tasks in case of failure in Django-Celery
I'm trying to run a task using celery. I need to send post requests to a remote server while the user presses the send button, So I tried using celery with Redis here with this configuration in settings file: BROKER_URL = os.environ.get("REDIS_URL") CELERY_RESULT_BACKEND = os.environ.get("REDIS_URL") CELERY_ACCEPT_CONTENT = ["application/json"] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Dubai' according to documentation for apply_async I can define retry options like the code below: __task_expiration = 60 __interval_start = 1 * 60 api_generator.apply_async(args=(*args), group=user_key, expires=__task_expiration, retry=True, retry_policy={ "max_retries": 3, "interval_start": __interval_start }) In documentation I found this definition for apply_async: apply_async(args=None, kwargs=None, task_id=None, producer=None, link=None, link_error=None, shadow=None, **options) and following the documentation, I can set this using retry and retry_policy and a sample code for how to define retry options add.apply_async((2, 2), retry=True, retry_policy={ 'max_retries': 3, 'interval_start': 0, 'interval_step': 0.2, 'interval_max': 0.2, }) I want my task to run 3 times to run in case of any failure, and the interval between each retry to 60 seconds. my task definition looks like this: @shared_task def api_generator(*args): import requests import json url = os.environ.get("API_URL_CALL") api_access_key = os.environ.get("API_ACCESS_KEY") headers = { "Authorization": api_access_key, "Content-Type": "application/json" } json_schema = generate_json(*args) response = requests.request("POST", url, headers=headers, data=json.dumps(json_schema), … -
How can I change model id from serializer?
In order to add data Django db, id should be different so I want to change id value of data model. How can I change model id from serializer ? msg = self.request.recv(1024) while msg: print([Name], msg.decode()) stream = io.BytesIO(msg) data = JSONParser().parse(stream) serializer = DataSerializer(data=data) # create new instance # serializer = DataSerializer(data, data=data) # update 'data' print(serializer) print(Data.objects.last().id + 1) serializer.id = Data.objects.last().id + 1 <<< can not input print(serializer) serializer.is_valid() serializer.errors serializer.validated_data -
How to send a POST request to the server from Fetch API? Examples don't work
I can't send a post request to the server. For some reason, the reguest.POST on the server is empty. Below are code examples JS on front let weekends = [] await fetch('{% url "get_weekends" %}', { method: 'POST', headers: new Headers({'Accept': 'application/json', 'Content-Type': 'application/json'}), params: {after: after_str, before: before_str} }).then(function (response) { return response.json(); }).then(function (data) { if (data['status'] === 'ok') { weekends = data['weekends'] } else { console.error(data) show_error('Не удалось получить список ваших выходных! Ошибка в статусе!') } }).catch(function (e) { console.error(e) show_error('Не удалось получить список ваших выходных! Не удалось выполнить запрос!') }); after_str and before_str saved str data (01.12.2021 and 31.12.2021) Python on backend def get_weekends_view(request): """ Вью возвращает список выходных пользователя в заданном промежутке времени """ form = GetAfterAndBeforeForm(request.POST) if form.is_valid(): after, before = form.cleaned_data['after'], form.cleaned_data['before'] result = [] for weekend in Weekend.objects.filter(user=request.user, date__range=(after, before)): result.append({'date': weekend.date.strftime('%d.%m.%Y'), 'status': weekend.get_status_display()}) return {'status': 'ok', 'weekends': result} else: return {'status': 'error', 'msg': 'Форма заполнена не верно! ' + str(request.POST)} forms class GetAfterAndBeforeForm(forms.Form): after = forms.DateField() before = forms.DateField() -
Connecting Python Bot to Django and frontend
I've created a simple python bot and talks some defined commands, since it's in a particular python file (.py file). Is there anyway I can link it to my Django framework? Like if I click on some button, particular python file will execute is there anyway to do so? If there are any specific library please let me know. -
Retrieving data from Django HTML form and passing it to a MySQL database
I have a database with multiple user names and phone numbers attached to each user. On the Django template that I created the user is presented with a list of names, and the user can click on a name, or multiple names, and the database is to respond with the phone number assigned to the name. However, I am using a for loop within the Django template to iterate over the names in the database to display for the user, as the count can change. It works correctly when I select one name, however, if I select multiple name, it takes the last name selected versus displaying all names. This error is due to my for loop solution which has the same "name" assigned to all inputs. Anyone have an idea on how I can approach this? My View form: def select_contact(request): alldata = identity_log.objects.values_list("first_name", flat=True) #https://docs.djangoproject.com/en/4.0/ref/models/querysets/ checkform = contact_form(request.POST or None) context = {'alldata': alldata} print(checkform) display_type = request.POST.get("contact_option", None) if display_type in alldata: print(display_type) return render(request, 'message_me/select_contact.html', context) My template: {% extends "base.html" %} {% load static %} {% block body %} <p>Please select your favorite Web language:</p> {% for x in alldata %} <form id="contact_option" role="form" action="" … -
Django retrieving env var fails on ElasticBeanstalk
I deployed my Django app using ElasticBeanstalk. When I access the top page I get 502 error. My log shows raise KeyError(key) from None KeyError: 'MY_APP_SECRET' in my settings.py. I double checked that value for MY_APP_SECRET is set on ElasticBeanstalk console. It seems Django at least sees DJANGO_SETTINGS_MODULE env var. How can I make it work? -
How to solve net::ERR_TIMED_OUT in axios post call?
Axios.post(`https://16.16.6.1:8000/api/login`, { username: "userName", password: "password" }) .then(res => { console.log("Logging in") }) .catch(err => { console.log(err) alert(err.message) }) Earlier I used to use backend which was running in my own system so used to use localhost or window.location.hostname in place of specific hostname address like "16.16.6.1". I wanted to access the Django server running on this host, it was giving me this error. -
Drf how to: simple-jwt authenticating without the USERNAME_FIELD
I have extended the TokenObtainPairSerializer, my user model has the email as the USERNAME_FIELD but this type of user does not have an email instead I want to use an auto-generated unique id to authenticate in place of the email. class MyTokenStudentSerializer(TokenObtainPairSerializer): def validate(self, attrs): user = authenticate()( student_id=attrs['student_id'], password=attrs['password']) if user is not None: if user.is_active: data = super().validate(attrs) refresh = self.get_token(self.user) refresh['student_id'] = self.user.student_id try: data["refresh"] = str(refresh) data["access"] = str(refresh.access_token) data['student_id'] = self.user.student_id data['firstname'] = self.user.firstname data['middlename'] = self.user.middlename data['lastname'] = self.user.lastname data['phone'] = self.user.phone data['last_login'] = self.user.last_login data['joined_date'] = self.user.joined_date except Exception as e: raise serializers.ValidationError( {'error': 'Something Wrong!'}) return data else: raise serializers.ValidationError( {'error': 'Account is not activated'}) else: raise serializers.ValidationError({ 'error': 'Incorrect student id and password combination!'}) even tho i don't pass an email field this takes email and password, how do i get it to take the student_id instead of the email. -
How to get previous Date can anyone please? Actually I m working on Blood donation project
#Models.py from django.db import models class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) mobile_number = models.IntegerField() cnic = models.CharField(max_length = 13) blood_group = models.CharField(max_length= 10) last_donation = models.DateTimeField(auto_now_add=True) #Views.py from django.shortcuts import render from .models import * from .forms import UserForm from datetime import datetime,timedelta from django.contrib import messages def home(request): return render(request, 'home.html') def donor(request): if request.method == "POST": userform = UserForm(request.POST) if userform.is_valid(): userform.save() else: userform = UserForm() return render(request, 'donor.html',{'userform':userform}) #forms.py from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import User from datetime import datetime,timedelta from django.shortcuts import render class UserForm(ModelForm): class Meta: model = User fields = "__all__" def clean_cnic(self): cnic = self.cleaned_data['cnic'] print("This is a cnic",cnic) if User.objects.filter(cnic = cnic).exists(): # i want to get previous date Actually I m working on Blood donation project. first time user will come he or she entered data and the date will automatically add Beacuse it is auto_now_add. Again the same user will come and entered data I will match the CNIC if user is exist if user exist then I have to get previous date and after getting previous date I have to minus previous date from current date to check it completed 90 days … -
Testing firebase push notification
I have done some setup looking at the documentation of django-fcm and wrote the following scripts. Now, I havent done the frontend part, but want to test it locally. Is there anyway we can test it from the localhost console like using curl request? My code: class PushNoti(models.Model): message = models.TextField(blank=True) notify_time = models.TimeField(blank=True) My view: #fcm firebase from firebase_admin.messaging import Message,Notification from fcm_django.models import FCMDevice message = Message( notification=Notification(title="title", body="text", image="url")) class NotificationView(viewsets.ModelViewSet): def create(self, request, *args, **kwargs): data= request.data serializer = self.serializer_class(data=data) if serializer.is_valid(): serializer.save() device = FCMDevice.objects.all() device.send_message(title="Title", body="Message",message=message,icon=None, data={"test": "test"}) FCMDevice.objects.send_message(message=message) return Response(serializer.data,status=200) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) When I call the post api the pushnoti object gets created without any error but I am not sure whether the notification is being sent to the channel or not. Also in setting file: INSTALLED_APPS = ( ... "fcm_django" ... ) FIREBASE_APP = initialize_app() FCM_DJANGO_SETTINGS = { # default: _('FCM Django') "APP_VERBOSE_NAME": "[string for AppConfig's verbose_name]", "ONE_DEVICE_PER_USER": False, "DELETE_INACTIVE_DEVICES": False, "UPDATE_ON_DUPLICATE_REG_ID": True, } Also, in the doc FCM_DJANGO_SETTINGS doenst have any server key field. Dont we need to provide a server key in the settings generated from the firebase?? -
Cannot resolve keyword 'book_hex' into field
I'm using Django. Instead of using a PrimaryKey to identify separate books, I thought of using a code to distinguish two books. I've implemented a random 10-digit code generator and I've plugged it in to the urlpatterns and functions. That all works. But now I can't access the code of a book in a ForeignKey as I could access id with the underscore in front: r = UserRents.objects.get(book_code=code) Django gives the following error: FieldError at /main/accept_rent_request/tQYMlQMIFM/ Cannot resolve keyword 'book_code' into field. Choices are: book, book_id, creation_date, id, status, user, user_id Here's the UserRents model: class UserRents(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE, blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) status = IntegerField(default=0) creation_date = models.DateTimeField(default=timezone.now) updation_date = 0 # Change to models.DateTimeField(default=timezone.now) when updated def __str__(self): return self.book.title How can I access the code property of the book to which the UserRents table is ForeignKeying to? -
Django Alluth Authentication Error in Production
I have integrated Google Login on production site. Basically Backend-Django(port-8000),Frontend-React(port-3000) inegration. I have manage successfully login with google login on http://example.com:8000/accounts/login/ But on Frontend its shows error. http://example.com:3000 ERROR is Now on my Google OauthId credentials are Authorized JavaScript origins http://example.com:8000 http://example.com:3000 Authorized redirect URIs http://example.com:8000/accounts/google/login/callback/ The error is not understanble for me as i am new to django world. Can someone guide me. -
How can i fix this error with using captcha in django?
My code[python version=3.10, django version=4.0]: def get_code(request): img = ImageCaptcha(200, 100) im = img.generate_image(chars='1234') fp = BytesIO() im.save(fp, 'png') return HttpResponse(fp.getvalue(), content_type='image/png') Error: TypeError at /get_code/ 'float' object cannot be interpreted as an integer Request Method: GET Request URL: http://localhost:8000/get_code/ Django Version: 4.0 Exception Type: TypeError Exception Value: 'float' object cannot be interpreted as an integer -
How to use multiple filters in same field in django?
I am trying to filter the same filed on different values. example of my API is- example.com/deals?store=amazon&store=flipkart&country=india I am using django-filter in the backend. Here is my code. class DealsList(generics.ListAPIView): throttle_classes = [UserRateThrottle] serializer_class = DealModelSerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter] queryset = DealsModel.objects.all() filterset_fields = ['category','store', 'price', 'highest_price', 'is_all_time_low', 'discount','rating','product__country'] search_fields = ['product_name','category','store'] pagination_class = CursorSetPagination def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) serializer = self.get_serializer(page, many=True) data = [] for item in serializer.data: lst = list(item.items()) # buy_url = Scrapper(lst[3][1]) # item['buy_url'] =buy_url.ConverttoAff() data.append(item) return self.get_paginated_response(data) When I am trying to filter the same field with multiple values it only shows the result of the first field. for example- example.com/deals?store=amazon&store=flipkart&country=india Here it filters out only the amazon stores, not flipkart. What is the best way to filter it out as per the requirements? -
Django filter column with OR statement
I found a question very similar to this one but that one did not specify how to return a specific column and I have been trying combinations for the past few hours with no luck. home_team_list2 = PreviousLossesNbav1WithDateAgg.objects.values_list('actual_over_under_result_field', flat=True).filter(Q(away_team_field="Chicago") | Q(home_team_field="Chicago")) This does not throw me any errors but it does not return anything. I am attempting to return that specific column from my models filtering on away team or home team equal to "Chicago"