Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to convert a form data that contains image files to json file using in python django and i am not using django restframe work just python&django
@csrf_exempt def registerSeller(request): print(request.body) data = json.loads(request.body.decode('utf-8')) i am new for django and trying to build api with out django restframework and this is the output for request.body but it gives me error AttributeError: 'bytes' object has no attribute 'read' request.body b'-----------------------------344288735834045826241553250616\r\nContent-Disposition: form-data; name="username"\r\n\r\nabe7\r\n-----------------------------344288735834045826241553250616\r\nContent-Disposition: form-data; name="password"\r\n\r\n123\r\n-----------------------------344288735834045826241553250616\r\nContent-Disposition: form-data; name="phonenumber"\r\n\r\n091010101\r\n-----------------------------344288735834045826241553250616\r\nContent-Disposition: form-data; name="email"\r\n\r\nemail@gmial.com\r\n-----------------------------344288735834045826241553250616\r\nContent-Disposition: form-data; name="shop_description"\r\n\r\ndescription new\r\n-----------------------------344288735834045826241553250616\r\nContent-Disposition: form-data; name="shop_name"\r\n\r\nname new\r\n-----------------------------344288735834045826241553250616\r\nContent-Disposition: form-data; name="images"\r\n\r\n[object File],[object File],[object File]\r\n-----------------------------344288735834045826241553250616--\r\n' -
Cannot connect to mssql database using Django (Mac OS)
My mssql database is inside the docker container. When trying to connect to the database using azure data studio I don't get any errors, whereas when I'm trying to connect to the db using Django I get the following error: Traceback (most recent call last): File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check_migrations() File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/core/management/base.py", line 486, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/db/migrations/loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations if self.has_table(): File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 55, in has_table with self.connection.cursor() as cursor: File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/utils/asyncio.py", line 33, in inner return func(*args, **kwargs) File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/db/backends/base/base.py", line 259, in cursor return self._cursor() File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/mssql/base.py", line 230, in _cursor conn = super()._cursor() File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/db/backends/base/base.py", line 235, in _cursor self.ensure_connection() File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/utils/asyncio.py", line 33, in inner return func(*args, **kwargs) File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/Users/aleksandr/Desktop/teplo/teplo_back/venv/lib/python3.9/site-packages/django/utils/asyncio.py", line 33, in inner return … -
How to send continuous response in python Django?
I want to run the following command and its sending output to template def nikto(request): context = {} host = request.GET.get('host', False) nikto_output = os.popen('nikto -h ' + request.GET['host']).read() # context['nikto_output'] = nikto_output context['nikto_output']=nikto_output return render(request,'nikto.html',context) # return render(request,'nikto.html',context) but it's first performing a complete task and then sent to the template, till then webpage is loading, I want to display one-by-one line output. if you know of any solution, please let me know. -
Don't want django makemigration to create a table in database as the I already have the table in the database
I already have a table name browser in my database and when I create a new django project and run python3 manage.py makemigrations command it adds a new table name BrowserAddition_browser in the database. How should I stop django from making a new table and use the current table which is present in the database.Thanks in advance for your help. This is model => model that i want to use in django browser(created before the project) and BrowserAddition_browser (create by django) -
django admin site foreign key from dropdown to search_field
Im a bit stuck at why a foreign key drop-down field in admin site is not changing to a search field. I read the documentation that states: These fields should be some kind of text field, such as CharField or TextField. You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API “follow” notation: search_fields = ['foreign_key__related_fieldname'] I have two models: class Company(models.Model): company = models.CharField(max_length=100) class User(AbstractUser): company = models.ForeignKey(Company, on_delete=models.CASCADE) When I want to create a user manually via admin site I get a drop-down list of possible companies as foreign keys I though that this solution should change the drop-down to a search field but it isnt. What am I doing wrong here? How to change this foreign key field to a search field? admin.py from django.contrib import admin from .models import Company, User class MyAdmin(admin.ModelAdmin): search_fields = ['company__company'] admin.site.register(Company) admin.site.register(User, MyAdmin) -
django how to change database with click button on new window and close, refresh the main page?
I made 'alert list' page. (alert_list.html) and when I click the button, it renders detail page uses pk on new window. (alert_detail.html) But , I have some problem with handle this. The things what I want to do is.. change Event.event_status value to 0. close new window(detail page) refresh main page(alert list page) <alert_list.html> {% for event_alert in event_list %} {% if event_alert.event_status == 1 %} <div class="col-1 red"> <div class="p-3 rounded-2" id="dash_board_patient_alert"> <a href="{% url 'Alert Detail' event_alert.event_id %}">{{event_alert.member_id}} {{event_alert.event_type}}</a> </div> </div> {% endif %} {% endfor %} {{event_alert_activate_count}} {{pink_block}} {% for _ in pink_block %} <div class="col-1 pink"> <div class="p-3 rounded-2" id="dash_board_patient_alert"> <a href="#"></a> </div> </div> {% endfor %} <alert_detail.html> {% for event_alert in event_list %} <form method="POST" class="post-form" action ="{% url 'Alert Update' event_alert.pk %}"> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-primary" id="patient_alert_result_confirm"> Confirm </button> </form> {% endfor %} <alert_update.html> I don't have any idea.. help me this page <views.py> def alert_list(request): Event.objects.order_by('-event_time')[:12] event_alert_activate_count = Event.objects.filter(event_status__startswith='1')[:12].count() pink_block = int(12) event_list = Event.objects.order_by('-event_time') context = { 'event_alert_activate_count': event_alert_activate_count, 'event_list' : event_list, 'pink_block' : pink_block } return render(request, 'dashboard/alert_list.html', context) def alertDetail(request,pk): event = get_object_or_404(Event, pk=pk) event_list = Event.objects.order_by('-event_time')[:1] context = {'event_list': event_list, 'event' : event,} … -
Django prefetch m2m through model
I have the following models: class Block(MPTTModel): # some fields links = models.ManyToManyField('self', through='BlockLink', symmetrical=False) class BlockLink(models.Model): source = models.ForeignKey( 'Block', on_delete=models.CASCADE, related_name='source_block' ) destination = models.ForeignKey( 'Block', on_delete=models.PROTECT, related_name='destination_block', null=True ) is_valid = models.BooleanField(default=False) With that, I can access the through model using: my_block.links.through.objects.filter(source=my_block.id) My problem is, that I access the blocks in a loop, and each of the blocks creates an own query to select the through model. So for 5000 blocks, we have 5000 additional queries. How can prevent this. Is there any way of annotating or prefetching the through model? What I tried? I tried the solution from Django prefetch through table using .prefetch_related('blocklink_set') but that ends up in the following error: Cannot find 'blocklink_set' on Block object, 'blocklink_set' is an invalid parameter to prefetch_related() Second try was .prefetch_related( Prefetch('blocklink', queryset=BlockLink.objects.all()), ) but that also ends in an error. -
amazon face rekognition changing request object
I am working on an image proctoring project, after including Amazon S3 bucket storage, i am receiving different request object from js(client) previously I was able to decode the request.body but after integrating S3 it's not working , it's sending me bytes, I am confused does S3 make any changes to request or Django middleware ? def post(self,request): frame_data = json.loads(request.body.decode('utf-8')) print(frame_data) actual_image = data_uri_to_cv2_img(frame_data['img_frame']) push_frame(actual_image,'register',frame_data['mode']) #push data when capture button is clicked on client if frame_data['mode'] == 'mentoring': try: random_img = ImageFrames.objects.filter(frame_captype__frame_captype = 'register',frame_captype__frame_cap_mode ='random').last().image_frame last_img = ImageFrames.objects.filter(frame_captype__frame_captype = 'register',frame_captype__frame_cap_mode='mentoring').last().image_frame res = compare_faces(random_img,last_img) if res['FaceMatches'][0]['Similarity'] > 90: compare_status = True else: compare_status = False data obj i am sending from client img_frame= { img_frame:data, <--- this is image in bytes mode:'mentoring' } var save_frame = (img_frame) => { if (img_frame.mode != 'random') { img_frame['mode'] = 'mentoring' } fetch( '/save_frame/', { method:'POST', body: JSON.stringify(img_frame) } ).then((resp)=>{ return resp.json() }).then((resp_data) data i am receiving after S3 data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAADhCAYAAAByfIirAAAgAElEQVR4nMy795PcZp7mqX9lZ3ZudqbddKtlWhKbFClDkSJF0Ym+isUy6YHMBJCJ9FnesDxZJMt7X1k+K8t77w2r6J0o7yhRnuazPxS3e29m7uIi7uJ2f3jiDQBvAMiIxAfP9/s+eC4ixkp4jIzWoGA0yIgGG6LgRG+yodNLiIINg9GC3mLBZLOj18oYjAqCqCIYnJgMLgwGFYPBhE40oDUa0YlWBEnGareh+p044hxIVg2yoEE26bAKBiSLCavZiFUwYTEZMUVHYzwTgVGvQTSaseglzHoRwWhEMGoxGTQImmjM+hhsNg12JQpV0uBSonFaInHLIqrVhNdhwSlbkAUrqqSgWgXsFj0ui4G8s8mUlRdRWVVKSdkFSoou0dHWSH9vG0P9nXR3NdPV1URvKEB/KMD0RA9Ts32Mj/cxNNhLa2OAzk -
(DJANGO) retrieving data from html form using GET/POST
This is part of the CS50W courseware Project 1. I have tried to retrieve a user input from a form using a get method. However, the search_query variable in views.py does not have any input. I then changed the get methods to post methods and it worked. Why is that so? layout.html(get method) <form action="{% url 'search' %}" method="GET"> <input type="search" name="search_query" placeholder="Search Encyclopedia"> </form> views.py(get method) def search(request): search_query = request.GET['search_query'] if search_query in util.list_entries(): return redirect('entry_page', title=search_query) for entry in util.list_entries(): if search_query in entry: return redirect('search_results') layout.html(post method) <form action="{% url 'search' %}" method="POST"> {% csrf_token %} <input type="search" name="search_query" placeholder="Search Encyclopedia"> </form> views.py(post method) def search(request): search_query = request.POST['search_query'] if search_query in util.list_entries(): return redirect('entry_page', title=search_query) for entry in util.list_entries(): if search_query in entry: return redirect('search_results') -
What is the connection between autocomplete_fields and JS in Media class?
I use Django. My admin.py: class CardInlineAdmin(admin.StackedInline): model = Card autocomplete_fields = ['project', 'course', 'vacancy', 'news', ] @admin.register(Section) class SectionAdmin(admin.ModelAdmin): list_display = ('name', 'id', 'priority', 'is_active',) inlines = (CardInlineAdmin,) search_fields = ['project', 'course', 'vacancy', 'news'] class Media: js = ( '//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js', 'js/card_in_section.js', ) If I open SectionAdmin on admin page the file card_in_section.js will not work. If I remove autocomplete_fields from CardInlineAdmin the file card_in_section.js will work. What is the reason of such behavior? -
How to count validate formset?
How to count how much the filled fields in formset object ? For example, I have a formset of form and each form has ChoiceField. How do I count the total filled ChoiceField in formset when each form of the formset is validated ? Thank you. -
ModelForm with multiple values not responsive
so I encountered this problem with Django and ModelForms. Everything loads as expected but when I'm trying to send data by hitting Enter nothing happens. models.py class Drinks(models.Model): name = models.CharField(max_length=50) number = models.DecimalField(decimal_places=2, max_digits=2000) def __str__(self): return self.name forms.py ( I tried with list and tuple as well ) class DrinksForm(forms.ModelForm): class Meta: model = Drinks fields = [ 'name', 'number' ] views.py def DrinksView(request): form = DrinksForm(request.POST or None) if form.is_valid(): print("VALIDATION COMPLETE") form.save() form = DrinksForm() return render (request, 'form2.html', { 'form' : form }) template.html <form method="POST"> {% csrf_token %} {{ form.as_p }} </form> admin.py from django.contrib import admin from .models import Drinks admin.site.register(Drinks) I did all necessary migrations. Any Ideas what im doing wrong? -
Django static tag variable
I'm trying to get images with Arabic names using this code: {%for book in books%} {% with 'BookCover/'|add:book.BookName|add:'.jpg' as image_static %} <img class="card-img-top" src="{%static image_static%}"> {%endwith%} {%endfor%} But when I'm running the server the name appears like this: <img class="card-img-top" src="/static/BookCover/%D9%81%D8%B5%D9%88%D9%84%20%D9%81%D9%8A%20%D8%A7%D9%84%D8%AB%D9%82%D8%A7%D9%81%D8%A9%20%D9%88%D8%A7%D9%84%D8%A7%D8%AF%D8%A8.jpg"> and if I have any mistakes in the question please correct me -
Using inherited class method on Django models classes
I have two Django model classes with their respective DB tables, both using the same class method. So I refactored and created a parent class with the class method: from django.db import models from django.forms.models import model_to_dict class Parent(models.Model): @classmethod def get_random(cls, variables: Set[str]) -> str: elements: list = [] for o in cls.objects.filter(active=True): elements.append(model_to_dict(o, fields=["id", "string"])) chosen: dict = choice(elements) # some other code... return chosen["string"] class Child1(Parent): string = models.CharField(max_length=100) type = models.ManyToManyField(Type, related_name="article_titles") active = models.BooleanField(default=True) class Meta: db_table = "table_child_1" class Child2(Parent): string = models.TextField() active = models.BooleanField(default=True) class Meta: db_table = "table_child_2" When I call the method on one of the child class with chosen_string: str = Child1.get_random(variables=variables) for example, I get a Django DB error: django.db.utils.OperationalError: no such table: app_name_parent. So it seems the parent class method is called on the default Django DB table name for parent class, instead of the child. What do I miss here? What would be the most elegant solution for using the same custom class method requesting the DB for two Django models? -
can we store rendering object in django
def fun(user, package_id, request): created_payment_request_object = ""; context = {}; return created_payment_request_object, render(request, 'index.html', context=context) I'm returning from fun and storing these returned values as payment_obj and rendered_obj payment_obj, rendered_obj = fun(user, package_id, request) Is it the right way? can we store a rendering object? -
Connecting my Django allauth project to MongoDB
I'm a newbie and I'm trying to connect my Django 3 project to my MongoDb, but when I trying to migrate I get an error code (See below) My DB connection code: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'my2ndBaseDB', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': 'mongodb+srv://<username>:<password>@my2ndbasecluster.wbu1f.mongodb.net/my2ndBaseDB?retryWrites=true&w=majority' } } } (In my code I have the correct username and password) This is the error code it throws at me: Error code: Operations to perform: Apply all migrations: account, admin, auth, contenttypes, sessions, sites, socialaccount Running migrations: Applying account.0003_auto_20211102_1418...Not implemented alter command for SQL ALTER TABLE "account_emailaddress" ALTER COLUMN "id" TYPE long Traceback (most recent call last): File "/workspace/.pip-modules/lib/python3.8/site-packages/djongo/cursor.py", line 51, in execute self.result = Query( File "/workspace/.pip-modules/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 784, in __init__ self._query = self.parse() File "/workspace/.pip-modules/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 876, in parse raise e File "/workspace/.pip-modules/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 857, in parse return handler(self, statement) File "/workspace/.pip-modules/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 889, in _alter query = AlterQuery(self.db, self.connection_properties, sm, self._params) File "/workspace/.pip-modules/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 425, in __init__ super().__init__(*args) File "/workspace/.pip-modules/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 84, in __init__ super().__init__(*args) File "/workspace/.pip-modules/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 62, in __init__ self.parse() File "/workspace/.pip-modules/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 441, in parse self._alter(statement) File "/workspace/.pip-modules/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 500, in _alter raise SQLDecodeError(f'Unknown token: {tok}') djongo.exceptions.SQLDecodeError: Keyword: Unknown token: TYPE Sub SQL: None FAILED … -
Django-CMS nav third child?
I need to display the third level in my navigation. Only the second level is displayed. Like this: |- Home |- About us |-|- History |-|-|- WW1 |-|-|- WW2 |- Contact I still hope there is someone who solved this problem! Thank youuu! {% for child in children %} {% if child.is_leaf_node %} <li><a href="{{ child.attr.redirect_url|default:child.get_absolute_url }}" title="{{ child.get_menu_title }}">{{ child.get_menu_title }}</a></li> {% endif %} {% if not child.is_leaf_node or child.ancestor %} <li class="dropdown"><a href="{{ child.attr.redirect_url|default:child.get_absolute_url }}" title="{{ child.get_menu_title }}">{{ child.get_menu_title }} ></a> <ul class="dropdown-menu xpl1"> {% for kid in child.get_descendants %} {% if kid.is_leaf_node %} <li><a href="{{ kid.attr.redirect_url|default:kid.get_absolute_url }}" title="{{ kid.get_menu_title }}">{{ kid.get_menu_title }}</a></li> {% endif %} {% if not kid.is_leaf_node or kid.ancestor %} <li class="dropdown"><a href="{{ kid.attr.redirect_url|default:kid.get_absolute_url }}" title="{{ kid.get_menu_title }}">{{ kid.get_menu_title }} ></a> <ul class="dropdown-menu xpl1"> {% for kidkid in kid.get_descendants %} <li><a href="{{ kidkid.attr.redirect_url|default:kidkid.get_absolute_url }}" title="{{ kidkid.get_menu_title }}">{{ kidkid.get_menu_title }}</a></li> {% endfor %} </ul> </li> {% endif %} {% endfor %} </ul></li> {% endif %} {% endfor %} ``` -
How to remove a user from all ther groups they belong to in django model?
For instance, I have two model Group and OrganizationUser. members is a field in Group model which defines as members=models.ManyToManyField('organizations.OrganizationUser', related_name="member_in_groups", blank=True) Which means a Group instance can have zero or multiple member and an OrganizationUser instance be a member of zero or multiple Group For a instance of OrganizationUser user1 I can do user1.member_in_groups.all() to access all the groups user1 is a member of. I want to remove user1 from all the groups user1 is a member of. I'm feeling iterating over the groups one by one and remove user1 isn't a right approach. What is the right way of doing so? -
Django template view
I'm just trying to understand something with Django and views. I have a form within an HTML page that I can add data to post to a database. Within this form, I have a field called Twitter Handle. When the field is updated I want to write a function that will call the Twitter API and return the number of followers. But as far as I'm aware, this cannot be done without the use of something like JavaScript that would monitor the field and then send a request to the python function to return the data? What I can't understand is that a view is bound to a function, so if I have a class view class addInvestorView(View): template_name = 'pages/add_investor.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request, *args, **kwargs): form = addInvestorForm(request.POST) if form.is_valid(): form.save() data = {"success": "successfully added"} else: data = {"error": form.errors} return JsonResponse(data, safe=False) How do I send a GET from JavaScript without refreshing the page, or how do I call a function without it being rendered within another page? Am I really misunderstanding all of this? -
Why does Django allow incoming connections not specified in ALLOWED_HOSTS?
Scenario - Someone is requesting a url served by a Django app. His IP is 3.3.3.3 . It could be a client but could be a server too, I don't know at the time of the request. In project settings file, there is ALLOWED_HOSTS = ["1.1.1.1", "2.2.2.2"] He (3.3.3.3) is still served. What are the allowed hosts for then? -
CSRF token missing error using vue-recaptcha and a Django Rest Framework middleware
I have the following setup : a frontend app developed with VueJS on which I have a registration form component, including few standard fields, a mandatory checkbox (user agreement), and a Google Recaptcha V2 (vue-recaptcha) checkbox a backend API developed with Django Rest Framework, with a specific route to request Google Recaptcha web service (using rest_framework_recaptcha application) I don't have any issue working in a development environment (frontend and backend accessible on localhost). Yet, when deployed in production (with https enabled), I face the following problem: Checking the user agreement checkbox first, then the Recaptcha works fine Checking the Recaptcha then the user agreement returned a 403 Forbidden error, with the message CSRF token missing or incorrect Once I get the previous error, I always get the error when filling the form again, no matter the order of checking boxes I don't get why: the problem does not occur on localhost the order of filling form lead to different behaviours the problem only occurs on my registration form while I do have several other forms (login, sending data, etc.) that work fine Any ideas to help me understand/investigate the problem ? I have read many posts related to Django and … -
index button to open a contact from in for loop in django
i have a card view in my site how do i address my button which should open a pop up contact form {% for dat in placeddata %} <div class="col-sm"> <div class="card" style="width: 18rem;"> <img src="{{dat.student.profileimg}}" width="250px" height="250px" class="card-img-top"> <div class="card-body"> <h5 class="card-title">{{dat.student.user.get_full_name}}</h5> <p class="card-text">Has been placed in {{dat.company.Comp_name}} Company.</p> <img width="50px" class="img-fluid" src="{{dat.company.profileimg}}"> <a href="" class="btn btn-primary">Contact</a> </div> </div> </div> {% endfor %}``` -
Keeping files uploaded on a site hosted on heroku in heroku postgres
I am hosting a site with django as backend, on heroku, and am using heroku postgres as database. Is there a way of keeping the files uploaded on the site in heroku postgres itself, without it getting removed after a certain period? I am assuming that there a way, since only files uploaded are removed and nothing else stored on the database. Also the organization I am developing a site for cannot use stuff like AWS due to tight budgeting. They do not expect heavy traffic on their site, hence if heroku postgres does not work, please suggest any alternate way to handle file/image uploads, without losing them -
From sqlite to PostgreSQL DB, has_perm method isn't working properly with programatcaly created permissions
I recently switched my django app from sqlite to PostgreSQL. After setting up the PostgreSQL DB, I did a dumpdata into a json file, changed the settings.py file accordingly to the new engine, and then a loaddata. Everything worked properly*. My entry point for my website is the following: @login_required def index(request): """View function for home page of site.""" if request.user.has_perm("myapp.access_main"): return redirect("myapp:main") elif request.user.has_perm("myappp.access_second"): return redirect("myapp:second") else: return PermissionDenied Users don't have permissions in my app, but groups for which they're part of do have. I have 2 groups(mods and group1, both have the "myapp.access_main" permission just like with my old db). If I connect as admin (a superuser, that I created with the sqlite db, which is part of group mods), everything works fine, I'm redirected to the main page. However, if I connect as a user1 (user created through the admin interface, created with the sqlite db too, is part of the group group1), the has_perm(...) method returns always False, hence a PermissionDenied is raised. I don't understand why the has_perm method is not working as intended for non-superusers. *: One important note is that I had to dumpdata with an exception: ./manage.py dumpdata myapp --exclude=myapp.RightsSupport. The … -
Django handle incoming chunked files by JS
I am currently writing a basic Django application which should be able to handle big files, which will be uploaded by a user. By now, as I expect very large files to be uploaded, I am chunking the files on the javascript side according to this https://newbedev.com/split-an-uploaded-file-into-multiple-chunks-using-javascript. To show the code: function fillFastaUploader() { document.getElementById("submitButton").addEventListener('click', function(e) { const size = 40000; let reader = new FileReader(); let buf; let file = document.getElementById('fastaFileUpload').files[0]; reader.onload = function(e) { buf = new Uint8Array(e.target.result); for (let i = 0; i < buf.length; i += size) { let fd = new FormData(); fd.append('fname', [file.name, i+1, 'of', buf.length].join('-')); fd.append('data', new Blob([buf.subarray(i, i + size)])); let oReq = new XMLHttpRequest(); oReq.open("POST", '', true); oReq.onload = function (oEvent) { // Uploaded. }; oReq.send(fd); } } reader.readAsArrayBuffer(file); }); } The problem is that when I try to upload a large file on the server (IIS), the file still seem to be too big (get an internal 500 error, small files are working). In Django I am currently just reading the file in like: readInputFasta = request.FILES['fastaFile'] Do I need to stream in the data in Django somehow or is there another way? Programs used: Django 3.2.4 IIS 10