Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - UpdateView changes are not saved, success_url is not used
I think I have a pretty basic UpdateView but the object is not saved when I submit the form. The success_url is never called. When I click the Update button, the form refreshes and I stay on the same page. I am able to update the object via admin, so I believe the model is working fine. I am not getting any errors. urls path('classroomdetail/<uuid:classroom_id>/', views.classroomdetail, name='classroomdetail'), path('classedit/<uuid:pk>/', views.ClassroomUpdateView.as_view(), name='classupdate'), Model class Classroom(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) classroom_name = models.CharField(max_length=20) course = models.ForeignKey(Course, on_delete=models.CASCADE) students = models.ManyToManyField(Student) class Meta: constraints = [models.UniqueConstraint( fields=['user', 'classroom_name'], name="unique-user-classroom")] def __str__(self): return self.classroom_name views class ClassroomUpdateView(UpdateView): model = Classroom fields = ['classroom_name'] template_name_suffix = '_update' success_url = reverse_lazy('gradebook:classroom') template {% extends 'base.html' %} {% load static %} {% block content %} {% load crispy_forms_tags %} <div class="container"> <div class="row"> <div class="col"> <h3>This Classroom belongs to {{ classroom.course }}</h3> </div> </div> <div class="row"> <div class="col-md-3"> <form class="form-group"> {% csrf_token %}{{ form|crispy }} <input type="submit" class="btn btn-primary mt-2 mb-2" value="Update"> </form> </div> </div> <div class="row"> <div class="col-md-3"> <a href="{% url 'gradebook:classroomdetail' object.pk %}"><div class="ps-2">Cancel</a> </div> </div> </div> {% endblock content %} -
How to handle multiple ClientId s for single social auth provider
I am trying to implement social auth for my backend that will serve mobile apps on different platforms (IOS, Android). I am using django-allauth.socialaccounts to accomplish the task. The problem is that for ex Google requires to have an OAuth client ID per each platform. That said I cannot create multiple social apps with the same provider because I am starting to get MultipleInstancesReturned error. I am thinking about attaching different Site instances to the applications, but not sure if sites framework is good for distinguishing mobile platforms. The resulting question is pretty simple - how to implement social login having more than 1 client id for provider? -
How I can access a url path from root project to use in templates
I have two apps books, users, and main app(config) which contains settings of the project. I have configured my urls.py in config as follows: urlpatterns = [ path('', TemplateView.as_view(template_name='index.html'), name='home'), path('admin/', admin.site.urls), path('books/', include('books.urls')), path('account/', include('users.urls')), ] and I want to access home path in base.html templated like this: <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="{% url 'home' %}">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'books:list' %}">My books</a> </li> </ul> but it throws this error: NoReverseMatch at / 'home' is not a registered namespace Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.1.5 Exception Type: NoReverseMatch Exception Value: 'home' is not a registered namespace Exception Location: /home/shoukrey/.local/share/virtualenvs/pdfstack-J-DuXMon/lib/python3.9/site-packages/django/urls/base.py, line 83, in reverse Python Executable: /home/shoukrey/.local/share/virtualenvs/pdfstack-J-DuXMon/bin/python Python Version: 3.9.2 Python Path: ['/mnt/sda4/My-Projects/real-world/pdfstack', '/usr/lib/python39.zip', '/usr/lib/python3.9', '/usr/lib/python3.9/lib-dynload', '/home/shoukrey/.local/share/virtualenvs/pdfstack-J-DuXMon/lib/python3.9/site-packages'] Server time: Sun, 29 Aug 2021 01:28:02 +0000 -
Django Advanced Model
I have 2 models. In 1 of them, I want to withdraw general information, and in another - advanced information. I want the models to combine the service_id field. In model AdvancedService i have 2 objects with one service_id. In the Service model, when I click on the service_id, I want view 2 objects that such an service_id. However, I do not understand how it can be done. My code: #models.py class ServiceModel(models.Model): service_id = models.CharField(max_length=150) total_cars = models.PositiveIntegerField() # bmw + audi repaired = models.PositiveIntegerField() # broken_motor + broken_body advanced = models.ForeignKey( 'AdvancedServiceModel', on_delete=models.CASCADE) class AdvancedServiceModel(models.Model): service_id = models.CharField(max_length=150) bmw = models.PositiveIntegerField() audi = models.PositiveIntegerField() broken_motor = models.PositiveIntegerField() broken_body = models.PositiveIntegerField() def __str__(self) -> str: return f'{self.service_id}' #admin.py from django.contrib import admin from .models import ServiceModel, AdvancedServiceModel from django.urls import reverse from django.utils.html import escape, mark_safe @admin.register(ServiceModel) class ServiceModelAdmin(admin.ModelAdmin): list_display = ['advanced_link', 'total_cars', 'repaired'] def advanced_link(self, obj: AdvancedServiceModel): link = reverse("admin:tasks_advancedservicemodel_changelist") return mark_safe(f'<a href="{link}">{escape(obj.advanced.__str__())}</a>') advanced_link.short_description = 'Service id' advanced_link.admin_order_field = 'service_id' # Make row sortable @admin.register(AdvancedServiceModel) class AdvancedServiceModelAdmin(admin.ModelAdmin): list_display = ['service_id', 'bmw', 'audi', 'broken_motor', 'broken_body'] -
DRF MultiPartParser returns value as list
I am trying to create an API endpoint. Here I am using MultiPart/form-data content-type to cater multiple input types. But I am stuck in MultiPartParser. my view function declaration is something like this: @api_view(['GET','POST','PUT']) @parser_classes([MultiPartParser,JSONParser]) def item_view(request): The MultiPartParser is parsing this: <QueryDict: {'code': ['3'], 'gst_rate': ['5']}> <MultiValueDict: {}> What I want: <QueryDict: {'code':3, 'gst_rate':5}> <MultiValueDict: {}> How can I do that? -
How to save uploaded file and edited file in django?
I want to user to upload file, and then I want to save that file (that part is working), then I want to calculate data in this document and export it in results.html. Problem is this, I already used return function for user to download document (with done calculations). How to additionally save edited file, and forward to user to download and see data? def my_view(request): print(f"Great! You're using Python 3.6+. If you fail here, use the right version.") message = 'Upload as many files as you want!' if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() #This part is doing calculations for uploaded file dfs = pd.read_excel(newdoc, sheet_name=None) with pd.ExcelWriter('output_' + newdoc + 'xlsx') as writer: for name, df in dfs.items(): print(name) data = df.eval('d = column1 / column2') output = data.eval('e = column1 / d') output.to_excel(writer, sheet_name=name) return redirect('results') else: message = 'The form is not valid. Fix the following error:' else: form = DocumentForm() documents = Document.objects.all() context = {'documents': documents, 'form': form, 'message': message} return render(request, 'list.html', context) -
Django save an image to database
I have a site in Django that upload a photo and than it saves in a folther. After that the program make some processing in the image and save it to database. But it is giving an error: UnboundLocalError: local variable 'listing' referenced before assignment Part of Model: class Listing(models.Model): item = models.CharField(max_length=64) description = models.CharField(max_length=255, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) category = models.CharField(max_length=1, choices=CATEGORIES, default=CATEGORIES[5][1]) time = models.DateTimeField(auto_now_add=True, blank=True) closed = models.BooleanField(default=False) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="owners") bids = models.ManyToManyField(Bid, blank=True, related_name="bids") comments = models.ManyToManyField(Comment, blank=True, related_name="comments") image = models.ImageField(null=True, blank=True) restoredimage = models.BinaryField(blank=True) View: listing.restoredimage = None listing.restoredimage = cv2.imread(img_save_path) Sorry I new to Django I don´t know if I'm doing right. -
How to call a django function on click that doesn't involve changing page
I would like to have a simple task: When I click a button in the Template a function in the Views is called. I know I should make a url but I don't want the page to reload when the button is clicked I read something about AJAX/jQuery & I wonder if there is any alternatives that is limited to django and python? Thanks in advance, -
Im thinking of making a webapp with django, that's basically a wallpaper generator, but where to store and how to display an image on heroku?
Basically ill be using pillow to create random wallpapers, but ive never worked with images in django, so idk how am i supposed to display the generated image....because whilst hosting on heroku? i know that people store images on AWS and stuff, but how im supposed to do store an image generated from pillow to aws, automatically, or can u even do that? ps; im not demanding for any code, i just need to get an idea, a kind of a road map or maybe a tutorial if u may. -
How can I allow users to create their own posts in Django?
I am trying to build a discussion forum with Django. I first did a test post with Django admin, but now wanted to implement a form so that any user can post. The idea is that the home page of the forum has a list of all existing posts, and clicking on the "Create a Post" button would take them to the post form, and after submitting they can see their post on the list. I have the code for the form ready and thought I had hooked it up correctly to the URL, but I am getting a blank page when I click on "Create a Post". I am new to Django, and need some help solving this. Here are my files: Models.py: class Category(models.Model): name = models.CharField(max_length=20) class Post(models.Model): title = models.CharField(max_length=255) author = models.CharField(max_length=60, default= 'None') body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) categories = models.ManyToManyField('Category', related_name='posts') class Comment(models.Model): author = models.CharField(max_length=60) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) post = models.ForeignKey('Post', on_delete=models.CASCADE) Forms.py: class CommentForm(forms.Form): author = forms.CharField( max_length=60, widget=forms.TextInput(attrs={ "class": "form-control", "placeholder": "Your Name" }) ) body = forms.CharField(widget=forms.Textarea( attrs={ "class": "form-control", "placeholder": "Leave a comment!" }) ) class PostForm(forms.Form): title = forms.CharField( max_length=255, … -
Logging of hard errors (eg. 500) not working
I've got the following in my settings, yet, 500 errors aren't being written to my djangoerrors file. I've confirmed that the file exists in this directory (I created it myself and the permissions are set to 777). LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': '/opt/python/log/djangoerrors.log' }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': True, }, }, } Any thoughts on why errors are not being written to this file? thanks! -
Django - forloop in model.py to assign foreignkey
I have two models - User and Rank. During def save() I want the Users Rank automatically assigned to a Rank depending on the points the user has and the min_points from the Rank model. Models class User(AbstractUser): points = models.IntegerField(default=0) rank = models.ForeignKey(Rank, on_delete=models.SET_NULL, null=True, blank=True) class Rank(models.Model): rank = models.CharField(max_length=200) min_points = models.IntegerField() Now I added save() function to User model to check the user points and compare to the correct Rank # ...user model def save(self, *args, **kwargs): for i in Rank.objects.all(): if self.points >= i.min_points: self.rank == Rank.objects.get(id=i.id) super().save(*args, **kwargs) Unfortunally nothing happend after saving or creating a new user. My IDE throw warning: Unresolved attribute reference 'objects' for class 'Rank' Do I miss something? I cant figure out the issue... -
How can I create a URL-Shortener using Django based on the URL id?
I am working with Django and I am just a beginner. Now I am trying to make a URL shortener with Base 62 so I have created one class in models.py and its name is URLGenerator. Here is its code: class URLGenerator: BASE = 62 UPPERCASE_OFFSET = 55 LOWERCASE_OFFSET = 61 DIGIT_OFFSET = 48 def generate_unique_key(self, integer): """ Turn an integer [integer] into a base [BASE] number in string representation """ # we won't step into the while if integer is 0 # so we just solve for that case here if integer == 0: return '0' string = "" remainder: int = 0 while integer > 0: remainder = integer % self.BASE string = self._true_chr(remainder) + string integer = int(integer / self.BASE) return string def get_id(self, key): """ Turn the base [BASE] number [key] into an integer """ int_sum = 0 reversed_key = key[::-1] for idx, char in enumerate(reversed_key): int_sum += self._true_ord(char) * int(math.pow(self.BASE, idx)) return int_sum def _true_ord(self, char): """ Turns a digit [char] in character representation from the number system with base [BASE] into an integer. """ if char.isdigit(): return ord(char) - self.DIGIT_OFFSET elif 'A' <= char <= 'Z': return ord(char) - self.UPPERCASE_OFFSET elif 'a' <= char … -
Django sends empty PDF in attachment
I am kind of newbee and I am sitting with this issue for couple months now. I need to autogenerate PDF and attach it to email sent by django. All emails are sent comes with attached PDF, but the PDF is empty, no info in the file, but I see the file with info when it generates... Here is my views.py class SendPDFView(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): pk = kwargs.get('pk') report = get_object_or_404(Report, pk=pk) template_path = 'pcreport/table_pdf.html' context = {'report': report} response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = f'filename="{report.flight}-{report.date}.pdf"' buffer = BytesIO() template = get_template(template_path) html = template.render(context) pisa_status = pisa.CreatePDF(html, dest=response) if pisa_status.err: return HttpResponse('Error creating <pre>' + html + '</pre>') pdf = buffer.getvalue() buffer.close() msg = EmailMessage("Subjest", "Body", "handlr.arn@gmail.com", ["handlr.arn@gmail.com"]) msg.attach(f'{report.flight}-{report.date}.pdf"', pdf, 'application/pdf') msg.send() return response -
error 'NoneType' object has no attribute 'is_absolute' while using mongodb
Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'is_absolute' Exception Location: C:\Users\A\IPFinder\venv\lib\site-packages\dns\resolver.py, line 1006, in _get_qnames_to_try Python Executable: C:\Users\A\IPFinder\venv\Scripts\python.exe while uploading file the submit button should save file but it is showing while running action_page.py the code is showing error 'NoneType' object has no attribute 'is_absolute' action_page.py import cgi import os import cgitb; cgitb.enable() form = cgi.FieldStorage() fileitem = form['filename'] if fileitem.filename: fn = os.path.basename(fileitem.filename) open(fn, 'wb').write(fileitem.file.read()) this is my index.html {% extends 'base.html' %} {% block title %} IP Finder {% endblock %} {% block body %} <div class="container"> <br> <br> <center> <h1 style="font-family:'Courier New'">Django NSLookup</h1> <br> <br> <form action="{% url 'index' %}" method="post"> {% csrf_token %} <div class="form-group"> <label> <input type="text" class="form-control" name="search" placeholder="Enter website"> </label> </div> <input type="submit" class="btn btn-primary" value="Search"> <p></p> <p>Click on the "Choose File" button to upload a file:</p> <form enctype = "multipart/form-data" action="action_page.py" method="get"> <input type="file" id="myFile" name="filename"> <input type="submit" value="upload"> </form> </form> </center> <br> <br> <p>IP Address is : {{ip_address}}</p> </div> {% endblock %} views.py import dns.resolver def Index(request): search = request.POST.get('search') my_resolver = dns.resolver.Resolver() ip_address = my_resolver.resolve(search, "A") for i in ip_address: context = {"ip_address": i.to_text()} # print(ip_address) return render(request, 'index.html', context) -
Save Calculated Value from View to Model in Django
I have a Django application that gives the user an option to save a calculation or not within the form. If the user says they want to save the calculation, I would like to save the calculation result in the database too along with the input details. For the user input I am already able to save it. The challenge comes when saving the calculated results which are being handled by the views.py. My code is below: for my views.py def coordinate_transform(request): if request.method == 'POST': form = CoordinateForm(request.POST) if form.is_valid(): from_epsg = request.POST.get('from_epsg') y = request.POST.get('y') x = request.POST.get('x') to_epsg = request.POST.get('to_epsg') # Transform Coordinates transformer = Transformer.from_crs(int(from_epsg), int(to_epsg)) transformed = transformer.transform(y, x) # Save to Database? save_data = request.POST.get('saved') if save_data == 'on': form.save() messages.success(request, "Coordinate Transormation data stored") context = { 'form': form, 'y': transformed[0], 'x': transformed[1], } return render(request, 'utility/coordinate_transform.html', context) else: form = CoordinateForm() context = { 'form': form, } return render(request, 'utility/coordinate_transform.html', context) In the above code, form.save() is working fine but the calculation is not being saved. I tried using the Django Querysets to save the model and its not working. Here is my model.py class CoordinateTransform(models.Model): from_epsg = models.ForeignKey(CRS, on_delete=models.CASCADE, related_name='from_epsg') x … -
How Can I change this def into class in django views?
How Can I change this def into class in django views? app/views.py: def vote(request, slug): question = get_object_or_404(Question, slug=slug) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question': question, 'error_message': "Nie wybrałeś żadnej opcji.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.slug,))) -
Django doesn't clean() the formset
I have three models: class Order(models.Model): ... class Job(models.Model): ... class Item(models.Model): // Creates a record of a job for the order order = models.ForeignKey( Order, on_delete=models.CASCADE, blank=True, ) job = models.ForeignKey( Job, on_delete=models.CASCADE, ) I am using a modified UpdateView to update the Order: def get_job_forms(order, data=None): "" Takes order instance and creates a formset for it from Items"" JobModelFormset = modelformset_factory( Item, form=ItemForm, fields='__all__', formset=BaseModelFormSet, ) qs = order.item_set.all() return JobModelFormset(data, queryset=qs) class ObjectView(UpdateView): "" CreateView if called with is_create=True, else UpdateView"" is_create = False def get_object(self, queryset=None): try: return super().get_object(queryset) except AttributeError: return None class OrderUpdateView(WriteCheckMixin, ObjectView): model = Order form_class = OrderForm def form_valid(self, form): self.object = form.save() if not self.is_create: formset = get_job_forms(self.object, self.request.POST) if formset.is_valid(): for f in formset: inst = f.save(commit=False) inst.order = self.object inst.save() else: return self.render_to_response( self.get_context_data(form=form, formset=formset)) return redirect(self.object.get_absolute_url()) def get_context_data(self, *args, formset=None, **kwargs): context = super().get_context_data(*args, **kwargs) order = self.get_object() context['formset'] = formset if formset else get_job_forms(order) return context When I call UpdateView it renders the template with one empty formset, like you would expect it. But if I call POST on the formset, formset.is_valid() returns True even if all the fields are empty. If I allow null values … -
What is the diffrence between django apps and django contenttype?
What is the diffrence between django apps and django contenttype in getting models for example from django.apps import apps model = apps.get_model(app_label=app_label,model_name=model_name) and from django.contrib.contenttypes.models import ContentType model = ContentType.objects.get(app_label=app_label, model = model).model_class() -
Django: Displaying different data on page depending on the date?
Is there a way to display different data on a page depending on the date? For example, I am building a macro tracker, and I would to show the data just for the day that the user inputted. So their meals that they added for 08-28-2021 would only display on the page for that day. Heres my Meal model. class Meal(models.Model): name = models.CharField( max_length=1, choices=TYPES, default=TYPES[0][0] ) date = models.DateField() foods = models.ManyToManyField(Food) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse('meal_details', kwargs={'meal_id': self.id}) URL path('meal/<int:meal_id>/', views.meal_details, name='meal_details') and view @login_required def meal_details(request, meal_id): meal = Meal.objects.get(id=meal_id) unadded_foods = Food.objects.exclude(id__in = meal.foods.all().values_list('id')) return render(request, 'meals/meal_details.html', {'meal': meal, 'foods': unadded_foods}) -
unable to get the username if the data is entered from the front end in django
I am creating an invoice app, I want once the data is entered the app should automatically pick the user. if I am entering the data from admin panel it works fine.. but when I enter the data using forms in front end it takes the user name as 'none' only. -
ValueError at / save_data/
Cannot assign "'Electronic'": "Product.category" must be a "Category" instance. File/models.py: from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=150, db_index=True) def __str__(self): return self.name class SubCategory(models.Model): name = models.CharField(max_length=150, db_index=True) category = models.ForeignKey(Category, related_name='souscatégories', on_delete=models.CASCADE) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=100, db_index=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) subcategory = models.ForeignKey(SubCategory, on_delete=models.CASCADE) def __str__(self): return self. and business logic code is there.... File/views.py # from django.urls import reverse_lazy # from django.views.generic import ListView, CreateView from django.shortcuts import render from .models import Product, Category, SubCategory # Create your views here. def home(request): if request.method == "POST": name = request.POST['name'] subcategory = request.POST['subcategory'] category = request.POST['category'] ins = Product(name=name, subcategory=subcategory, category=category) ins.save() data = Product.objects.all() return render(request, 'mysiteapp/index.html', {'data': data}) and templates is there.... <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Hello, world!</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="/">Product List </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" … -
Managing static files Separately For Media Uploads and Separate for React Build
I have a little problem with my current Static Files Config. Current Settings.py #... GOOGLE_APPLICATION_CREDENTIALS = BASE_DIR / 'Cloud_Storage_Secrets/model-calling-323507-96957393f399.json' STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ BASE_DIR / 'static', BASE_DIR / 'build/static' #React Frontend Files ] MEDIA_ROOT = BASE_DIR / 'static/images' STATIC_ROOT = BASE_DIR / 'staticfiles' GS_BUCKET_NAME = 'GS_BUCKET_NAME' STATICFILES_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_CREDENTIALS = service_account.Credentials.from_service_account_file( GOOGLE_APPLICATION_CREDENTIALS ) #... Now the problem is that React frontend Build is also considered as static files when Django serves these files. Locally it works fine after creating a build from the npm run build command manually. But when I push this in production with two separate engines One Node.js for React and the other is Python for Django app on Heroku, then Django tries to get Build files from GS_BUCKET as configured for Media files and static files. So frontend build files are not picked by Django. So I'm trying to make two configurations. Google Cloud Storage for just media files but Static Files should work as default bypassing Google Cloud Storage. So How to make it possible. Please suggest to me any method to make them separate. Or how to Bypass Google Cloud Storage Config for just Media Files. Thanks! If … -
Cloud Identity Aware Proxy Cors Problem | React, Django
I deployed two different services on Google App engine. I want to use IAP for security. Service A is a Django Rest backend, second service is React Client. I have Cors issue i can't resolve. In React i use react-google-login to get Authorization Berer token to make request to my backend. When i try to make request from client to backend i have cors issue like on picture below: If i copy this request as curl and put it into postman and send it, i get 200 and expected response from backend. If i disable IAP, there is no cors problem, frontend app gets 200 from backend. My django settings accept all cors origins. What am I missing guys? I guess it must be something very simple. I tried different axios/fetch options like withCredentials, refererPolicy, headers etc. Also when i run chrome without web security app works fine. In django setting i have CORS_ORIGIN_ALLOW_ALL= True, CORS_ALLOW_ALL_ORIGINS = True ALLOWED_HOSTS = ['*'] i don't think this is backend problem. -
Link existing file in django ImageField
I'm trying to initialize an image file, which is already present on my system, using the shell. But this creates a copy of that file and store it at the specified location. What I want is that the file that is present that should be used and its copy should not be created. Here are my model and shell commands. My Model: class Manupulate(models.Model): image = models.ImageField(upload_to='media',blank=True) Shell Command: from django.core.files import File from {my app name}.models import Manupulation item = Manupulation() item.image.save("<filename>", File(open("<File path>", "rb"))) # "rb" mode for python 3 This will create a file in my media directory(copy of that image which I don't want). Please someone help me with this.