Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
google cloud storage images differ for authenticated url and public url
I cant seem to understand how is it possible that for GCS the authenticated URL shows a different image then the public URL ? Im uploading the images via a python django script def upload_to_cloud(blob_name, file_obj): file_type = imghdr.what(file_obj) blob_name = str(blob_name) + '.' + file_type # concatenate string to create 'file_name.format' stats = storage.Blob(bucket=bucket, name=blob_name).exists(client) # check if logo with the same reg.nr exists if stats is True: # if exists then delete before uploading new logo storage.Blob(bucket=bucket, name=blob_name).delete() blob = bucket.blob(blob_name) blob.upload_from_file(file_obj=file_obj, content_type=f'image/{file_type}') path = blob.public_url return path class CompanyProfile(SuccessMessageMixin, UpdateView): # TODO why company logo differs from the one in ads_list? model = Company form_class = CompanyProfileCreationForm def form_valid(self, form): """ Check if user uploaded a new logo. If yes then upload the new logo to google cloud """ if 'logo' in self.request.FILES: blob_name = self.request.user.company.reg_nr # get company registration number file_obj = self.request.FILES['logo'] # store uploaded file in variable form.instance.logo_url = upload_to_cloud(blob_name, file_obj) # update company.logo_url with path to uploaded file company = Company.objects.get(pk=self.request.user.company.pk) company.save() return super().form_valid(form) else: return super().form_valid(form) Any ideas on what Im doing wrong and how its even possible? The file that I actually uploaded is the one under authenticated url. The file … -
Create custom permission dynamically for specific field name of a model in Django
I have created a model and I want to create some groups and permissions dynamically with a specific field name of the model and the group name or permission code name. For example, if I have Institute model with some fields (for example eiin, name, address, category), I want a dynamic custom permission called name_can_edit_address for the name field. Which is working fine (like-_can_edit_address) with Meta class but I can't add field name of the model as suffix of the permission(like name_can_edit_address) as code name. It is possible to do that? It's get NameError: name 'self' is not defined. # model specifications class Institute(models.Model): CATEGORY=( ('play', 'play'), ('High school', 'High school'), ('College', 'College'), ) eiin = models.CharField(max_length=50, blank=True, null= True) name = models.CharField(max_length=100) address = models.ForeignKey(Address, on_delete=SET_NULL, blank=True, null=True) category = models.CharField(max_length=100, choices=CATEGORY) # dynamic group creation ok # create group dynamically with the model objects def save(self, *args, **kwargs): super(Institude, self).save(*args, **kwargs) Group.objects.create(name=str(self.name)+"_students") Group.objects.create(name=str(self.name)+"_teachers") Group.objects.create(name=str(self.name)+"_controller") Group.objects.create(name=str(self.name)+"_employees") Group.objects.create(name=str(self.name)+"_guardians") # problem is here. It's not taking name field as suffix of code name for permissions # create permissions dynamically with institution name & permission code like (field_permissioncode) class Meta: permissions = ( (str(self.name)+'_can_edit_address', 'can edit address of institute'), (str(self.name)+'_can_add_eiin', 'can add … -
How to verify id token in django using firebase admin sdk?
From react native jwt token is generated with this. https://rnfirebase.io/reference/auth/idtokenresult const idTokenResult = await firebase.auth().currentUser.getIdTokenResult(); console.log('User JWT: ', idTokenResult.token); I sent this token through Authorization header using Bearer to the backend. This is the django backend but it is not decoding the token class FirebaseAuthentication(BaseAuthentication): def authenticate(self, request): token = request.headers.get("Authorization") decoded_token = auth.verify_id_token(token) uid = decoded_token["uid"] user, created = User.objects.get_or_create(username=uid) return user This is the error I am getting decoded_token = auth.verify_id_token(token) File "/usr/local/lib/python3.9/site-packages/firebase_admin/auth.py", line 220, in verify_id_token return client.verify_id_token(id_token, check_revoked=check_revoked) File "/usr/local/lib/python3.9/site-packages/firebase_admin/_auth_client.py", line 127, in verify_id_token verified_claims = self._token_verifier.verify_id_token(id_token) File "/usr/local/lib/python3.9/site-packages/firebase_admin/_token_gen.py", line 293, in verify_id_token return self.id_token_verifier.verify(id_token, self.request) File "/usr/local/lib/python3.9/site-packages/firebase_admin/_token_gen.py", line 331, in verify header, payload = self._decode_unverified(token) File "/usr/local/lib/python3.9/site-packages/firebase_admin/_token_gen.py", line 412, in _decode_unverified raise self._invalid_token_error(str(error), cause=error) firebase_admin._auth_utils.InvalidIdTokenError: Can't parse segment: b'\x05\xe6\xabz\xb6\xc6r#\xa2%%3#Sb"\xc2&\xb6\x96B#\xa2&cSVS#\x93FVVF3\x13cv6C\x93v&#V\x13\x83\x13\x96&&cs\x93\x03c3fc\x13#3vR"\xc2\'G\x97\x02#\xa2$\xa5uB\'\xd0' -
Django-hosts with Nginx
My nginx config is : server { listen 80; server_name hello.in; location /{ proxy_pass http://xxx.xx.xx.xxx:8000/; } } I am using django-hosts with this nginx config. In django-hosts, I have configured my urls with abc.hello.in but it is not redirecting to that view. Can anyone help me with this how will I able to configure nginx with django-hosts? -
custom function as DRF SerializerMethodField
How do you define a separate function that acts as a model seralizer on a django model instance? (not a SerializerMethodField) def function_a(model): ... return B class ExampleSeralizer(serializers.HyperlinkedModelSerializer): field_A = serializers.???('function_a') class Meta: model = models.ModelA fields = ['field_A'] -
How to make create (POST) request using api in django
I wish to create new a data when any user was make any requests like Create Export Delete or Update but now I am working on Export.. I have two urls one is having data of tables (average_data urls) and one url which is have (audit_logs url) a data of user which will be created after when any user download an pdf format of the data .. so basically I wish to show which user on which time and which action he does it will get it on the audit_logs url I am making request of post in data/views but getting error bad request at /audit_logs/create/ views.py def averagePDF(request): global fromDate global toDate global site global device global parameters global interval global data headers = { 'authorization': "Bearer X...............", } devices_url = "http://127.0.0.1:8000/stations/list" devices_params = { 'id': device } devices = requests.request("GET", devices_url, headers=headers, params=devices_params) response = HttpResponse() response['Content-Disposition'] = 'attachment; filename=Average Data.pdf' elements = [] company_name = Paragraph(devices.json()[0]['site'], header_style) elements.append(company_name) report_data = Paragraph("Date: " + fromDate + " to " + toDate + " Station: " + devices.json()[0]['station'], title_style) elements.append(report_data) styles = getSampleStyleSheet() styleN = styles['Normal'] styleN.wordWrap = 'CJK' file_data = [] header = [] header.append("Timestamp") header.append("Station") for parameter … -
ModuleNotFoundError: No module named 'qr_code' still i installed getting error like this
error like this getting again even I installed app module not found "QRcode" -
WSGIRequest' object has no attribute 'session_key
I am getting this error when i try to access the session I am not able to understand why it is not understanding what is session it is in installed apps it knows what is session def _cart_id(request): cart = request.session_key if not cart: cart = request.session.create() return cart def add_cart(request,id): prod = Product.objects.get(id = id) try: cart = Cart.objects.get(cart_id = _cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save() try: cart_item = CartItem.object.get(product = prod,cart = cart) cart_item.quantity += cart_item.quantity except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product = prod, quantity = 1, cart = cart, ) cart_item.save() return redirect('/shop/') -
Django Model Form not Saving || Instead writes to address bar
I currently have a customer details form that I need to submit to the database. However when I submit the form it does not save nor redirect as the code suggests. It instead writes all the fields into the URL bar of the page. Models.py: from django.db import models class newCustomerClass(models.Model): customerName = models.CharField("Customer Name",max_length=50 , blank=True) addressStreetNo = models.CharField(max_length=50 , blank=True) addressStreet = models.CharField(max_length=50 , blank=True) addressSuburb = models.CharField(max_length=50, blank=True ) addressCity = models.CharField(max_length=50, blank=True ) addressPO = models.CharField(max_length=50 , blank=True) contact = models.CharField(max_length=50, blank=True ) mail = models.CharField(max_length=50, blank=True ) CellNo = models.CharField(max_length=50, blank=True ) Forms.py: from django import forms from .models import newCustomerClass from django.forms import ModelForm class newCustomerForm(ModelForm): class Meta: model = newCustomerClass fields = 'customerName', 'addressStreetNo' ,'addressStreet', 'addressSuburb' ,'addressCity' , 'addressPO' , 'contact' , 'mail' , 'CellNo' Views.py: def newCustomer(request): form = newCustomerForm() if request.method == 'POST': form = newCustomerForm(request.POST) if form.is_valid(): form.save() return redirect('home') else: print(form.errors) content = {'form':form} return render(request, 'main/newCustomer.html' , content) Templates.html: {% extends "main/base.html"%} {% block content %} <br> <div class="container" style="text-align: center"> <form> {% csrf_token %} {{ form.non_field_errors }} {{ form.source.errors }} {{ form.source }} <h1 class="h1">New Customer</h1> <br> <h5>Customer Name {{ form.customerName }}</h5> <br> <h5>Street No {{ form.addressStreetNo … -
Django: admin page redirect on save but in a new tab
I am new to the django world and web development in general I am redirecting the admin-user to an HTML that displayed what was saved (preview.html). in admin.py I added an override to response_add and response_change def response_add(self, request, obj, post_url_continue=None): return redirect('preview') def response_change(self, request, obj): return redirect('preview') in views.py def preview(request): context = { "Tools": Tool.objects.all() } return render (request,'templates/preview.html',context) it workes fine but it opens the html on the same tab of the admin-user. what I want is to open the HTML in a new tab instead of the same tab it would be greatly appriciated if someone has an idea thanks -
django how to use variable in query filter
I'm trying to create a Django filter using a variable as filter input for a contains query on a jsonfield. I just cannot get it to work. Form what I'm finding the solution should be using kwargs but I'm lost how to implement this. lookupValue = "[{{\"displayName\":\"{0}\"}}]".format(user['name']) print("value is: ") print(lookupValue) recent_user_calls = CallRecord.objects.filter(participants__contains = [{"displayName":"Some Name"}]) #recent_user_calls = CallRecord.objects.filter(participants__contains = lookupValue) I create the value I want to search and put it in lookup value. In the last commented out line I try to use this value in de query. This does not work as where the previous line works perfectly. A few lines before I print the lookupvalue and it is 100% the same as the fully typed out version. I'm have been staring at this for 2 days. Can someone please point me in the right direction? -
how do i get the specific profile of user that created a post in django
i ve been stuck for days now trying to find a way to solve this, i am trying to return the specific profile of user that created a post in django but when i try it i get a VectorDetails() missing 1 required positional argument: 'pk'. Let me show my views.py and urls.py Views.py (views for showing the posts and returning specific users ) def VectorDetails(request, pk, vectors_slug): vector = get_object_or_404(Vectors, slug=vectors_slug) vectors = Vectors.objects.filter(status='published').order_by('?')[:6] creators = Profile.objects.filter(creator=True) creator = Profile.get_object_or_404(pk=pk) context = { 'vector': vector, 'vectors': vectors, 'creators':creators } return render(request, 'vector-details.html', context) views.py (view for returning the specific user) from django.shortcuts import render, get_object_or_404 from userauths.models import Profile def creator_profile_detail(request, pk): creators = get_object_or_404(Profile, pk=pk) context = { 'creators': creators } return render(request, 'creator_profile_detail.html', context) urls.py from django.urls import path from . import views app_name = 'creators' urlpatterns = [ path('<int:pk>', views.creator_profile_detail, name="creator_profile_detail"), ] template.html <div class="premium_uyhau mt-4"> <div class="urip_widget_avater"> <a href=""><img src="{{vector.creator.profile.image.url}}" class="img-fluid circle" alt=""></a> <div class="veryfied_author"><img src="assets/img/verified.svg" class="img-fluid" width="15" alt=""></div> </div> <div class="widget_avater_124"> <h4 class="avater_name_214"><a href="{% url 'creators:creator_profile_detail' creators.pk %}">{{vector.creator|title}}</a></h4> <span>{{vector.creator.profile.bio|title}}</span> </div> </div> -
Google cloud storage images differ for authenticated and public url
I ran in to a confusing problem with gcs. Im uploading a image file via python script in django and the image on the authenticated url differs from the image on the public url. I am actually uploading the file thats in the authenticated url. Any ideas how this can happen? My scripts in views.py: def upload_to_cloud(blob_name, file_obj): file_type = imghdr.what(file_obj) blob_name = str(blob_name) + '.' + file_type # concatenate string to create 'file_name.format' stats = storage.Blob(bucket=bucket, name=blob_name).exists(client) # check if logo with the same reg.nr exists if stats is True: # if exists then delete before uploading new logo storage.Blob(bucket=bucket, name=blob_name).delete() blob = bucket.blob(blob_name) blob.upload_from_file(file_obj=file_obj, content_type=f'image/{file_type}') path = blob.public_url return path class CompanyProfile(SuccessMessageMixin, UpdateView): model = Company form_class = CompanyProfileCreationForm def form_valid(self, form): """ Check if user uploaded a new logo. If yes then upload the new logo to google cloud """ if self.request.FILES['logo']: blob_name = self.request.user.company.reg_nr # get company registration number file_obj = self.request.FILES['logo'] # store uploaded file in variable form.logo_url = upload_to_cloud(blob_name, file_obj) # update company.logo_url with path to uploaded file return super().form_valid(form) else: return super().form_valid(form) -
Django localization basics
Check out the post if you would like to learn how to localize Django apps 👇 https://blog.crowdin.com/2021/11/10/django-translation/ -
Slow installation of python packages in aws lightsail
I have been trying to install some python packages in lightsail but it has been slow mainly taking more than 8 hours thus far. I have used pip install -r mypiplistreq.txt after long hours I used pip3 install -r mypiplistreq.txt it was still the same result, the pip comes up with the messageS such as `INFO: pip is looking at multiple versions of urllib3/[PACKAGE_NAME] to determine which version is compatible with other requirements. This could take a while.` `INFO: This is taking longer than usual. You might need to provide the dependency resolver with stricter constraints to reduce runtime. If you want to abort this run, you can press Ctrl + C to do so. To improve how pip performs, tell us what happened here: https://pip.pypa.io/surveys/backtracking` And it then downloads different versions of .whl or tar.gz files some of them numbering over 15 versions with different file sizes in Kb and Mb There have been many such messages mostly for packages which I did not even specify in my requirements list. This has made my installation to take hours on lightsail using bitnami for django. What can I do to improve its installation. I hope that I have made my … -
Having issues retriving data from my database to the users
I am trying display all courses from my course model to the users, but seems i am getting it wrong. here is my code; views.py def course_list(request, category_slug=None): category = None categories = Category.objects.all() courses = Courses.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) courses = courses.filter(category=category) return render(request,'courses/content/list.html', {'category': category, 'categories': categories, 'courses': courses}) def course_detail(request, id, slug): course = get_object_or_404(Courses, id=id, slug=slug, available=True) return render(request, 'courses/content/detail.html', {'course': course}) here is the code for my list.html {%block content %} <section id="about-home"> <h2>Courses</h2> </section> <!-- courses section starts --> <section id="course"> <h1>Our Amazing Courses</h1> <p>Replenish man have thing gathering lights yielding shall you</p> <div class="course-box"> {% for course in courses %} <div onclick="window.location.href='{{ course.get_absoule.url}}';" class="courses"> <img src="{% if courses.cover %}{{ courses.cover.url }} {% else %} {% static 'images/c3.jpg' %}{% endif %}" alt="{{ courses.name }}" /> <div class="details"> <span>{{courses.updated}}</span> <a href="{{ course.get_absolute_url }}"></a> <h6>{{courses.name}}</h6> <div class="star"> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="far fa-star"></i> <span>(23)</span> </div> </div> <div class="cost">${{courses.price_display}}</div> </div> {% endfor %} </section> {%endblock content%} the above codes is for my views.py and list.html -
No file chosen This field is required
The Views from .models import Posts from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.messages.views import SuccessMessageMixin from django.views.generic import CreateView class PostCreateView(LoginRequiredMixin, CreateView): model = Posts fields = ['caption', 'image'] template_name = 'home/creat_post.html' def form_valid(self,form): form.instance.user = self.request.user return super().form_valid(form) The models class Posts(models.Model): caption = models.CharField(max_length=2200) date_posted = models.DateTimeField(default=timezone.now()) image = models.ImageField( upload_to='PostsImages') user = ForeignKey(User, on_delete=models.CASCADE ,related_name='UserPosts') def __str__(self): return f"Post {self.id} ({self.user.username})'s" def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) img.save(self.image.path) So I am able to add in the admin page normally and see the posts in the home.. but when I try to create post from using this class --> every time I add image and hit post, it tells me this field is requird Image of what I see -
django application only working with port 8000
I am working on an project and I have hosted it on ec2 to see if everything is working fine or not. It's only a single page application for now with no endpoint. Problem is it only works if I use my_domain:8000 or my_ip:8000 here is the config file i have written. server { listen 8000; server_name mydomain.info; # to avoid any error while fetching fevicon location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/dev/myproject; } location / { include proxy_params; # communicate via socket file created by Gunicorn proxy_pass http://unix:/home/ubuntu/dev/myproject.sock; } } I enabled it using: sudo ln -s /etc/nginx/sites-available/config-file /etc/nginx/sites-enabled/ after doing that I restarted nginx using- sudo systemctl restart nginx then started server using- python3 manage.py runserver 0.0.0.0:8000 It's my first time doing this and I think I have done something wrong with config file or while enabling it but I can't figure it out. -
Can I learn Python by myself?
Im an absolute beginner at Python. I start watching some videos on youtube. Please, can you tell me if I can learn Python by myself? Can you help me with websites? if yes, which course should I enrol in? Thank you, Rubi -
How to encode and decode an image in JSON for celery and django
I am trying to apply some logic to the image recieved from API call. Below is the code from the Django Rest Framework. I am trying to serialize the image so I can send it to a celery task but I am not serializing and deserialzing the image correctly. serializer.validated_data is <InMemoryUploadedFile: 1.png (image/png)>)]) serializer.validated_data['picture'].file is <_io.BytesIO object at 0x7f1375e1edb0> if serializer.is_valid(): image_uploaded = serializer.validated_data['picture'].file json_data = base64.b64encode(image_uploaded.read()).decode('ascii') call = test_func.delay(json_data) results = TestSerializer(TestModel.objects.get(pk=call.get())) @shared_task() def test_func(json_data): img_temp = asarray(Image.open(json_data)) ....some logic return model_instance.id I get the following error on the call.get() OSError: [Errno 36] File name too long I am not sure how to correctly serialize and derialize the image. Can someone please show how to fix this? -
In Openedx Based Project, Xblock customization need to add CKEditor in textarea in javascript
In Openedx Based Project, Xblock customization needs to add CKEditor in textarea in javascript. i am using this xblock "edx-sga Staff Graded Assignment XBlock" need to add one textarea in as a richtext-editor like CKEditor. -
Django-postgres-extesion ArrayRemove
Hey I'm trying to add network monitoring parameter values (int) into a Django models ArrayField every minute for further processing. Django-postgres-extension sounded promising for my purposes, but now I'm struggling with couple of issues. Im adding values (int) to my array using MyMeasData.objects.filter(ipAddress=ipa).update(paramOne = ArrayPrepend(param1, 'ParamOne')) but I need to keep my array length under n samples by removing last value of the array. Q1: what is the correct syntax to remove last value of the Array. All my attempts have failed, MyMeasData.objects.filter(ipAddress=ipa).update(paramOne = ArrayRemove('paramOne', [-1])) Q2: How do I get the size of queryset paramOne, so I know when to start ArrayRemove in Q1 MyMeasData.objects.filter(ipAddress = ipa).values_list('paramOne', flat = True) gives a queryset: <QuerySet [[903, 903, 901, 903, 901, 901, 901, 899]]> I have looked into the django-postgres-extension documentation, but wasn't able figure out the correct syntax. Im using (python 3.8.8, django 3.2.7) Any help would be highly appreciated! -
Uploading image with react "File extension “” is not allowed error
I am trying to upload an image from react to django. Here is my drop function: drop = async (files) => { console.log(files[0].name) <- correctly prints out "car.png" const object_image = URL.createObjectURL(files[0]) const FILES = { "uploaded_image": [{ image: object_image, address: await fetch(object_image).then(res => res.blob()) }] } And below is how I try to send it sendTheImage= () => { let formData = new FormData() formData.append('picture', this.state.files[0].address) axios.post("api/call", formData, { headers: { 'accept': 'application/json', 'content-type': 'multipart/form-data' } }) The error is File extension “” is not allowed. Allowed extensions are ...,png,.... Which shows that react is not able to get the file extension to send it to the Django backend. Am I creating the blob correctly? how to fix this issue? -
Incorrect Authentication Data
I tryng to send email in my django projects. Here is my settings:- EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'gmail.com' # EMAIL_USE_TLS = True EMAIL_USE_SSL = True EMAIL_PORT = 465 EMAIL_HOST_USER = 'noreply.marketage@gmail.com' EMAIL_HOST_PASSWORD = '*******' I am getting this error (535, b'Incorrect authentication data') I turned on less secure app also. I also tried my cpanel Email. For that my setting was # EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # EMAIL_HOST = 'mail.marketage.io' # EMAIL_PORT = 587 # EMAIL_USE_TLS = True # # EMAIL_USE_SSL = True # EMAIL_HOST_USER = 'noreply@marketage.io' # EMAIL_HOST_PASSWORD = '*******' # DEFAULT_FROM_EMAIL = EMAIL_HOST_USER For this settings I get the same error. I dont know what causing this issue. But My email was working 4 days ago and it worked just fine. But Suddenly Its not working. I tried to debug my code for that I used Gmail SMTP in my localhost. In Localhost its working completely fine but its not working when I try to send email from live server. Is there any solution?? Thanks In Advance -
How to join on multiple column with a groupby in Django/Postgres
I have the following tables that I need to join on date and currency: Transactions Description | Date | Amount | Currency Exchange rates Currency | Date | Rate I need to join on both the date and currency columns, multiply the rate and the amount and sum that up to get the total value in the different currency. I also need to group it per calendar month. Is this possible using the Django ORM or would I need to use SQL directly? If so, how do I go about doing this in Postgres?