Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access denied to css file that is public on S3 AWS bucket
So I have a Django application running on a docker container, on AWS EC2. The static content is hosted on an S3 bucket (css, javascript, etc.). This all works fine. I did implement a PDF output for some files using weasy print. Locally, it produces the expected PDF fine. However on the server, I get a 500 error. Upon closer inspection, the following error popped in the django logs that I have added to my decorator (that is responsible for generating the PDF). The decorator decorates some handle that is called, and the produced PDF shows up in the download folder. A decorated handler: @generate_pdf_httpresponse def handler_warehouse_packingslip(request, **kwargs): id = kwargs.get("pk") context = { .... details to provide to print.... } filename = "foo.pdf" infos = {"context":context, "template_path":'projectlibs/pdf_outputs/pdf_base.html', "extra_css_files":[], "filename":filename,"request":request} return infos The decorator: def generate_pdf_httpresponse(func): @functools.wraps(func) def wrapper_generate_pdf_httpresponse(*args, **kwargs): try: logger.info(f"Wrapper for pdf response") value = func(*args, **kwargs) html_string = render_to_string(value.get("template_path"), context=value["context"]) html = HTML(string=html_string, base_url=value["request"].build_absolute_uri()) css_files = [] pdf = html.write_pdf(stylesheets=css_files) logger.info(f"Creating tmp file for pdf response") with tempfile.NamedTemporaryFile() as file: file.write(pdf) file.seek(0) stream = file.read() httpresponse = HttpResponse(content_type='application/pdf;', content=stream) httpresponse['Content-Disposition'] = f'attachment; filename={value["filename"]}' httpresponse['Content-Transfer-Encoding'] = 'binary' return httpresponse except Exception as ex: logger.error(f"PDF wrapper failed: {ex}") return … -
Django: Filtering the fields of the m2m model from the models associated with the m2m model will take time
There are quite a few lines of code and logs that may be complicated and difficult to understand. I apologize for that. The following is OR full-text search for Video.title and Tag.name using pgroonga, an extension for full-text search. But the query takes about 2000-4000 ms to execute. The number of hits is about 130,000, but we have a LIMIT 20 limit. The index for full-text search is being used successfully. Video: 300K rows Tag: 5K rows video_tag_through: 1.3M rows # models.py class Tag(models.Model): name = models.CharField(unique=True, max_length=30) created_at = models.DateTimeField(default=timezone.now) ... class Video(models.Model): title = models.CharField(max_length=300) tags = models.ManyToManyField(Tag, blank=True) updated_at = models.DateTimeField(auto_now=True) ... class History(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) video = models.ForeignKey(Video, on_delete=models.CASCADE) ... class Favorite(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE video = models.ForeignKey(Video, on_delete=models.CASCADE) ... class Playlist(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) is_wl = models.BooleanField(default=False, editable=False) ... class Track(models.Model): playlist = models.ForeignKey(Playlist, on_delete=models.CASCADE, null=True) video = models.ForeignKey(Video, on_delete=models.CASCADE) ... # migration file ... operations = [ migrations.RunSQL( "CREATE EXTENSION pgroonga", "DROP EXTENSION pgroonga", ), migrations.RunSQL( "CREATE INDEX pgroonga_video_index ON videos_video USING pgroonga (title pgroonga_varchar_full_text_search_ops_v2)", "DROP INDEX pgroonga_video_index", ), migrations.RunSQL( "CREATE INDEX pgroonga_tag_index ON videos_tag USING pgroonga (name pgroonga_varchar_full_text_search_ops_v2)", "DROP INDEX pgroonga_tag_index", ), ] # lookups.py class Groonga(Lookup): lookup_name = … -
Create list of Approvers Django
I am trying to create an application where you can create project-based expenses, and each project should have a list of approvers who will approve the expense once uploaded to the project, how do I replicate this in Django. What I tried to do. I got the approvers into the form as a ModelMultipleChoiceField self.fields['approvers'] = forms.ModelMultipleChoiceField(queryset=Profile.objects.all()) and saved it as a list into the database def getApprovers(approvers): id = [] for profile in approvers: id.append(profile.id) return id in project create function project.approvers = getApprovers(form.cleaned_data['approvers']) I created a templatetag to display the list of approvers as the Profile Queryset objects. I tried to iterate over the saved list of approvers, but I keep getting errors def approvers_list(approvers): for profile in list(approvers): return profile How better can I represent this. here is the project and expense models class Project(MiscClass): owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True) organisation = models.ForeignKey(Organisation, on_delete=models.SET_NULL, null=True, blank=True) title = models.CharField(max_length=200, null=True, blank=True, unique=True) slug = models.SlugField(max_length=500, null=True, blank=True, unique=True) category = models.ForeignKey('Category', on_delete=models.CASCADE, null=True, blank=True) description = models.TextField(null=True, blank=True) approvers = models.CharField(max_length=100, null=True, blank=True, validators=[int_list_validator]) class Meta: ordering = ['-created'] def __str__(self): return str(self.title) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Project, self).save(*args, **kwargs) class Expense(MiscClass): PROCESSING … -
ModuleNotFoundError: No module named 'PIL' , after installing in new PC
I have cloned a Git repo which have Pillow==5.2.0,but even after installing it results in above error during execution. Currently the models.py have, from PIL import Image Tried, import Image from Pillow import Image import Image // after installing Image library but no success, However the same Git repo works perfectly on Win 7 machine but after cloning and installing in new Win 10 , the error happens Project link https://github.com/Anoop-George/farmproject.git -
Name is not defined (Django queryset.filter) [closed]
What i want to do is i want to only show article comments that belongs to article that author has a public profile attribute. Here is the problem ,i get "name is not defined" on filters which points to here: Filters #this works totally fine class FollowedUserServiceCommentFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): return queryset.filter( userservice__author__followers__author=request.user ) #this is the one with issue class PublicUserServiceCommentFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): return queryset.filter( userservice__author__public_profile = true ) But the interesting thing is that i have another filter which works pretty fine (as i pointed above). Views.py class PublicUserServiceCommentViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = UserServiceComment.objects.all() serializer_class = UserServiceCommentSerializer filter_backends = [PublicUserServiceCommentFilterBackend] Models class UserServiceComment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='userservicecomments_set') userservice = models.ForeignKey(UserService, on_delete=models.CASCADE, related_name='userservicecomments') content = models.CharField(max_length=100) class UserService(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE,null=True,related_name='userservices') userservice = models.CharField(unique=False,max_length=100,null=True,blank=True) class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) public_profile = models.BooleanField(default=True) I get "name not defined" but i can't point out which name it is. When i try directly from browser it is fine but it gives error when trying from Curl or Json. Syntax looks fine, I checked it multiple times. What is the issue?Did I … -
127.0.0.1:8000/admin/ won't load up
Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 4.0 Exception Type: TypeError Exception Value: 'set' object is not reversible Exception Location: C:\Users\User\PycharmProjects\pythonProject2\venv\lib\site-packages\django\urls\resolvers.py, line 494, in _populate Python Executable: C:\Users\User\PycharmProjects\pythonProject2\venv\Scripts\python.exe Python Version: 3.10.0 Python Path: ['C:\Users\User\PycharmProjects\pythonProject2\mywebsite', 'C:\Users\User\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\User\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\User\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\User\AppData\Local\Programs\Python\Python310', 'C:\Users\User\PycharmProjects\pythonProject2\venv', 'C:\Users\User\PycharmProjects\pythonProject2\venv\lib\site-packages'] Server time: Mon, 27 Dec 2021 18:46:36 +0000 -
Django Admin panel refuses Content Security Policy
I am struggling to use django-csp in my admin panel, I can see my frontend with vue3 and vite, you can see my demo site on here. When I try to log in admin I get a black screen and in the console, I see the error below: Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' fonts.googleapis.com ajax.cloudflare.com static.cloudflareinsights.com www.google-analytics.com ssl.google-analytics.com cdn.ampproject.org www.googletagservices.com pagead2.googlesyndication.com". Either the 'unsafe-inline' keyword, a hash ('sha256-Tq5HCCxkFfCSF4NPeTUcXBhJqVIuv2SvsJXpa2ACR2Y='), or a nonce ('nonce-...') is required to enable inline execution. I configured my django-csp in my settings: # default source as self CSP_DEFAULT_SRC = ("'none'",) CSP_INCLUDE_NONCE_IN = ["default-src"] CSP_STYLE_SRC = ("'self'", 'fonts.googleapis.com', "'unsafe-inline'", "'unsafe-eval'", "https") # scripts from our domain and other domains CSP_SCRIPT_SRC = ("'self'", 'fonts.googleapis.com', "ajax.cloudflare.com", "static.cloudflareinsights.com", "www.google-analytics.com", "ssl.google-analytics.com", "cdn.ampproject.org", "www.googletagservices.com", "pagead2.googlesyndication.com") # images from our domain and other domains CSP_IMG_SRC = ("'self'", "www.google-analytics.com", "raw.githubusercontent.com", "googleads.g.doubleclick.net", "mdbootstrap.com") # loading manifest, workers, frames, etc CSP_FONT_SRC = ("'self'", 'fonts.gstatic.com', 'fonts.googleapis.com') Can you help me to fix this? Thanks -
Django - how to validate data from post that is not in a django form?
I am receiving post data from my template but it's being created with js, it is not a django form. I know that if I am posting a field using a django form I can use form.is_valid() or x = form.cleaned_data['field'] but I don't know how to validate/clean my data when not using a django form. The reason that I'm using js for this form/template is to get a specific look that I couldn't do with a standard django template/form. models.py class AssessComment(models.Model): assessment = models.ForeignKey(Assessment, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) comment = models.TextField(blank=True) js snippet // this js is appended to the grade-form element in the template document.getElementById('grade-form').appendChild(table); comment = document.createElement('td'); commentName = "row-" + n + "-comment"; commentText = document.createElement("textarea"); commentText.setAttribute("name", commentName); rowName[n].appendChild(comment); comment.appendChild(commentText); The above js is putting a textarea in a table and giving it the name commentName. The template sends this as a post to my view. I iterate through several rows of n. template div class="form-group"> <form action="" method="post">{% csrf_token %} <div id="grade-form"></div> <!-- js is inserted here --> <div class="form-group"> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> </div> views.py while s < len(cs): comment = "row-" + str(s) + "-comment" form_comment = request.POST[comment] # … -
Django This backend doesn't support absolute paths after integrating aws S3 bucket
I found similar question on stackoverflow on this topic but still now my problems didn't solved. I am facing following problems after integrating aws S3 bucket: problem 1: Image resizing not working after integrating aws S3 bucket. problem 2: getting this error page after image upload NotImplementedError at /blog/edit/hello/ This backend doesn't support absolute paths. here error details of my terminal "C:\Users\Fdg\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\files\storage.py", line 123, in path raise NotImplementedError("This backend doesn't support absolute paths.") NotImplementedError: This backend doesn't support absolute paths. [27/Dec/2021 23:49:44] "POST /blog/edit/hello/ HTTP/1.1" 500 118419 my settings.py AWS_ACCESS_KEY_ID = "my acess key" AWS_SECRET_ACCESS_KEY = "my secret key" AWS_STORAGE_BUCKET_NAME = "my bucket name" AWS_S3_CUSTOM_DOMAIN = 'my aws domain name' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_DEFAULT_ACL = 'public-read' AWS_S3_FILE_OVERWRITE = False AWS_QUERYSTRING_AUTH = False DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_MEDIA = '/media/' AWS_STATIC = 'static' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC) MEDIA_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_MEDIA) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' here is my models.py for upload images: class BlogHeaderImage(models.Model): image = models.ImageField(upload_to='blog/images/',validators=[validate_file_size,FileExtensionValidator( ['png','jpg'] )]) blog = models.ForeignKey(Blog,on_delete=models.CASCADE,related_name="blog_header_image") def save(self,*args,**kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: out_put_size = (300,300) img.thumbnail(out_put_size) img.save(self.image.path) def __str__(self): return str(self.blog) Though I am getting this error but image is uploading on aws … -
Django get count of total quantity in cart
I 'm trying to get the total quantity of the items I have added to cart. e.g. Item id 1 quantity 1 pc Item id 2 quantity 1 pc Item id 3 quantity 4 pcs There are 6 pcs in total in cart. In cart detail page, I could get correct count using this line {{cart.get_total_qty}} This is my cart.py page: class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, update_quantity=False): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session[settings.CART_SESSION_ID] = self.cart self.session.modified = True def remove(self, product): product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def __iter__(self): product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) for product in products: self.cart[str(product.id)]['product'] = product for item in self.cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] item['quantity'] = int(item['quantity']) yield item def __len__(self): return sum(item['quantity'] for item in self.cart.values()) def get_total_price(self): return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()) def get_total_qty(self): return sum(item['quantity'] for item in self.cart.values()) def clear(self): del self.session[settings.CART_SESSION_ID] self.session.modified = True Now I … -
Getting errors after installing Django AllAuth and migrating
Help! I'm getting errors after installing Django AllAuth and migrating! Errors: File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/opt/virtualenvs/python3/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute django.setup() File "/opt/virtualenvs/python3/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/django/apps/registry.py", line 93, in populate raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: auth``` -
Какие поля нужны для хранения счета? [closed]
Нужна модель матча по пинг понгу. Требуется модель, из которой можно будет взять следующие данные: Время | Игрок1 | Игрок2 | Выигранные сеты игрока1 | сеты игрока2 | счет по сетам например 16.01.01 | олег | данил | 3 | 0 | 11:3, 11: 6, 11: 9 пока что модель выглядит так class Game(models.Model): date = models.DateTimeField(auto_now_add=True) player1 = models.CharField() player2 = models.CharField() sets1 = models.IntegerField() sets2 = models.IntegerField() А какие поля нужны для хранения счета? Еще важно, что количество сетов может быть разным, и соответственно количество счетов по сетам тоже. -
How can I limit access to certain urls depending on the logged in user?
first of all I want to clarify that I am new to this, so if I fail in some concepts I apologize in advance. I have configured the django administration panel, with an administrator user and two other users that I need to have different permissions to access certain urls of the web environment. In the home page there are three titles with links to three different sections of the page: SECTION A, SECTION B AND SECTION C. I want to have a user that has access to all the sections of the page and the other user that has access only to two sections. How can I manage that? Another thing I would need is the following: in my configuration, by default, when you launch the web server, the first thing that opens is the django administration portal, but I need that when you log in with a user, access directly to the url that has permissions. Thanks in advance -
Understand the responsibility of each part of django architecture
Im a little confuse about Django responsibility architecture. In my project, i chose work with CBV and built-in urls. In my studies, i understood that the responsibilities are divided into: Model, View, Template where: Model takes care data and DataBase, from docs : "definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing" View takes care about request and response Template is a hight level layer app to show data correct me if not that. Most of my questions are where to put the codes, eg: In my models i use something like: class Product(models.Model): ..."""other fields""" user = models.ForeignKey(User, on_delete=models.CASCADE) product_title = models.CharField(max_length=255, default='product_title') product_title_seo = models.CharField(max_length=255, default='product_title_seo') slug = models.SlugField(max_length=250,unique=True,null=True) def __str__(self): return self.product_title def get_absolute_url(self): return reverse('product_change', kwargs={'slug': self.slug, 'pk': self.pk}) def save(self, *args, **kwargs): self.product_title_seo = slugify(self.product_goal + " " + self.product_type + " " + self.product_district) self.product_title = slugify(self.product_title) if not self.slug: self.slug = self.product_title_seo return super().save(*args, **kwargs) So as we can see i have 3 methods inside my model class, but i need some treatment for the majority of fields which would represent a considerable increase in methods. This approach is correct, a lot of … -
Is there any specific condition, When to use APIView and when to use ViewSets in Django
IN Serialezers.py file I have seen, that the user is using APIView in one and Modelviewset in few. from django.shortcuts import render from rest_framework import serializers from rest_framework.response import Response from rest_framework.utils import serializer_helpers from rest_framework.views import APIView from rest_framework.viewsets import ModelViewSet from .models import * from rest_framework import status from .serializers import * class ProductList(APIView): def get(self, request): products = Product.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) def post(self, request): serializer = ProductSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class CategoryViewSet(ModelViewSet): serialzer_class = CategorySerializer queryset = Category.objects.all() -
Rounding up a decimal not working properly in python(or django)
I was trying to round up a decimal with the code I found below, but it doesn't seem to work properly in python(django). Here is the code: import math def round_up(n, decimals=0): multiplier = 10 ** decimals return math.ceil(n * multiplier) / multiplier Here are some of the results I get when I run the function: print(round_up(20.232, 2)) print(round_up(20.0, 2)) print(round_up(20.4, 2)) 20.24 20.0 20.4 However, for some reason, I get a weird value when I input 80.4. I am getting 80.41 instead of 80.4: print(round_up(80.4, 2)) 80.41 Is there any other way I can round up decimals in python(django)? I have gotten this off the internet, so there might be some other problems other than the one I mentioned above(inputting 80.4). Basically, I just want to round up a decimal to the second decimal point like above(but of course rounding up 80.4 or 20.3 would just be 80.4 and 20.3 respectively). Thank you, and please leave any questions you have. -
How to send file from system storage django?
I want to send file from my FileSystemStorage as response of a POST request, but every time i getting my error handler triggered. Why? def get_frame(request): frame_number = request.POST['frame_number'] filename = request.POST['filename'] fss = FileSystemStorage() # creating name of file i need name = f'frame_{frame_number}_{filename.replace(".mp4", "")}.png' # execute file path img = fss.path(name) return FileResponse(open(img, 'rb')) script.js for(let i=0; i<=frames_needed; i++) { let frame_number = fps * i // making POST request for 1 frame let img = get_each_frame(frame_number, filename) img.done(function(response) { console.log(response) }) // getting this handler triggered img.fail(function(error) { console.log(error, 'error') }) } get_each_frame function function get_each_frame(frame_number, filename) { let request = $.ajax({ type: "POST", url: "get_frame", data: { 'frame_number': frame_number, 'filename': filename, 'csrfmiddlewaretoken': $('[name=csrfmiddlewaretoken]').val(), }, dataType: "json", }); return request } -
Django Models return fileds as columns for django admin
I looked a lot but I couldn't find a way to return my model to django admin with the columns not only the model name: What I wish to accomplish from my model is to have the fields represent as columns in django admin, such as it is in users: I have a model called Products: from django.db import models # Create your models here. class Product(models.Model): title = models.CharField(max_length=30, null=False, blank=False) price = models.FloatField(null=False, blank=False) description = models.CharField(max_length=250, null=False, blank=False) longDescription = models.TextField(max_length=900, null=True, blank=True) def __str__(self): return self.title It's register on admin site so I can see it as: I'm looking for a way to have my products listed as users, with the id, price, description as columns... Is it possible? Thanks in advance! -
get_extra_restriction() missing 1 required positional argument: 'related_alias' error django
I deployed my django site on heroku and when i run my url which uses django taggit in it error shows up. I am using django taggit for meta keys to find related blogs. -
how to enable/disable buttons in HTML jscript
I am trying to enable buttons on a web page using a js funtion for a django project. I am new this so please be cool :-) <input onclick="change(id)" type="button" value="Modify" id="11" class="btn btn-info"></input> <div class="btn-group" role="group" aria-label="Basic example"> <button type="button" class="btn btn-secondary" disabled="false" id="edit_11">Edit</button> <button type="button" class="btn btn-secondary" disabled="false" id="delete_11">Delete</button> </div> <br></br> <input onclick="change(id)" type="button" value="Modify" id="22" class="btn btn-info">/input> <div class="btn-group" role="group" aria-label="Basic example"> <button type="button" class="btn btn-secondary" disabled="false" id="edit_12">Edit</button> <button type="button" class="btn btn-secondary" disabled="false" id="delete_12">Delete</button> </div> <br></br> <script> function change(id) { var elem = document.getElementById(id); let newID = "edit_".concat(id) if (elem.value=="Undo") { elem.value = "Modify"; choiceEdit = document.getElementsByName(newID) choiceEdit.disabled = false } else { elem.value = "Undo"; choiceEdit = document.getElementsByName(newID) choiceEdit.disabled = true } } </script> What I would like to happen is for the name of the main button change from "Modify" to "Undo", which happens. But I'd also like for the two related Edit and Delete buttons to be enabled so as to press them. Anyone can tell me what I am doing wrong? Thanks! -
Use Django template tags with Alpine.js x-text
I'm using Alpine.js in my Django templates and so far I've been quite happy with the results. However, I would like to use Django template tags for instance floatformat on a value computed by Alpine.js. For now, I am formatting the number directly in Alpine.js and my code look like this: <div x-data="{rawNumber: 1.23456, get formattedNumber() { return Math.round(rawNumber + Number.EPSILON) * 100) / 100 } }"> My formatted number is <span x-text="formatNumber"></span> </div> What I'm looking for is a way to use Django template tags on the value computed by Alpine.js. A very naïve implementation (which of course generates error) would look like this: <div x-data="{rawNumber: 1.23456}"> My formatted number is {{ <span x-text="rawNumber"></span>|floatformat:2 }} </div> -
By using Django and allauth, how can we stop authentication of a user with same email address for two social accounts?
I am new to Django and was trying to implement the below-mentioned scenario which is as such: I have a google account as well as a facebook account with the same email address by using django-allauth. So if I am already logged in using google/facebook account and try to login from facebook/google i.e. the other social account in the same session, I should show that the user has already been logged in with this email ID. My approach is to set email and provider id in the session request and manipulate it in the pre_social_login signal in my social adapter. So far I have defined my middleware as such: middleware.py from django.contrib import messages class SimpleMiddleware(object): def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. if request.path == '/accounts/login/' and request.method == 'GET' and not request.user.is_authenticated: if 'email' not in request.session: request.session['email'] = '' request.session['provider']='' request.session['is_active']='False' response = self.get_response(request) return response my_adapter.py from allauth import account from allauth.socialaccount.adapter import DefaultSocialAccountAdapter class MySocialAccountAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin): if request.session['email']=='' and request.session['provider']=='': request.session['email']=sociallogin.account.extra_data['email'] request.request.session['provider']=sociallogin.account.provider request.session['is_active']=False response = self.get_response(request) elif request.session['email']==sociallogin.account.extra_data['email'] … -
How to check file arrived in javascript and HttpResponse object django
Hi everyone and merry christmas Actually my code is working fine, but i can't figure out how to catch a file arrives message in javascript I'm working widh django 2.1 template: ... <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> ... <input type="file" id="prd" name="prd" required> </div> ... <input id="btn_ini" type="submit" name="submit" value="Init process"> </form> ... <script type="text/javascript"> document.addEventListener('???', function(){ // I wish indicate to the user that the process is runnning and don't close the page. // at the moment the logic is working as spected but I can't achieve how to check in javascript when file arrives. }) </script> </body> </html> #views def add_destination(request): ... if request.method == 'POST': ... return handle_uploaded_file(prd) return render(request, 'add-destination.html') def handle_uploaded_file(f) ... file = # processing file ... with open(file, 'rb') as f: file_data = f.read() response = HttpResponse( file_data, content_type='application/force-dowload') response['Content-Disposition'] = 'attachment; filename="proc_{}"'.format(incoming_file_name) return response return None -
Heroku Django Virtual Environment source code modification
I managed to deploy my django app (with mongodb as database) on heroku. But I need to modify some source code in django package in the virtual environment. How can I access to virtual environment created by heroku from requirements.txt ? Or maybe how can I upload directly the virtual environment to heroku and make sure that my GIT django app is working on it? thank you -
Getting "This Field is Required" line in my output of django template
As you can see in this picture, every field is having "This field is required" line which i do not want to print there. Can someone help? Picture.jpg