Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
A model to handle multiple types with different fields in Django
In django I should create this model which I then use in django rest framework for api requests: A criterion model which can be of three types: qualitative, quantitative and multiple. In the quantitative case, the criterion template has only one description field. In the qualitative case, the criterion model has one description field and two other integer fields In the qualitative case, the criterion model has a description field and multiple fields of the type "name" and "weight". I was thinking about such an implementation but it seems too little pythonic to me: class Criterion(models.Model): TYPES_LIST = ( ('QUALITATIVE', 'Qualitative'), ('QUANTITY', 'Quantity'), ('MULTIPLE', 'Multiple choice'), ) type = models.CharField(max_length=64, choices=TYPES_LIST) description = models.TextField() class Meta: abstract = True class QualitativeCriterion(Criterion): decision_scheme = models.ForeignKey(DecisionScheme, on_delete=models.CASCADE, related_name='qualitative_criteria') class QuantityCriterion(Criterion): CLASSIFICATIONS_LIST = ( ('TEST1', 'TEST 1'), ('TEST2', 'TEST 2'), ) MEASUREMENT_UNITS_LIST = ( ('M', 'Meter'), ('CM', 'Centimeter'), ) classification = models.CharField(max_length=64, choices=CLASSIFICATIONS_LIST) measurement_unit = models.CharField(max_length=64, choices=MEASUREMENT_UNITS_LIST) decision_scheme = models.ForeignKey(DecisionScheme, on_delete=models.CASCADE, related_name='quantity_criteria') class MultipleChoicesCriterion(Criterion): decision_scheme = models.ForeignKey(DecisionScheme, on_delete=models.CASCADE, related_name='multiple_choices_criteria') class MultipleChoicesCriterionOption(models.Model): description = models.CharField(max_length=255) weight = models.PositiveIntegerField() criterion = models.ForeignKey(MultipleChoicesCriterion, on_delete=models.CASCADE, related_name='options') I would like that from the decision schema calling a related name of the type "criteria" I get all but implementing … -
Passing task url to initProgressBar in Celery Progress returns 400 (Bad request)
I am building an app with django and docker. I decided to use celery progress to track the progress of a long task. I think it is maybe due to the url that I pass or the way I pass it. Substantially after button click I send an ajax call to start the task and another to wait for the task id on the same view. That returned would trigger the initProgressBar. urls.py(project) from django.contrib import admin from django.urls import path, include, re_path urlpatterns = [ path('admin/', admin.site.urls), path('', include('mappa.urls')), path('celery-progress/', include('celery_progress.urls')), ] main.js const poll_state = function(){ $.ajax({ type: 'POST', url: $('#ProcForm').data('url'), dataType: 'json', data: { 'poll_state': 'yes', 'csrfmiddlewaretoken': csrftoken, }, success: function(res){ if (res['onHold'] == 'yes'){ console.log(res) setTimeout(function(){ poll_state() }, 500) } else{ console.log(res) var task_id = res.proc_id var progressUrl = '{% url "celery_progress:task_status" "task_id" %}'; var progressUrl = progressUrl.replace("task_id", task_id) CeleryProgressBar.initProgressBar(progressUrl); // <--- This is the line triggering the error } } }) } settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'leaflet', 'django_celery_beat', 'django_celery_results', 'crispy_forms', 'corsheaders', 'celery', 'celery_progress', 'mappa' ] CELERY_BROKER_URL = 'redis://redis:6379/0' CELERY_RESULT_BACKEND = 'redis://redis:6379/0' CELERY_CACHE_BACKEND = 'django-cache' CELERY_ACCEPT_CONTENT = ['application/json', 'json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Europe/Rome' -
How to get current in django urls.py using requests module
I need to get current url using requests module in django For eg : In urls.py file import requests How to get current url using this module -
pytest-django: django_db_keepdb Does Not Prevent Destruction of Test Database
I am testing a Django (v. 4.1) application using pytest-django (v. 4.5.2). I want to preserve the database that is created during testing so that I can examine it afterward. According to the pytest-django documentation: django_db_keepdb Returns whether or not to re-use an existing database and to keep it after the test run. Here is how I am using it: import datetime import pytest from annotations import import_data @pytest.mark.django_db def test_import_data(django_db_keepdb): start_date = datetime.datetime(2016, 1, 1) end_date = datetime.datetime(2016, 6, 1) import_data.import_data(start_date, end_date) The test runs but pytest destroys the test database after the test run. Creating test database for alias 'default' ('test_vita')... PASSED [100%]Destroying test database for alias 'default' ('test_vita')... Perhaps I am misinterpreting what django_db_keepdb is supposed to do? How can I prevent the test database from being destroyed? -
Not updating the profile in Django
Not updating the profile in Django Error : int() argument must be a string, a bytes-like object or a real number, not 'function' **model: ** class Profile(AbstractUser): codemeli = models.CharField(max_length=10, verbose_name='کد ملی', unique=True) fname_en = models.CharField(max_length=150, verbose_name='نام لاتین') lname_en = models.CharField(max_length=150, verbose_name='نام خانوادگی لاتین') father = models.CharField(max_length=150, verbose_name='نام پدر', null=True) father_en = models.CharField(max_length=150, verbose_name='نام پدر لاتین', null=True) date_birth = models.DateField(verbose_name='تاریخ تولد', null=True) place_birth = models.CharField(max_length=150, verbose_name='محل تولد', null=True) gender = models.CharField(max_length=10,choices=Gender, verbose_name='جنسیت', null=True) status_marriage = models.CharField(max_length=10,choices=Status_Marriage, verbose_name='وضعیت تاهل', null=True) mobile = models.CharField(max_length=11, verbose_name='موبایل', null=True) phone = models.CharField(max_length=11, verbose_name='تلفن ثابت', null=True) method_introduction = models.CharField(max_length=10,choices=Method_Introduction, verbose_name='طریقه آشنایی', null=True) tahsilat = models.CharField(max_length=10,choices=Tahsilat, verbose_name='تحصیلات', null=True) reshte = models.CharField(max_length=150, verbose_name='رشته تحصیلی', null=True) job = models.CharField(max_length=150, verbose_name='َشغل', null=True) job_father = models.CharField(max_length=150, verbose_name='َشغل پدر', null=True) job_mather = models.CharField(max_length=150, verbose_name='َشغل مادر', null=True) mobile_father = models.CharField(max_length=11, verbose_name='موبایل پدر',null=True) mobile_mather = models.CharField(max_length=11, verbose_name='موبایل مادر',null=True) bank = models.CharField(max_length=150, verbose_name='َبانک / شعبه',null=True) account_number = models.CharField(max_length=150, verbose_name='شماره حساب',null=True) card_number = models.CharField(max_length=150, verbose_name='شماره کارت',null=True) shaba_number = models.CharField(max_length=150, verbose_name='شماره شبا',null=True) departman = models.ForeignKey(Departman, on_delete=models.CASCADE, verbose_name='متقاضی', null=True) state = models.CharField(max_length=150, verbose_name='استان',null=True) city = models.CharField(max_length=150, verbose_name='َشهر',null=True) area = models.CharField(max_length=150, verbose_name='َمنطقه',null=True) address = models.CharField(max_length=150, verbose_name='آدرس',null=True) description = models.TextField(verbose_name='توضیحات', null=True) image = models.ImageField(default='avatar.jpg', upload_to="Member/profile/", verbose_name='تصویر') status = models.CharField(max_length=4, choices=Status, verbose_name='وضعیت نمایش', null=True) semat = models.CharField(max_length=50, choices=Semat, null=True, verbose_name='سمت', default='0') … -
How to make an ER model with tables and relationships with a sqlite3 database
Working with Django, need an ER model. It doesn't have to be the original database in the first place. Any way to create one without manually drawing all of the tables? A solution that exports and imports into MySQL to reverse engineer also works. Tried Schemacrawler, didn't understand enough to use it. Tried to export it, again, not enough understanding. -
browser requests not completing
I have a django app served with uwsgi and nginx. This app has been deployed for 8 years and now we are seeing that browser requests do not complete. This is what we see in the request timing tab: ss shows only 3 connections to the origin. In the uwsgi log it appears the request has completed: {address space usage: 10855825408 bytes/10352MB} {rss usage: 560128000 bytes/534MB} [pid: 3279260|app: 0|req: 1/25] 10.240.0.58 () {46 vars in 1033 bytes} [Wed Mar 15 13:05:09 2023] GET /report/TASKS/BatchDashboard/ => generated 457971 bytes in 5765 msecs (HTTP/1.1 200) 6 headers in 327 bytes (4 switches on core 0) There are no errors in the nginx or django logs. Any thoughts on why this is suddenly happening and/or how I can debug or fix this? -
Django Design Pattern with NoSQL DynamoDB
This is a general design question as to how to best implement DynamoDB (or NoSQL/Key-Value in general) with the Django ORM for a rather large project with many django apps in it. I am planning on using this in conjunction with a regular SQL DB as well for the more "mundane" and not speed dependant queries. I've found some good insights in this stackoverflow answer already but I am wondering how this works in general as I have not used NoSQL DBs before. I am planning on using the PyNamoDB interface as it seems the most recommended and tested. I primarily require DynamoDB (KV-pair) for 1 or 2 tables that can potentially have several millions of "rows" written per day and then increasingly queried the same (high read&write traffic). Something that will eventually be just too much with a traditional SQL table and where a "model" with a single table data structure isn't really appropriate. Does anyone have experience on this topic especially relating the following questions: If the "traditional" Django model setup (models.Model) does no longer apply I assume and anything like using models.Manager and the traditional Queryset is out the question? If so then this then perpetuates all … -
How to use django-notification to send an anonymous notification to a user
I've implemented a notification sending when the certain object is changed. notify.send(request.user, #UserA recipient=worker.profile.user, #UserB target=application, verb="Your object has been changed") Here is the example of such notification "UserA: Your object Obj has been changed". But for my case I need to send this notification anonymously (just not display the name of UserA in notification) e.g. just "Your object Obj has been changed", but I still need the info about sender. I couldn't find any examples of such use of django-notification system, but it is mentioned in the documentation that there is an anonymous usage of the fields. I've tried to set sender field to None. But it has to be not empty. I've also tried to set actor field. Name of request.user is still mentioned in notification. -
Django: add localhost deployment to CSRF_TRUSTED_ORIGINS
I am trying to debug my cloud deployed Django app. I want to make request to the app using my locally deployed frontend app. I have made the localhost and localhost:3000 to trusted origins. CSRF_COOKIE_SECURE = True CSRF_TRUSTED_ORIGINS = [ 'http://localhost', 'http://localhost:3000', 'https://example.com', ] In my Django app, I still get CSRF verification failed. Request aborted. How can I add my local frontend deployment to CSRF_TRUSTED_ORIGINS? Should it be my external IP Address? What is the other way to debug this way and exempting my localhost frontend to the CSRF verification? -
check if scheduled actions are due
I use huey to create scheduled tasks, that run for example every minute. I created an example to display my question: class Campaign(models.Model): active = models.BooleanField("active", default = True) name = models.CharField("campaign name", max_length = 32) class CampaignTime(models.Model): campaign = models.ForeignKey(Campaign, on_delete = models.CASCADE) time_start = models.TimeField("start time") time_end = models.TimeField("end time") running = models.BooleanField("campaign running right now", default = False) ad_to_show = models.ForeignKey(Ad, on_delete = models.CASCADE) I am not sure if I implemented this "smoothly": from django.utils.timezone import localtime as T class CampaignService: for campaign in Campaign.objects.all(): for ctime in campaign.campaigntime_set.values(): if T.time() > ctime["time_start"] and ctime["running"] == False: ... ## start campaign and set ctime["runnning]" = True elif T.time() > ctime["time_end"] and ctime["running"] == True: ... ## end campaign and set ctime["running"] = False else: continue This somehow looks crude to me. Any suggestions on how to implement this more nicely? -
Get 1-4 Items via Django Rest Framework
I want to create awebapp where the user can choose between comparing 2,3 or 4 items of the database (Postgres). i already could create a view function to query a fixed amount of items. e.g query 3 Items View Function from myapp.models import Item @api_view(['GET']) def get_three_items(request, pk1, pk2, pk3): item1 = Item.objects.get(pk=pk1) item2 = Item.objects.get(pk=pk2) item3 = Item.objects.get(pk=pk3) data = [item1.serialize(), item2.serialize(), item3.serialize()] return Response(data) urls.py from django.urls import path from .views import get_three_items urlpatterns = [ path('items/<int:pk1>/<int:pk2>/<int:pk3>/', get_three_items), # ... ] But in my web app the user is able to choose between comparing 2,3 or 4 items. Is there a way to write the View Function and URL in a way, that it is dynamic or do i have to create a view for each compare capacity. So a view to compare 2 items. A view to compare 3 items and a view to compare 4 items? -
Django custom tags requires 3 arguments, 2 provided
#custom_tags.py def modulo(value, number,number2): mod = value % number if mod == number2: return True else: return False {% comment %} index.html {% endcomment %} {% for post in posts|slice:"1:"%} {% if post.id|modulo:4:0 %} <div class="post-entry-1"> <a href="{{post.slug}}"><img src="{{post.image.url}}" alt="" class="img-fluid"></a> <div class="post-meta"><span class="date">{{post.category}}</span> <span class="mx-1">&bullet;</span> <span>{{post.created_date}}</span></div> <h2><a href="single-post.html">{{ post.title }}</a></h2> </div> {% endif %} {% endfor %} ------------eror------- TemplateSyntaxError at /blog/ modulo requires 3 arguments, 2 provided When I mod the value with the variable number, I want to check the result with the variable number2 -
How to serve user uploaded media files in Django Production without any using anything else as a service?
What is the best way to serve media files in Production without using S3 or FTP? Whitenoise doesn't support it. I'll have to serve some ZIP files that'll be created from a view. I can compromise security aspects, will run it on RailwayApp. I had tried using Whitenoise but it doesn't support media files. -
How to pass model validations to ModelSerializer when using source parameter?
In my serializer I have my columns from model changed to different names because I need them that way in API. model: class User(models.Model): name = models.CharField(max_length=50, null=True) telephone_number = models.CharField(max_length=15, null=True, blank=True) serializer: class UserSerializer(serializers.ModelSerializer): phoneNumber = serializers.CharField(source='telephone_number') class Meta: model = User fields = ('name', 'telephone_number') But when I do it then serializer doesn't take into account validations given set in model. >>> serializer = UserSerializer() >>> print(repr(serializer)) UserSerializer(): name = CharField(allow_null=True, max_length=50, required=False) phoneNumber = CharField(source='telephone_number') <- no max_length here How to invoke these validations without need to duplicate them into serializer? (of course my models are considerably bigger that's why i'm asking) -
Watchman looking to opt/homebrew/root-state and can't access it
Im trying to run my Django server as I did lot of times before, but probably after update or so im receiving errors from watchman, specifically this one Watchman warning: opendir(/opt/homebrew/var/run/watchman/root-state) -> Permission denied. And its strange because from what I researched this folder should have restricted access. So I have two folders there, user-state and root-state Its still running server when im starting it, but throwing bunch of those errors in terminal so im just curios why its even watching in this dir. After deleting all watching paths its starts looking in this path again. -
Django ForeignKey to a model that might not exist
I want to set a foreign key in app1 to a model of app2 that is an optional dependency. To achieve loose coupling, i want app1 to work even if app2 is not installed, with that foreign key simply being deactivated. Is there a way to do this? (and is it a good idea?) # app1/models.py optional_field = models.ForeignKey( "app2.some_model", null=True, blank=True, on_delete=models.SET_NULL ) -
How to find what is the actual error in static? [closed]
I have included the following code in my Django project to display a background image, but I am encountering an error in the static part. I have already checked the STATIC_URL, STATIC_ROOT, and STATICFILES_DIRS settings and ensured that the about.jpg file is located in the correct directory. What else could be causing this error and how can I fix it?" <div class="home"> <div class="background_image" style="background-image:url({%static'images/about.jpg'%});" </div> </div> -
How to sort a queryset based on objects' foreign key by sorted method?
I'm happy with the instruction to do sorting: sorted(qs, key=lambda obj: obj.name.lower(), reverse=True) But as I need to sort the queryset by obj's foreign key's field. It looks invalid with: (Sort won't work! The order didn't change.) sorted(qs, key=lambda obj: obj.fkname.name.lower(), reverse=True) which fkname is the foreign key of the object. I don't want to do sorting like this: Course.objects.order_by("subject__name")[0].name # The course cls has a FK to Subject. Can this be possible? -
Djnago model 'signup' have the field 'username' but i got the error "signup given an unexcpected argument 'username' "signuo
i have a model signup in django which contains the fields username ,email,user but i got the error signup got an unexcpected argument "username" I tried to change the name of model and field but i got the same error -
Django Rest Framework Model Viewsets 'POST' method not appeared in ALLOW methods after explicitly allowing it
Fairly new to it but have after trying out many different solutions, I still get the following problem where the POST html form would not appear (and POST method not allowed) as seen below, all while using a root superuser model.py class Category(models.Model): category = models.CharField('category', max_length=100, null=False, blank=False, default="NA") def __str__(self) -> str: return self.category class Meta: verbose_name_plural = "categories" class Item(models.Model): name = models.CharField('name', max_length=64) slug = models.SlugField(max_length=64, null=True, blank=True) icon = models.ImageField(blank=True, upload_to ='uploads/') category = models.ForeignKey( Category, on_delete=models.CASCADE, default='Uncategorized') subcategory = models.CharField( max_length=255, null=True, blank=True) quantity = models.DecimalField( max_digits=9, decimal_places=2) suggested_value = models.DecimalField( max_digits=6, decimal_places=2, null=False) retail_value = models.DecimalField(max_digits=6, decimal_places=2,max_length=30) description = models.TextField('description', max_length=255, blank=True) created_at = models.DateTimeField(auto_now_add=True, db_index=True) tenant = models.TextField('tenant', default='shared') exclude = ('tenant') class Meta: # db_table = "storeItems_item" default_permissions = ('view','add', 'change', 'delete') ordering = ['name'] get_latest_by = 'created_at' def __str__(self): return self.name def get_absolute_url(self): return reverse( 'storeItems_item_detail', args=(), kwargs={'slug': self.slug}) def save(self, *args, **kwargs): # assign permission to item group = Group.objects.get(name=self.tenant) super(Item, self).save(*args, **kwargs) for perm in ['view_item', 'add_item','change_item']: assign_perm(perm, group, self) # Default retail value if not self.retail_value: self.retail_value = self.suggested_value() super().save(*args, **kwargs) Everything I've tried with configuring the viewset's permission: class StoreItemsViewSet( viewsets.ModelViewSet, PermissionListMixin, # viewsets.GenericViewSet, mixins.ListModelMixin, # … -
authenticate() takes from 0 to 1 positional arguments but 2 were given
I'm trying to submit this User model, but when I try to create a user, it throws me an error: authenticate() takes from 0 to 1 positional arguments, but 2 were given. While it throws this error, it successfully creates the user with no password when I check my admin How can I solve this problem? Models.py: class User(AbstractUser): username = models.CharField(max_length=70, unique=True) email = models.EmailField(unique=True) phone_number = models.CharField(max_length=15) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'phone_number', 'password'] def __str__(self): return "{}".format(self.email) Views.py: def create_user(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = form.save() authenticate(request, user) return redirect('Home') else: form = RegistrationForm() return render(request, 'register.html) Forms.py: class RegistrationForms(forms.Form): username = forms.CharField(label="Username", max_length=70, widget=forms.TextInput(attrs={'class':'form-control'})) first_name = forms.CharField(label="First Name", widget=forms.TextInput(attrs={'class':'form-control'})) last_name = forms.CharField(label="last Name", widget=forms.TextInput(attrs={'class':'form-control'})) email = forms.EmailField(label="School Email", widget=forms.EmailInput(attrs={'class':'form-control'})) phone_number = PhoneNumberField(label="School Phone Number", widget=forms.NumberInput(attrs={'class':'form-control'})) password = forms.CharField(label="Password", widget=forms.PasswordInput(attrs={'class':'form-control'})) repeat_password = forms.CharField(label="Repeat Password", widget=forms.PasswordInput(attrs={'class':'form-control'})) class Meta: model = User fields = ['username', 'password', 'email', 'first_name', 'last_name', 'phone_number', 'repeat_password'] -
Django upload many images to model field
I have project in django responsible for creating notes with optional adding images. Now I can add note with maximum one image. I want to allow user add as many images as want, but I don't know how. I tried using ArrayField in model field but it didn't worked. I want to be this way: when user click 'Add image' and explorer shows up he can choose more than one image. And then these images save to one model instance. For example if img field will be ArrayField in database will be: img = ['image1.jpg', 'image2.jpg', 'image3.jpg'], I don't want to create as many objects as there is images to upload. My model: class Note(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='note', null=True) title = models.CharField(max_length=200) note_text = models.TextField() add_date = models.DateTimeField('added date') img = models.ImageField(upload_to='images', blank=True) edit_dates = ArrayField( models.DateTimeField('edit dates', blank=True, null=True), default=list, ) def __str__(self): return self.title My form: class AddNewNote(forms.ModelForm): class Meta: model = Note fields = ['title', 'note_text', 'img', ] My view: class CreateNoteView(CreateView): model = Note template_name = 'notes/add_note.html' form_class = AddNewNote def get_success_url(self): return reverse('show', kwargs={'pk' : self.object.pk}) def form_valid(self, form): form.instance.add_date = timezone.now() form.instance.user = self.request.user return super(CreateNoteView, self).form_valid(form) and add_note.html: {% extends 'notes/base.html' … -
Django collectstatic erroring
I've got this collectstatic error since upgrading from Django 3.x to 4.y Traceback (most recent call last): File "manage.py", line 13, in <module> execute_from_command_line(sys.argv) File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 209, in handle collected = self.collect() File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 154, in collect raise processed File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/contrib/staticfiles/storage.py", line 338, in _post_process content = pattern.sub(converter, content) File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/contrib/staticfiles/storage.py", line 215, in converter hashed_url = self._url( File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/contrib/staticfiles/storage.py", line 152, in _url hashed_name = hashed_name_func(*args) File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/contrib/staticfiles/storage.py", line 388, in _stored_name cache_name = self.clean_name(self.hashed_name(name)) File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/contrib/staticfiles/storage.py", line 113, in hashed_name raise ValueError( ValueError: The file 'dist/vendor/bootstrap-select/js/i18n/defaults-ar_AR.js.map' could not be found with <core.storage.StaticStorage object at 0x7f7a3230e160>. I'm storing to S3 and here is my specific storage class class MediaStorage(S3Boto3Storage): """ This is our default storage backend for all media in the system. DEFAULT_FILE_STORAGE expects a class and not an instance """ def __init__(self, *args, **kwargs): kwargs.setdefault("file_overwrite", False) kwargs.setdefault("url_protocol", "https:") kwargs.setdefault("querystring_auth", False) kwargs.setdefault("location", get_storage_env("media")) kwargs.setdefault("default_acl", "public-read") kwargs.setdefault("object_parameters", {"CacheControl": "max-age=31536000"}) super(MediaStorage, self).__init__(*args, **kwargs) def _save_content(self, obj, content, parameters): """ We create a clone of the content file … -
Storing pdf / image or both files in database not in storage/folder in django
I want to store images and pdf files in the database directly and not in the folder storage, what field type should be given in models along with other information which will be stored in another table and files will be stored in another table of the database. and also how to retrieve those files and view file in later time. #django #fileupload tried looking for multiple resources which all were showing to store files in storage