Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I show real product price and also Discounted price
My html : {% for stock in stocks %} <p> size : {{stock.size}}</p> {% for dis in discount %} price : {{stock.price}} and Discount Percent : {{dis.discount_percent}}% {% endfor %} {% endfor %} I used first loop because my product can has two different size, and second loop is just because I used objects.filter(), for example price is 200$ and discount_percent is 25, How can I show discounted price that became 150$ ? -
How to manage concurrency in Django app where user can upload and dowload files?
I develop a Django app with 2 main functionalities: import data from other databases using API -> produce one csv files per model of the database export filtered data in a zip folder from csv files produced by import In "standard use", import is an automatic programmed task using celery (every day at midnight). But some users will be authorized to make import when needed, replacing the csv files of the day. Import can takes time so I may face problems of concurrency when a user is producing a new import (and replacing csv files of the day) while another user try to export the data of the day. How should be manage this concurrency? thanks for help -
I want to use Django to categorize mp3 files into a list and keep playing the mp3 files in the list
I want to classify mp3 files into a list using Django and play the mp3 files in the list continuously. (When playing only one mp3 file, use the html5 audio tag.) Get the length of the mp3 file in front and Should I give it a break for the length of time and execute the next file? Or is there another good way? -
how to make and return graphs with data frames converted to json in django template and view
i would like to know how to draw and add graph in django from pandas dataframes converted to json? after several documentation I really did not have an idea of the steps to follow for the processing of json files in order to create beautiful graphs in django views.py : def parasol_view(request): parasol = function_parasol() parasol_json = parasol.to_json(orient='records') parasol = parasol.to_html(index = False, table_id="table_parasol") context = { 'parasol': parasol, 'parasol_json':parasol_json } return render(request,'parasol.html',context) template {%block content%} <hr> {{parasol| safe}} {{parasol_json}} {%endblock content%} -
how to inset data in a django website in production from admin side
I have hosted a Django webiste on Cpanel. and successfully connected my website with the MySQL database. but I want to insert data like photos and announcements with admin panel, like we use to do with Django admin panel in development. but in production, there is no option for uploading data from the admin side. I need to know how to do this task. -
Django Authentication linking API to the app and integrating social authentication
I have a Django project where I want to create a authentication system .I am also using JWT and DRF and social auth. All the tutorials I can find only involve handling one the above .I was wandering if there is a way to combine social authentication and JWT for the API -
data is not expected in nested serializer
I m making a post request. but the data is not giving me as expected. views.py @api_view(['POST']) def ruleAssignment(request): if request.method == 'POST': data = JSONParser().parse(request) serializer=RuleAssignmentParamsSerializers(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data,status=status.HTTP_200_OK,safe=False) return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and serializers.py I have create function to split the objects and save the data in different models. class RuleAssignmentParamsSerializers(serializers.ModelSerializer): ruleAssignmentDetails = serializers.SerializerMethodField() targetDefination = serializers.SerializerMethodField() class Meta: model = RuleAssignmentParams fields = ( 'id', 'ruleAssignmentDetails', 'detailSrl', 'parameterName', 'valueType', 'overwriteValue', 'targetDefination', ) def create(self,validated_data): print(f'validated_data',validated_data) ruleAssDetails = validated_data.pop('ruleAssignmentDetails') print(f'ruleAssDetails',ruleAssDetails) def get_ruleAssignmentDetails(self,obj): rule = RuleAssignmentDetails.objects.get(id=obj.ruleAssignmentDetails_id) serial = RuleAssignmentDetailsSerializers(rule) return serial.data def get_targetDefination(self,obj): rule = TargetDefination.objects.get(id=obj.targetDefination_id) serial = TargetDefinationSerializers(rule) return serial.data and the object I m sending: { "ruleAssignmentDetails": { "id": 1, "ruleAssignment": { "id": 1, "empId": 1, "roleId": 1, "empName": "Emp01", "roleName": "CEO" }, "detailSrl": 12, "rule": 4, "validityType": "F", "startDate": "2021-06-14", "endDate": null, "frequency": { "id": 1, "frequencyName": "Test", "frequencyTpe": "Weekly" } }, "detailSrl": 12, "parameterName": "Param1", "valueType": "D", "overwriteValue": null, "targetDefination": { "id": 1, "targetName": "MIN SALES", "displayName": "MIN SALES" } } and when I print(validated_data) in serializer it's giving me: {'detailSrl': 12, 'parameterName': 'Param1', 'valueType': 'D', 'overwriteValue': None} not the whole object. how do I get all the data in serializer -
django How to randomly merge two different querysets (but with some fields in common)
I am using Django 3.2 I have two models that look a bit like this: class A(models.Model): title = models.CharField(max_length=255) caption = models.CharField(max_length=64) image = models.ImageField() # ... other fields unique to this model only class B(models.Model): title = models.CharField(max_length=255) caption = models.CharField(max_length=64) image = models.ImageField() # ... other fields unique to this model only I want to be able to write a function like this: def get_modelA_records_with_randomly_inserted_modelB(criteria_for_A, criteria_for_B, page_num): qs_A = get_records_for_modelA(criteria_for_A, page_num) qs_B = get_records_for_modelB(criteria_for_B, page_num) # Randomly insert records of B into list of records of A new_qs = qs_A | qs_B # how? A trivial way to do this would be to laboriously iterate through qs_A, inserting qs_B elements based on a random boolean flag - but I'm wondering is there a more pythonic or "djangoistic" way to do this? -
Dynamically Change Ordering of `fields` of Django Serializer using DynamicFieldsModelSerializer
I have been using DynamicFieldsModelSerializer like so: class DynamicFieldsModelSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) if fields is None: request = self.context.get('request') if request is None: return fields = request.query_params.get('fields') if fields is None: return fields = fields.split(',') # Drop any fields that are not specified in the 'fields' argument allowed = set(fields) existing = set(self.fields.keys()) for field_name in existing - allowed: self.fields.pop(field_name) And the Serializer in question inherits the above class. Like so: class OrderReportSerializer(DynamicFieldsModelSerializer): card = CardSerializer(fields=('id', 'name')) board = BoardIDSerializer(source='card.board') customer = CustomerIdNameSerializer(source='card.customer') supplier = SupplierIdNameSerializer(source='card.supplier') quantity = serializers.CharField(source='card.quantity') . . . class Meta: model = Order fields = ( # fields whose source is Card 'local_ordered_date', 'card', 'country', 'customer', 'supplier', . . . ) And the view that uses aforementioned Serializer is following: class SomeView(): def table_view(self, queryset, **kwargs): user = kwargs["user"] """ Override if different logic is required to display report data in table view. """ report_model = Report.objects.get(user=user, report_type=self.__str__()) fields = report_model.table_fields queryset = queryset.select_related( 'card__board', 'card__customer', 'card__supplier', ... ... ) if 'balance' in fields or 'invoice_total' in fields: ... ... return OrderReportSerializer( queryset, … -
Django Rest Framework Dynamic Filter against the url
views.py class ProductFilterView(APIView): permission_classes = [AllowAny] serializer_class = SpecificationListSerializer filter_fields = ('title', 'price') def get(self, request, *args, **kwargs): qs = list_products() filter_params = {} for filter in self.filter_fields: query_params = self.request.query_params.get(filter) if query_params: if ',' in query_params: filter_params[filter] = query_params.split(',') else: filter_params[filter] = query_params serializer = self.serializer_class(qs.filter(**filter_params), many=True) return Response(data=serializer.data, status=status.HTTP_200_OK) i have filter_fields = ('title', 'price'), and i want to make it dynamic. i want to get all fields from serializer serializers.py class SpecificationListSerializer(serializers.ModelSerializer): """Serializer For SpecificationCategory""" category = CategorySerializer(many=True) #product = ProductSerializer(many=True) title = serializers.CharField() class Meta: model = Specifications fields = '__all__' def get_category(self, obj): fieldebi = obj.fields.all() return fieldebi there is something wrong, i want to give all fields taken in serializer and to be shown in views.py as filter_fields. is there any way to do it? -
How to add comment to APIView class method assigned as reference inside the class?
Here is how the method has been written in the class: class ChangePasswordView(views.APIView): def put(self, request): '''Description is here''' ... post = put I want to add a custom comment to the post method. How can I do that? -
Django Rest Framework API Testing with Token authentication and IsAdmin permission Returning 401, AssertionError
good people, I am writing test cases for my django rest framework API for the first time. I have used token authentication and is admin permission. I have written some api endpoint tests. The tests run fine without authentication. I have also done this in POSTMAN and with providing token authorization at headers it runs fine there. But whenever I am running the unit test cases with token authentication and is admin permission it is returning me 401, assertion error. I am stuck with this for the last two days. Can anyone please help me to figure out where I am doing wrong? I am providing my code below: My Model: class Vendor(models.Model): user = models.ForeignKey(MyUser, on_delete=models.CASCADE, related_name='myuser') vendor_name = models.CharField(max_length=100) vendor_type = models.CharField(max_length=100, choices=Vendor_Type) display_name = models.CharField(max_length=100) vendor_mail = models.CharField(max_length=255) vendor_phone = models.CharField(max_length=15) vendor_address = models.CharField(max_length=255) def __str__(self): return self.display_name My serializer: class VendorSerializer(serializers.ModelSerializer): address_details = VendorAddressDetailSerializer(read_only=True, source='detaisaddress') sales_person = VendorContactSerializer(read_only=True, source='contactperson') social_account = VendorSocialSerializer(read_only=True, source='vendorsocial') class Meta: model = Vendor fields = ['id','vendor_name', 'vendor_type', 'display_name', 'vendor_mail', 'vendor_phone','vendor_address', 'user', 'address_details', 'sales_person', 'social_account'] My view: class VendorViewSet(viewsets.ModelViewSet): queryset = Vendor.objects.all() serializer_class = VendorSerializer authentication_classes = [TokenAuthentication] permission_classes = [IsAdminUser] URL Patterns: router = DefaultRouter() router.register('vendors', VendorViewSet, basename='vendors') urlpatterns = [ … -
Create SPA applications with Django and Vanilla.js
How can I make SPA applications in Django and vanilla.js. Is there a way to only send a template as string, and render it on the front-end using javascript? Any help is highly appreciated. Thank you -
How to generate a pdf in angular and save it in django server's filesystem
I'm working on a feature that requires to send pdf as attachements to email. I use Django's MailMultiAlternative class to send the mails. I generate my PDF file in my front-end side, using Angular. I know i can use Django's templates to generate a pdf, but i already have my Angular component finished and interpolated, plus i'm using scss in Angular, and i don't want to make the styles of the document in django templates, if possible. Is there any way to automatically generate, upload on the server, and send the PDF without requiring the user to download it. What i would like -
How can I change price on changing selecting different from dropdown? (Django)
Html <select class="tranactionID" style="width: 250px;"> {% for val in productID.list %} <option price={{val.Price}} class="price_value" >{{val.AUID}} - {{val.Description}} - {{val.Price}}</option> {% endfor %} </select> <div class="pricing"> <p class="price"><span class="mr-2 price-dc">Rs. </span><span class="price-sale" id='id_price'>Rs. </span></p> </div> Script <script> $(document).on("change", '.price_value', function (event) { event.preventDefault(); console.log($('#id_price').val($(this).children(":selected").attr("price"))); }); </script> Problem In the dropdown I have different values from the server and {{val.price}} represents the price of each item. Now what I want is that if I change the option value from the dropdown the price should be updated in the " for price" respectively. -
Send newline char in urllib.quote in Django
I'm trying to send two sentences (newline between them) using urllib.quote to Django template but unable to get the newline on template. I've tried .encode("utf-8") and %0A but none of them working. Here's my code: # s = "Some string over here. %0A Some string there." s = "Some string over here. \n Some string there." WEBROOT = "{}://{}/mytemplate/?message={}".format( protocol, Site.objects.get_current(), urllib.quote( s.encode('utf8') ), ) return HttpResponseRedirect(WEBROOT) In Template: <div class="subtitle"> {% if message %} <span>{{ message }}</span> {% else %} .... {% endif %} </div> What I want: Some string over here. Some string there. What I'm getting: Some string over here. \n Some string there. or, Some string over here. %0A Some string there. -
DRF: request.user returns nothing for token based authentication
I am basically new to DRF & trying to make one API endpoint to update user via mobile app,here is my code for that, class MobileAppUserUpdateView(APIView): def post(self, request, format=None): user = request.user print('USER',user) #<- prints nothing print('TOKEN',request.auth) #<- prints the token return ResponseBuilder.success([constants.RECORD_UPDATED]) there I want to access the user who has made that request using the auth token but getting nothing there.Here is my settings for DRF, NON_FIELD_ERRORS_KEY = 'message' REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', # 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_AUTHENTICATION_CLASSES': ( # 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'NON_FIELD_ERRORS_KEY': NON_FIELD_ERRORS_KEY, } I have also added the "rest_framework.authtoken" in the INSTALLED_APPS list as per the documentation.Any help would be appreciated... -
'>' not supported between instances of 'QuerySet' and 'int' in Django
this is my code: now = datetime.datetime.now() before_requests = MyModel.objects.filter(expired_at__lte=now) and i have this error: DateTimeField MyModel.expired_at received a naive datetime (2021-06-22 11:34:44.810749) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" '>' not supported between instances of 'QuerySet' and 'int' can every one help me? -
Assign/Mapping Multiple Country to user Django
I have a list of Countries as Master Model. Now I want to map/assign one or more Countries to a user in Profile. Model.py from django.db import models from django.conf import settings from Roads.models import CountryMaster class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) country = models.ForeignKey(CountryMaster, on_delete=models.DO_NOTHING, null=True) views.py @login_required def edit(request): if request.method == 'POST': user_form = UserEditForm(instance=request.user, data=request.POST) profile_form = ProfileEditForm(instance=request.user.profile, data=request.POST, files=request.FILES) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() else: user_form = UserEditForm(instance=request.user) profile_form = ProfileEditForm(instance=request.user.profile) return render(request, 'account/edit.html', { 'user_form': user_form, 'profile_form': profile_form }) Forms.py class ProfileEditForm(forms.ModelForm): class Meta: model = Profile fields = ('country', ) widgets = {'country': forms.SelectMultiple} I was able to do till here. I want to assign multiple Countries to a User Profile. -
Django DateTimeField showing different time in shell and browser
I just made a Coupon model in Django and displaying the valid_from and valid_till in the template. The value show in django shell ORM is the actual time created, and count 20days from it till it expires. However the one in template keep showing the CURRENT time and counts 20days from the CURRENT time. It's my first time trying something outside of tutorial and I don't know how to pinpoint a "fix", especially when django orm shell is showing the right time as I intended. models.py from django.db import models from django.contrib.auth.models import User from PIL import Image from django.utils import timezone from datetime import timedelta import uuid class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) img= Image.open(self.image.path) if img.height> 300 or img.width> 300: output_size= (300, 300) img.thumbnail(output_size) img.save(self.image.path) def twentydays_coupon(): return timezone.now()+ timedelta(days=20) class Coupon(models.Model): user= models.OneToOneField(User, on_delete= models.CASCADE) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) valid_from= models.DateTimeField(default=timezone.now) valid_till= models.DateTimeField(default=twentydays_coupon) def __str__(self): return f'{self.user.username} Coupon' views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm from .models import Coupon def register(request): if request.method … -
django 2d payment getway using django-paypal in uk
I'm using django-paypal to implement my payments in uk, i know the basic usage of the package but, i'm wondering if it has 2d support for UK? (new to payments sorry if missed up things..) -
How can I add pictures in Openstreetmap folium marker popup using django database?
I am using openstreetmap for showing data. I need to add image in marker popup and image will come from django database. SO how can I do that? #this is my code for i in qs: folium.Marker([i.latitude, i.longtitude], tooltip='click here for more', popup= "", icon=folium.Icon(color='green', icon='user')).add_to(map1) and it gives me this error. TypeError at /location/map/ can only concatenate str (not "ImageFieldFile") to str -
How to get the updated value in django UpdateView after updating the profile information?
I am successfully able to update the user info, but I am not able to redirect the user to the new url The url for profile is below: from django.urls import path, include from users import views as user_views from .views import SignUpView, ProfileUpdateView urlpatterns = [ path('profile/<str:username>', user_views.profile, name='profile'), path('profile/<str:username>/update', ProfileUpdateView.as_view(), name='profile-update'), path('register/', SignUpView.as_view(), name='register'), path('captcha/', include('captcha.urls')), ] So when I update my username from xyz to abc, it redirects me to profile/xyz and not profile/abc my views.py: class ProfileUpdateView(UpdateView): model = User template_name = "users/profile_update.html" success_message = "Your profile was updated successfully" slug_url_kwarg = 'username' slug_field = 'username' context_object_name = 'profile' fields = ['username', 'email'] second_form_class = ProfileUpdateForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["form2"] = ProfileUpdateForm(self.request.POST, self.request.FILES, instance = self.request.user.profile) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form2 = self.second_form_class(request.POST, request.FILES,instance=self.request.user.profile) if form2.is_valid(): profile = form2.save(commit=False) profile.user = request.user profile.save() form = self.get_form() return self.form_valid(form) else: return self.form_invalid(form) def get_success_url(self): self.object = self.get_object() form = self.get_form() username=form.cleaned_data['username'] user = User.objects.get(username=self.request.username) print(user) return reverse_lazy("profile", kwargs={'username': self.user}) -
Django multiple of the same dependent dropdownboxs in one form
I have a problem with the following; I have a dependent dropdown menu in a Django model form. Now I want to use it several times in the same form but I can't get it to work if I load more than one then I can only enter/use one. And I have a 2nd problem if this works how do I get the different values in a list/array so that I can store them in the db? The ultimate goal is to select how many beams are desired and on that basis to be able to enter the desired hours, ion species, energy and flux per beam. My code is as follows: models.py from django.db import models from smart_selects.db_fields import ChainedForeignKey class IonSpecies(models.Model): # ionspecie = models.CharField(max_length=10) Name = models.CharField(max_length=10) def __str__(self): # return self.ionspecie return self.Name class Energys(models.Model): Ion_Species = models.ForeignKey(IonSpecies, on_delete=models.CASCADE) Name = models.CharField(max_length=50) def __str__(self): # return self.energy return self.Name # Create your models here. class CreateBeamRequestModel(models.Model): #status choices SELECT = 'Select' REQUEST = 'Request' TENTATIVE = 'Tentavive' ACCEPTED = 'Accepted' CONFIRMED = 'Confirmed' CANCELLED = 'Cancelled' COMPLETED = 'Completed' QUEUED = 'Queued' STATUS_CHOICES = [ (SELECT, ('Select an option')), (REQUEST, ('Request')), (TENTATIVE, ('Tentative')), (ACCEPTED, ('Accepted')), (CONFIRMED, … -
In Django admin, how can I hide another related model field when adding it to the "Tədris" model?
I tried to do it with signals but I couldn't. Models and their images on the admin panel. Please help me https://i.stack.imgur.com/A3zS0.png https://i.stack.imgur.com/edtrK.png https://i.stack.imgur.com/yNio1.png https://i.stack.imgur.com/plhUW.png