Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why am I getting syntax error in nested if..else statement in Django views
I believe in Python we can do the following: if expression1: statement(s) if expression2: statement(s) elif expression3: statement(s) elif expression4: statement(s) else: statement(s) else: statement(s) I am trying to do something like this in Django views: if qs1.count() > 100: # do something elif qs1.count() - qs2(count) < 12: # do something else elif qs3.count() > qs2.count(): if qs1.count() == qs3.count(): # Error here << # do whatever else: # forget it I am getting SyntaxError: invalid syntax at the code line shown. What am I doing wrong? How do I improve the statement flow so as not to encounter an error. -
Django redirection to another page not working
So I'm trying to create a webstore using Django and HTML. To make it short, my problem is that when I press the button "Products" on the navigation bar it gives me an 404 error. This is the error it gives me. It also gives me errors in the terminal The error in the terminal. I have been trying to figure out what's wrong for the past hour but nothing seems to be working. Here's my code; (The file product.html is located in a folder named "templates") My views.py file from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Item # Skriptist models.py impordib eseme (Item'i) # def product(request): context = { "items": Item.objects.all() } return render(request, "product.html", context) def checkout(request): return render(request, "checkout.html") class HomeView(ListView): model = Item template_name = "home.html" class ItemDetailView(DetailView): model = Item template_name = "product.html" My urls.py file from django.urls import path from django.conf.urls import include, url from .views import ( ItemDetailView, checkout, HomeView ) # Skriptist views.py improdib "item_list'i" # app_name = "core" urlpatterns = [ path('', HomeView.as_view(), name='home'), path('checkout/', checkout, name='checkout'), path('product/<slug>/', ItemDetailView.as_view(), name='product'), ] And finally this is my scripts.html file which has all of the javascript stuff. {% … -
How do I increase an IntegerField in Django?
I am making a Todo list web app in Django. I am just learning Django and a very much novice, so any help is greatly appreciated. My problem: My app will allow users to sign up and they can have a profile of their own. They can create ToDos and delete them as they want. Now, I want to introduce an attribute to all the users called "todos". This is basically an integer value that will keep track of how many todos they have created since they signed up. And every time the user adds a new task, I want this value to increase by 1. I just can't seem to figure out how to implement this. This is my models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default="default.jpg", upload_to="profile_pics") todos = models.IntegerField(default=0) def __str__(self): return f"{self.user.username} Profile" def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) views.py class TodoListView(ListView): model = ToDo template_name = "ToDo/home.html" context_object_name = "todos" ordering = ["-date_posted"] class TodoCreateView(CreateView): model = ToDo fields = ["title"] success_url = reverse_lazy("todo-home") def form_valid(self, form): … -
Django does not make migrations of multiple models under app_label?
class User(models.Model): ...... ...... class Meta: app_label = 'app_name' class Customer(models.Model): ...... ...... class Meta: app_label = 'app_name' Only User model is created but Customer model is not created. I am creating models out of app scope -
Django pop up modal after Inserting/updating data
I've been searching on google and SO but that doesnt work when i apply it to my code, I just want that if the user update/insert data, a pop up modal message appears I have this form in my html <form method="post" id="myform" class="myform" style="width: 100%" enctype="multipart/form-data">{% csrf_token %} <table id="blacklistgrids" border="2px"> <tr> {% for v in table.0 %} {% if forloop.first %} <th id="thupdate">{{v}}</th> {% else %} <th ><input type="text" name="updatedate" value="{{ v }}"></th> {% endif %} {% endfor %} <th hidden></th> <th data-id='headerss' id='headerave'>Average</th> </tr> <tbody> {% for row in table|slice:"1:" %} <tr class="tr2update"> <td><input type="text" value="{{row.0}}" name="students" hidden>{% for n in teacherStudents %}{{n.Students_Enrollment_Records.Student_Users}}{% endfor %}</td> <td class="tdupdate" hidden><input type="text" hidden></td> {% for teacher in students %} <input type="hidden" name="id" value="{{teacher.id}}"/> <td> <input type="text" data-form-field="{{teacher.id}}" name="oldgrad" class="oldgrad" value="{{teacher.Grade|floatformat:'2'}}"/> </td> {% endfor %} {% for avg in average %} <td data-id='row' id="ans"><input type='number' class='averages' step="any" name="average" value="{{average.average_grade|floatformat:'2'}}" readonly/></td> {% endfor %} </tr> {% endfor %} </tbody> </table> <div class="buttons"> <input type="submit" value="&nearrow;&nbsp;Update" class="save" formaction="/updategrades/"> <!--formaction="/updategrades/"--> </div> </form> <script> if (typeof jqXhr.success != 'undefined') { $('#thanksModal').modal('show'); } else { $('#myform').html(jqXhr); } </script> and this is my views.py import json def updategrades(request): /some logic/ return HttpResponse(json.dumps({"success":True}), content_type="application/json") -
Django 2.2 - django.db.utils.OperationalError: no such table
I am pulling my hair out. I just can't get migrations to work anymore. Every time I run python3 manage.py makemigrations or python3 manage.py makemigrations app_name I get the following error: Traceback (most recent call last): File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: catalog_fault The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/urls/resolvers.py", line 584, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/site-packages/django/urls/resolvers.py", line 577, in urlconf_module return import_module(self.urlconf_name) File "/home/peter/.virtualenvs/21q_env/lib/python3.6/importlib/__init__.py", line … -
Change integer field value with update_or_create method for an inlineformset
I have 2 models: class Contract(models.Model): number = models.CharField( blank=False, null=False, default="", max_length=255, ) date = models.DateField( blank=False, null=False, ) slug = models.SlugField(blank=False, null=True, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL) def save(self, *args, **kwargs): self.slug = slugify(self.number) super(Contract, self).save(*args, **kwargs) class ContractItems(models.Model): contract = models.ForeignKey(Contract, on_delete=models.CASCADE, related_name='contractitmes_set') item = models.ForeignKey( Catalog, on_delete=models.CASCADE, blank=False, ) quantity = models.PositiveIntegerField() forms.py class ContractAddForm(forms.ModelForm): class Meta: model = ContractItems exclude = () class ContractForm(forms.ModelForm): date = forms.DateField( widget=forms.TextInput( attrs={'type': 'date'} ), ) class Meta: model = Contract fields = ( 'number', 'date', ) ContractAddFormSet = inlineformset_factory( Contract, ContractItems, form = ContractAddForm, extra = 1, ) In views i pass inlineformset so that, when i create Contract i cant also create as many ContractItems as i want. views.py class ContractCreate(LoginRequiredMixin, CreateView): model = Contract fields = ['number', 'date', 'author'] class ContractAddItemsCreate(LoginRequiredMixin, CreateView): model = Contract # fields = ['number', 'date', 'author'] success_url = reverse_lazy('tabs') form_class = ContractForm def get_context_data(self, *args, **kwargs): data = super(ContractAddItemsCreate, self).get_context_data(**kwargs) if self.request.POST: data['contractitems'] = ContractAddFormSet(self.request.POST) else: data['contractitems'] = ContractAddFormSet() return data def form_valid(self, form): context = self.get_context_data() contractitems = context['contractitems'] with transaction.atomic(): form.instance.author = self.request.user self.object = form.save() if contractitems.is_valid(): contractitems.instance = self.object contractitems.save() return super(ContractAddItemsCreate, self).form_valid(form) What i … -
Django ORM Group by, Sum with row ID to get position of user on leaderboard
I want to create a leaderboard from the below table. I have managed to do a sum group by of the table based on points, but now I want to extract the row index of specific user to display only his position on the leaderboard Table =# Select * from user_activity; user_activity_id | user_activity_date | user_activity_point | user_activity_description | user_activity_document_id | user_activity_user_id ------------------+-------------------------------+---------------------+---------------------------+--------------------------------------+----------------------- 24 | 2020-02-28 08:32:22.17622+00 | 2 | Page Classification | e516c38c-5f96-4e46-af15-aa6dcbe30184 | 2 ORM leaderboard = User_Activity.objects.values('user_activity_user_id').order_by('points').annotate(points=Sum('user_activity_point')) So now this brings back a queryset which I can loop over to get the index of the specific user and use that as his position, but surely there must be a better way to get the index directly from the query -
Not displaying details in database
I am not able to get the deatils of the beneficiary in the database when I fill up the form for beneficiary and husband the details of only the husband is shown in the database and the details of the beneficiary is somewhat lost.The fields of the beneficiary are all empty. <body ng-app=""> {% extends "pmmvyapp/base.html" %} {% load crispy_forms_tags %} {% load static %} {% block content%} <div class="col-md-8"> <form method="post" action="/personal_detail/" enctype="multipart/form-data" id="regForm"> <div class="group"> <div class="tab"> {% csrf_token %} <div class="form-group"> <div class=" mb-4"> <!--Beneficiary Details--> <h6><u>(*Mandatory Fields)Please Fill up the details below </u></h6> </div> <legend class="border-bottom mb-4" ,align="center">1.Beneficiary Details</legend> <label for="formGropuNameInput">Does Beneficiary have an Adhaar Card?*</label> <input type="radio" name="showHideExample" ng-model="showHideTest" value="true">Yes <input type="radio" name="showHideExample" ng-model="showHideTest" value="false">No <!--logic for yes--> <div ng-if="showHideTest=='true'"> <div class="form-group"> <label for="formGropuNameInput">Name of Beneficiary(as in Aadhar Card)*</label> <input name="beneficiary_adhaar_name" class="form-control" id="formGroupNameInput" placeholder="Enter name of Beneficiary as in Aadhar Card" required> </div> <div class="form-group"> <label for="formGropuNameInput">Aadhaar Number(Enclose copy of Aadhaar Card)*:</label> <input name="adhaarno" class="form-control" id="aadhar" pattern="[0-9]{4}[0-9]{4}[0-9]{4}" placeholder="Enter Aadhar Card number with proper spacing" required> </div> <input type="file" name="adhaarcopy" /> <div class="form-group"> <div class="form-check"> <input class="form-check-input is-invalid" type="checkbox" value="" id="invalidCheck3" required> <label class="form-check-label" for="invalidCheck3"> Give consent to collect adhaar card data </label> <div class="invalid-feedback"> You … -
Pythonanywhere: Error running WGSI application
I'm trying to run a Django app in pythonanywhere, and I'm running into a WGSI application problem. I'll try to explain the things I've tried: When I run the server from the console on pythonanywhere with "manage.py runserver" it doesn't have any problems. The error looks like this: 11:13:54,818: Error running WSGI application 11:13:54,818: ModuleNotFoundError: No module named 'atrapamente.settings' 11:13:54,819: File "/var/www/atrapamente_eu_pythonanywhere_com_wsgi.py", line 11, in <module> 11:13:54,819: application = get_wsgi_application() 11:13:54,819: 11:13:54,819: File "/home/Atrapamente/.virtualenvs/venv/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 11:13:54,819: django.setup(set_prefix=False) 11:13:54,819: 11:13:54,820: File "/home/Atrapamente/.virtualenvs/venv/lib/python3.7/site-packages/django/__init__.py", line 19, in setup 11:13:54,820: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 11:13:54,820: 11:13:54,820: File "/home/Atrapamente/.virtualenvs/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 76, in __getattr__ 11:13:54,820: self._setup(name) 11:13:54,820: 11:13:54,820: File "/home/Atrapamente/.virtualenvs/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 63, in _setup 11:13:54,820: self._wrapped = Settings(settings_module) 11:13:54,821: 11:13:54,821: File "/home/Atrapamente/.virtualenvs/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 142, in __init__ 11:13:54,821: mod = importlib.import_module(self.SETTINGS_MODULE) 11:13:54,821: *************************************************** 11:13:54,821: If you're seeing an import error and don't know why, 11:13:54,821: we have a dedicated help page to help you debug: 11:13:54,821: https://help.pythonanywhere.com/pages/DebuggingImportError/ 11:13:54,822: *************************************************** On the console, I tried finding the WGSI file as they explain on the help page. Then I checked if I could import my settings and the path. Apparently there are no problems there. I checked it like this: (venv) Atrapamente@green-euconsole1:~/atrapamente$ python3.7 -i /var/www/atrapamente_eu_pythonanywhere_com_wsgi.py >>> import atrapamente.settings … -
502 Bad Gateway nginx with Selenium and Django
I have a web-app with DigitalOcean (gunicorn/nginx) using Selenium and Django. I'm trying to scrap data from 3 websites and save this data in a database, but I get this error if the process take more than 60 seconds 502 Bad Gateway nginx/1.14.0 (Ubuntu) How can I extend or disable response waiting time for nginx ? -
Crontab with django: ValueError not enough values to unpack
I'm implementing crontab with my django project and am getting a error which I'm unable to figure out the cause of: Traceback (most recent call last): File "/Users/stein/Documents/renbloc/api_web/ebdjango/manage.py", line 19, in execute_from_command_line(sys.argv) File "/Users/stein/Documents/renbloc/api_web/venv/lib/python3.7/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/Users/stein/Documents/renbloc/api_web/venv/lib/python3.7/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/stein/Documents/renbloc/api_web/venv/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/Users/stein/Documents/renbloc/api_web/venv/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/Users/stein/Documents/renbloc/api_web/venv/lib/python3.7/site-packages/django_crontab/management/commands/crontab.py", line 29, in handle Crontab().run_job(options['jobhash']) File "/Users/stein/Documents/renbloc/api_web/venv/lib/python3.7/site-packages/django_crontab/crontab.py", line 141, in run_job module_path, function_name = job_name.rsplit('.', 1) ValueError: not enough values to unpack (expected 2, got 1) I have the following in the settings.py file: Cron_Dir = BASE_DIR + '/api/cron/my_cron_job' CRONJOBS = [ ('* * * * *', Cron_Dir) ] and the function my_cron_job is just: def my_cron_job(): a = 1+1 I first thought crontab somehow got 2 functions registered instead of one but after removing all tasks with: python manage.py crontab remove and then adding the tasks again I still get the same error. Would really appreciate some help. -
django rest framework filter on related tables
i need help filtering on a field on a related table. I have tow models Kalas and names, where one (Kalas model) has a one to one relation with the basic User model: class Kalas(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) visitKalas = models.ForeignKey('self', on_delete=models.DO_NOTHING, blank=True, null=True) isActive = models.BooleanField(default=True) capacity = models.IntegerField(default=0) fullName = models.CharField(max_length=100, default="default name") phoneNumber = models.IntegerField() address = models.CharField(max_length=40) postal = models.CharField(max_length=50) time = models.DateTimeField(auto_now_add=True) lat = models.FloatField(default=0) lng = models.FloatField(default=0) def __str__(self): return "user: %s, address: %s %s" % (self.user, self.address, self.postal) class names(models.Model): kalasID = models.ForeignKey(Kalas, on_delete=models.CASCADE, related_name='names') name = models.CharField(max_length=30) and i have made a nested serializer: class NamesMapSerializer(serializers.ModelSerializer): class Meta: model = names fields = ['name'] class KalasMapSerializer(serializers.ModelSerializer): #bruk denne hver gang man vil ha kalas og navn sammen names = NamesMapSerializer(many=True, read_only=True) class Meta: model = Kalas fields = ['id', 'fullName', 'capacity', 'lat', 'lng', 'names'] class MapSerializer(serializers.ModelSerializer): kalas = KalasMapSerializer() class Meta: model = User fields = ['username', 'kalas'] and a view that lists all users and its kalas with names: class MapViewSet(viewsets.ModelViewSet): queryset = User.objects.all() permissions_classes = [permissions.AllowAny] serializer_class = MapSerializer but i dont know how to filter so it only shows users with kalas that i active kalas.isActive=True. i've tried … -
Django - set ONE session_key for every visitor/browser and remember it without logging in
I'm trying to create e-commerce cart in Django and got into trouble with session_key. When I'm logged in the admin page, my session_key is always the same. But after I logout, my session_key is None. So I call request.session.create() but after refreshing the page, session_key is again None. Is there any way how to force Django to remember user's browser? So how could I implement the same logic as is for logged users for not logged users? Thanks! -
How do i solve [Errno 13] Permission denied: 'list.txt'
I recently lunch a small video downloading website.Which has list.txt file inside it.When a user enter a url it was suppose to write a url to that list.txt file and again read from it.It was working fine in localhost but in production it throws error. [Errno 13] Permission denied: 'list.txt' Request Method: GET Django Version: 3.0.2 Exception Type: PermissionError Exception Value: [Errno 13] Permission denied: 'list.txt' I performed several chmod operations but didnt work. -
How to process Javascripts FormData object within Django Post using Ajax and Native Javascript
How can Javascripts FormData object be processed (data extracted from the FormData object) within Django class based view, post method using Ajax and native Javascript, NOT JQuery? // Javascript var form = document.GetElementById('my-form'); var formData = new FormData(form); var request = new XMLHttpRequest(); request.open('POST', 'my/django/url/', true); request.send(formData); Then in Django class based view post method what do I do? # Django / Python if request.is_ajax(): form_data_post = request.POST.get(formData['post'], None) form_data_files = request.FILES.get(formData['files'], None) # Process the formData here I can receive the formData object in request.POST but it's a mess and I can't make sense of it so I'm not sure if I'm sending it correctly or not, or if I need to do something special in Django to process it. I know there is csrftoken and other things to consider in the AJAX call which I haven't included here as that's not my concern. Google hasn't been my friend with this one. -
How to store in and access from , GAE /tmp to Django html?
I found this link that says we can use /tmp to store files for our instance in Google App Engine. https://cloud.google.com/appengine/docs/standard/python3/using-temp-files But the problem is that 1) How do i store to the \tmp folder, is it by just writing the save path as = "\tmp" or something else 2) How will i access those files stored in the \tmp folder in my django html page, currently i can assess the static files using {% static %} tag -
Getting ModuleNotFoundError when trying to load Scrapy settings from environment variable
I am running Scrapy with a Django project and am trying to define the Scrapy settings from outside of the Scrapy project. I am using get_project_settings() which looks for the environment variable SCRAPY_SETTINGS_MODULE. I have managed to set this to scraper.crawling.crawling.settings but when get_project_settings() is run, I am shown the error: ModuleNotFoundError: No module named crawling. This is correct, since crawling is a directory and not the module, settings is, which I am trying to direct it to. Is anyone able to help me such that get_project_settings will correctly find the module settings? Below is the folder structure I am using: ├───django-scraper | ├───django_scraper | | └───settings.py | │ | ├───scraper | │ ├───crawling | │ │ └───crawling | │ │ ├───spiders | │ │ ├───settings.py | | | └───crawler_process.py The following is in my Django settings.py so this is set upon starting the server: os.environ['SCRAPY_SETTINGS_MODULE'] = 'scraper.crawling.crawling.settings' get_project_settings() is called from within crawler_process.py, although I don't think the location is an issue since it is looking at the enviornment variable anyway. My sys.path already has 'C:\\Users\\georg\\Django\\django-scraper' in it, and it appears to access scraping fine but then tries to take scraper.crawling as a module. I hope that's enough information … -
changing elasticsearch default min_term_freq and min_doc_freq
I use this technologies/packages in django for handling search page elasticseach 2 (as search database) elasticseach-py django-haystack (as search tools with elasticseach backend engin) drf-haystack (for using django-haystack in django-rest-framework) where can I change min_term_freq and min_doc_freq default values because my More Like This search not working any other suggestions are welcomed -
link should only be visible to the superuser and the group
I have the below url for in the _base.py which will render a link in the left side when the user hovers a section called Uploads, {'label': 'Upload User Data', 'url': '/admin/user/bulk_user_update/', 'permissions': 'bulkupdate.access_user'}, I want this url only to visble to the superuser and the current permission bulkupdate.access_user How can i achieve this any help is appreciated -
Is 304 error being caused by ManifestStaticFilesStorage
I have recently noticed that I am getting the following when I run my Django project locally: "GET /static/MySearch/css/style.css HTTP/1.1" 304 0 i) I am running it in debug mode. ii) The file is clearly visible within the MySearch static directory, but also within the static directory that is created using collect static iii) I have recently added the following to the settings file: STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' I was wondering if the 304 error was being caused by ManifestStaticFilesStorage and if I needed to worry about it ? Thanks Mark -
Django Model Import Error: ValueError: attempted relative import beyond top-level package
I have created a new app "grn" in my django project and tried to import the models from another app named "packsapp" in the same project like this: Models.py from ..packsapp.models import * But I got the following error: ValueError: attempted relative import beyond top-level package Here's the structure of the app: yantra_packs grn --migrations __init__.py admin.py apps.py models.py tests.py views.py media packsapp --migrations templates templatetags views1 __init__.py apps.py decorators.py forms.py models.py urls.py views.py How can I import the models of the packsapp in the grn ?? -
Probleme with content types and parsers/renders with django rest_framework
I'm using django rest framework to recieve SOAP messages. I create a custom Parser and Render but now I have a problem with content types. My render and parser content_type is 'text/xml' and ONLY accepts this post content type. There is a way to add more content types? I've search in the docs but I've not found anything appart from creating new parsers/renders for any content type. The main is problem is that my client who sends me soap messages change the content type and I would like to accept them all. Thank you! -
Run custom one time script django
I want to run a custom one time script (to read from Excel file and write to DB) the problem is when i run python manage.py shell < poligon/run.py I lose when all data in run.py The project structure is .venv apps/ -- all my apps poligon/ run.py manage.py settings/ -
Unable to upload file from Angular using pre-signed url?
My Backend(Django) generates the presigned URL's as: session = boto3.Session( aws_access_key_id=*****, aws_secret_access_key=*****, region_name=*****, ) s3 = session.client('s3') url_object = s3.generate_presigned_post(Bucket=bucket, Key=key, ExpiresIn=expiry) return url_object I upload file from my Frontend(Angular 8) to the pre-signed URL as follows: this.http.post(url, form).subscribe(result=>{ const presigned_url = result; this.customHttp.post(String(presigned_url["url"]), file, {params: presigned_url["fields"]}).subscribe(); }); This throws the following message: <Error> <Code>MethodNotAllowed</Code> <Message>The specified method is not allowed against this resource.</Message> <Method>POST</Method> <ResourceType>BUCKETPOLICY</ResourceType> <RequestId>4A605D8379FFCDDD</RequestId> <HostId>e8jvo5mJwkXad7Wg0wIvy3E0FYHVPY96mxZeFLhznsVM5cs8uaTfVqiWxekoowqU805g+y+xV3g=</HostId> </Error> Now, when I try to upload file to the pre-signed URL using the following python code, it works: url = url_object['url'] data = url_object['fields'] files = {'file': open('/../../../image.png', 'rb')} requests.post(url, data=data, files=files) Can someone help me with this, as I want to upload the file from my Frontend(Angular) ?