Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I send Django object as parameter in Javascript?
So as mention in title, I'm trying to send my Django object to JavaScript so I can massage it in the front end. Let me show you the code (simplified). views.py def main_page(request): contents = Contents.objects.all() context = { 'contents' : contents } return render(request, 'main/home.html', context) template {% for u in all_ans_us_paginated %} <div class="row"> <div class="col"> <div class="" id="{{u.id}}" onclick="DetailModal('{{u}}')"> </div> </div> </div> {% endfor %} ... <script> function DetailModal(u) { console.log('{{u.author}}'); console.log('{{u.body}}'); } </script> My intention is to show a modal when the click event is triggered. But putting the modal part aside, I can't pass data as parameter to JavaScript. *I don't want to make any changes in the python code. Is it possible to do it only with HTML and JavaScript? **JSON.parse(u) won't work, because u is string. -
Which framework should I learn for freelancing, Django or Node.js [closed]
I have also learned python, java script, css and html I searching best backend framework (Django and Node.js) -
Upload 10000 xlxs records to mysql using django
I have around 10k xlxs files (each with 4 different sheets and same data format for all sheets). I wanted to fetch that data and add that data to MySQL tables. With my current code it is takin around 1-2 hrs. to fetch and fill data. I wanted to optimize this and reduce time to around 5-10 mins for 10k files. Pls suggest me right solution. TIA. class ImportFileView(APIView): def post(self,request): xlsx_file = request.FILES.getlist('file') # Around 10k files for file in xlsx_file: wb_obj = openpyxl.load_workbook(file) working_sheet = wb_obj['Sheet1'] create_table_one = TableOne.objects.create( id = working_sheet['B1'].value, first_name = working_sheet['B2'].value, last_name = working_sheet['B3'].value, country = working_sheet['B4'].value, region = working_sheet['B5'].value, lab = working_sheet['B6'].value, sample_date = working_sheet['B7'].value, issue_date = working_sheet['B8'].value, release_year = working_sheet['B9'].value, comments = working_sheet['B10'].value, ) create_table_one.save() for col in range(2,4): group = working_sheet[get_column_letter(col)+str(11)].value name = working_sheet[get_column_letter(col)+str(12)].value unit = working_sheet[get_column_letter(col)+str(13)].value sample_unit = working_sheet[get_column_letter(col)+str(14)].value parameter = working_sheet[get_column_letter(col)+str(15)].value type = working_sheet[get_column_letter(col)+str(16)].value default_value = working_sheet[get_column_letter(col)+str(17)].value for row in range(19,90): create_data = TableData.objects.create( id = create_table_one.id, temperature = working_sheet['A'+str(row)].value, group = group, name = name, unit = unit, sample_unit = sample_unit, parameter = parameter, type = type, default_value = default_value, actual_value = working_sheet[get_column_letter(col)+str(row)].value ) create_data.save() working_sheet = wb_obj['Sheet2'] for col in range(2,100): if working_sheet[get_column_letter(col)+str(5)].value == None or working_sheet[get_column_letter(col)+str(5)].value … -
Setting DEBUG = False, ALLOWED_HOST = ['localhost', '127.0.0.1'] causes 500 Error
I'm using Django 3.0 with the setting: DEBUG = True when I change to DEBUG = False and run manage.py runserver, I get the following error: CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False and after changing ALLOWED_HOSTS = ['localhost', '127.0.0.1'] It is throwing Server Error (500) I've tried all the solutions of stack overflow related to this problem, but not able to solve this. Please Help, how can I fix this? -
register in Django administration isn't work
i tried to add register to my django and it doesn't work it means it doesn't register in Django administration bast.html <html> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> {%block head %} <title>Base</title> {% endblock %} </head> <body> <br> <div class="container"> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/account/login">Login Page</a> <a class="navbar-brand" href="/account/register">Register</a> </div> <div id="navbar" class="navbar-collapse collapse"> {%if user.is_authenticated %} <ul class="nav navbar-nav "> <li><a href="/account">Home</a></li> <li><a href="/account/login">login</a></li> <li><a href="/account/profile">profile</a></li> <li><a href="/account/profile/edit">edit profile</a></li> <li><a href="/account/logout">logout</a></li> <li><a href="{% url "login" %}">login</a></li> </ul> {% else %} <ul class="nav navbar-nav navbar-right"> <li><a href="/account/login">login successfully!</a></li> <li><a href="/account/register">Register</a></li> </ul> {% endif %} </div><!--/.nav-collapse --> </div><!--/.container-fluid --> </nav> {% block body%} <h1>Login</h1> {% endblock %} </body> </html> another file is register.html {% extends 'base.html' %} {% block body %} <div class="container"> <h1>Welcome</h1> <p> register below! </p> <h2>REGISTER</h2> <form method="post"> {{form.as_p}} {% csrf_token %} <button type ="submit">register</button> </form> </div> {% endblock %} and also here is my login.html file that its work {% extends 'base.html' %} {% block body %} <div class="container"> <h1>Welcome</h1> <p> Login below! </p> <h2>LOGIN</h2> <form method="post"> {{form.as_p}} {% csrf_token %} <button type … -
Image for loop in Django template html
I would like to ask how to generate images in for loop in html template in Django: this code doesn't work: Plants: {% for plant in plants %} {{ plant.name }} {% endfor %} but if I replace this: {{ plant.name }}.jpg by this: carrot.jpg then the image is displayed. All the images I have saved in static/plant_photos and the name of each photo correspond with name of the plant. -
Django REST Framework - Get reverse value of boolean field in serializer
I have 2 models: class Model(models.Model): ... related = models.ForeignKey( 'RelatedModel', on_delete=models.CASCADE, related_name='related_model' ) class RelatedModel(models.Model): ... flag = models.BooleanField() I need to pass value of 'flag' attribute of RelatedModel in Model instance serializer and additionally this value must be reversed i.e. if it is 'True', I should return 'False' as boolean data type. Already implemented this with method: class ModelSerializer(serializers.ModelSerializer): ... flag = serializers.SerializerMethodField() @staticmethod def get_flag(obj): return not obj.related.flag class Meta: model = Model fields = ( ... flag ) But maybe there is opportunity to use only serializer fields like this but with reverse value? flag = serializers.BooleanField( source='related.flag', read_only=True ) -
Add two instances to same table in django
In my case, it a treasury managing app, the task is i want to transfer an amount x from this treasury to the other treasury, from bank to cashier or from paypal acc to my bank, i m adding two instances to same table but with different details. anyone can help pls. thanks in advance MODEL : class Treasury(models.Model): name = models.CharField(max_length=256) class TreasuryItem(models.Model): treasury = models.ForeignKey('Treasury', on_delete=models.CASCADE) date = models.DateField(default=timezone.now) name = models.CharField(max_length=256) debit = models.DecimalField(max_digits=20, decimal_places=2, null=True, blank=True) credit = models.DecimalField(max_digits=20, decimal_places=2, null=True, blank=True) FORM : class TreasuryItem1Form(ModelForm): class Meta: model = TreasuryItem fields = "__all__" class TreasuryItem2Form(ModelForm): class Meta: model = TreasuryItem fields = "__all__" VIEW: def TreasuryItem_Create(request, pk): treasurys = Treasury.objects.all() treasury = treasurys.get(id=pk) form1 = TreasuryItem1Form() form2 = TreasuryItem2Form() if request.method == 'POST': form1 = TreasuryItem1Form(request.POST) form2 = TreasuryItem2Form(request.POST) if form1.is_valid() and form2.is_valid(): form1.save() form2.save() return redirect('treasury_profile', pk) -
Cannot assign "(<Qualification: Qualification object (1)>,)": "QualificationApproval.qtitle" must be a "Qualification" instance
this is my model of Qualification Approval class QualificationApproval(models.Model): """Model definition for QualificationApproval.""" # TODO: Define fields here qtitle = models.ForeignKey(Qualification, on_delete=models.CASCADE) ofEqualCode = models.CharField(max_length=100) porposDate = models.DateField() anNo = models.IntegerField() status = models.CharField(max_length= 50, default="pending") sec9 = models.ForeignKey(Sec9, on_delete=models.CASCADE) class Meta: """Meta definition for QualificationApproval.""" verbose_name = 'QualificationApproval' verbose_name_plural = 'QualificationApprovals' so here is qtitle is foreign key of qualification the problem is that when I assign the qualification in QualifcationApproval so its give me and error def sec9edit(request, secId): if 'userId' not in request.session: return render(request, "front/login.html", { "message": "Login Required First" }) user = User.objects.get(pk = request.session['userId']) sec1 = Sec1.objects.get(user = user ) qualification = Qualification.objects.all() if request.method == "POST" and secId: sec9 = Sec9.objects.get(pk = secId) sec9.curriculum = request.POST['curriculum'] sec9.save() qlrn = request.POST.getlist('qualification') code = request.POST.getlist('code') pdate = request.POST.getlist('pdate') anticipated = request.POST.getlist('anticipated') j = 0 qa = QualificationApproval.objects.filter(sec9 = sec9) for q in qlrn: if q: qua = Qualification.objects.get(pk = q.split(',')[0]) print(type(qa[j].qtitle)) qa[j].qtitle = qua, qa[j].ofEqualCode = code[j], qa[j].porposDate = pdate[j], qa[j].anNo = anticipated[j], qa[j].sec9 = sec9 qa[j].save() messages.success(request, 'Section 9 udpated successfully') return HttpResponseRedirect(reverse('addCentre/sec10')) else: try: sec9 = Sec9.objects.get(sec1= sec1) qa = QualificationApproval.objects.filter(sec9 = sec9) except: return render(request, "front/sec9.html", { "qualification": qualification }) return render(request, … -
Save output of generic listview into html-file
Using django I get the correct output displayed in the browser when direct it to right URL after login and add the needed query string (GET) parameters. Now I would like - from a different view - to get the aforementioned output and save it directly into a (server side) (html) file. Do I need to construct an HttpRequest object? What settings are required there? How to I get the content out of the HttpResponse? Or is there a simpler solution? -
How to get results from celery task to react via django rest framework
I am trying to create a celery task within django rest framework and return the result to the react frontend. Here is my URLs from .views import ImageViewSet from rest_framework import routers from django.urls import path, include router = routers.DefaultRouter() router.register(r'analyze', ImageViewSet) urlpatterns = [ path('', include(router.urls)), ] Here is my serializer class ImageViewSet(viewsets.ModelViewSet): queryset = Test.objects.all() serializer_class = TestSerializer def create(self, request, *args, **kwargs): serializer = TestSerializer(data=request.data) ...some logic result = test_task.delay(file_path) return JsonResponse({"task_id": result.id, "task_status": result.status}, status=status.HTTP_201_CREATED) def list(self, request, task_id, *args, **kwargs): task = current_app.AsyncResult(task_id) response_data = {'task_status': task.status, 'task_id': task.id} if task.status == 'SUCCESS': response_data = TestSerializer(Test.objects.get(pk=task.get())) return Response(response_data.data, status=status.HTTP_201_CREATED) I can see that the def create function works because when I go to the Django admin, I find everything saved and calculated correctly. I believe the problem is in def list or the URL files On my frontend I have the following getResults= () => { let formData = new FormData() formData.append('picture', files[0]., files[0].name) axios.post("/api/analyze/", formData, { headers: { 'accept': 'application/json', 'content-type': 'multipart/form-data' } }) .then(resp => { console.log(resp.data) }) } I get {task_id: '8f09fc07-e434-4e8c-88c4-f4d60fb711dd', task_status: 'PENDING'} But I am not sure how to update this function so I get the results when celery is … -
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/