Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Signals: Can't Use For Loop?
When i remove the for loop in the signals then it works (creates an object properly) but when i use the for loop it should create an object for each post in the Collection object but this doesn't work. It doesn't even create an object of the Collection_List_Item model. Is there a reason why this for loop doesn't work? Is there a way to work around this? models class Collection(models.Model): posts = models.ManyToManyField(Post, related_name='collection_posts', blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) collection_name = models.CharField(max_length=100) collection_description = models.CharField(max_length=1000, blank=True) collection_likes = models.ManyToManyField(User, related_name='liked_collections', blank=True) collection_image = models.ImageField(upload_to="images/") private = models.BooleanField(default=False) follows = models.ManyToManyField(User, related_name='collection_follows', blank=True) def __str__(self): return self.collection_name class Collection_List_Item(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) collection = models.ForeignKey(Collection, on_delete=models.CASCADE, null=True) saved = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return self.collection.collection_name signals: @receiver(post_save, sender=Collection) def create_collection_list_item(sender, instance, created, **kwargs): if created: for i in instance.posts.all(): collection_list_item = Collection_List_Item.objects.create(collection=instance, user=instance.author, post=i) collection_list_item.save() -
Performance issues with django-storages + CloudFront
I'm using S3 Buckets for static and media files of my Django app. I have AWS CloudFront "in front" of the Buckets and I have setup django-storages in order to use this CDN to serve me my files. However, my requests are taking too long. It is worth mentioning that I am using HyperlinkedModelSerializer and VersatileImageField. I would expect that my files were retrieved by the CDN but it looks like my app is using boto3 to actually download the files from S3 (and I think this is happening during serialization). Here's some information from cProfile: ncalls tottime percall cumtime percall filename:lineno(function) 174 0.004 0.000 17.172 0.099 /MyProjectPath/env/lib/python3.8/site-packages/storages/backends/s3boto3.py:515(exists) 61 0.003 0.000 16.586 0.272 /MyProjectPath/env/lib/python3.8/site-packages/boto3/s3/inject.py:723(object_download_fileobj) 61 0.001 0.000 16.582 0.272 /MyProjectPath/env/lib/python3.8/site-packages/boto3/s3/inject.py:624(download_fileobj) 62 0.003 0.000 57.723 0.931 /MyProjectPath/env/lib/python3.8/site-packages/rest_framework/serializers.py:507(to_representation) 62 0.000 0.000 57.687 0.930 /MyProjectPath/env/lib/python3.8/site-packages/versatileimagefield/serializers.py:53(to_representation) 62 0.000 0.000 57.687 0.930 /MyProjectPath/env/lib/python3.8/site-packages/versatileimagefield/serializers.py:42(to_native) 62 0.003 0.000 57.686 0.930 /MyProjectPath/env/lib/python3.8/site-packages/versatileimagefield/utils.py:220(build_versatileimagefield_url_set) I don't think the app should be contacting the S3 Buckets directly. Has anyone experienced this? Could this be a because of a misconfiguration or is there any known issue related to DRF/django-storages/VersatileImage that would affect performance this badly? -
How to create two type of users in a django website, re-writting authentication back end
So, this is how i am trying to create the two models: class UserManager(BaseUserManager): def create_user(self, email, username, year, branch, rollNo, password=None): if not email: raise ValueError("Users must have an email") if not username: raise ValueError("Users must have a username") if not year: raise ValueError("Users must specify an year") if not branch: raise ValueError("Users must specify a branch") if not rollNo: raise ValueError("Users must have a roll number") user = self.model( email=self.normalize_email(email), username=username, year=year, branch=branch, rollNo=rollNo ) user.set_password(password) user.save(using=self._db) return user def create_guest(self, username, college, year, email, password=None): if not username: raise ValueError("Please give a valid username") if not college: raise ValueError("Please provide your college") if not year: raise ValueError("Specify your year") if not email: raise ValueError("A valid email needs to be provided") user = self.model( email = self.normalize_email(email), username = username, year = year, college = college ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, year, branch, rollNo, password): user = self.model( email=self.normalize_email(email), username=username, year=year, branch=branch, rollNo=rollNo, password=password ) user.is_admin = True user.is_staff = True user.is_superuser = True user.set_password(password) user.save(using=self._db) return user class GuestUser(AbstractBaseUser): email = models.EmailField(unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date_joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last_login', auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) … -
How to use two different databases in Django? (SQLite and MongoDB)
For my project, I'm trying to set up two different databases in Django. These databases are SQLite and MongoDB. What I'm trying to do is I'm trying to hold user data in SQLite and for big data, I want to use MongoDB. After so many searches on the internet, I couldn't understand how to do it. I just did this little code in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': str(BASE_DIR / 'db.sqlite3'), }, 'bigdata_db' : { 'ENGINE' : 'mypackage.backends.mongodb', 'NAME' : 'bigdata_db', 'HOST' : '', } Please someone could help me. I'm really trying so hard to understand but it's so complicated for me. Also, in Django SQLite came already set up but here the main issue is how to set up MongoDB and connected two of them. -
Transmit a param into its validator and make migrations?
Django 3.1.7 I've transmitted a param to its validator: class RenderedCssFile(models.Model): char_pattern = r".*-\d+\.css$" file_name = models.CharField(max_length=255, verbose_name=gettext("File name (eg. main-1.css"), validators=[lambda value: GeneralValidator. validate_charfield_against_pattern( value, RenderedCssFile.char_pattern), ], ) I was very glad. But only before migrations were made: Migrations for 'staticassets': staticassets/migrations/0001_initial.py - Create model RenderedCssFile - Create model PhpFile - Create model JsFile - Create model CssFile Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 182, in handle self.write_migration_files(changes) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 219, in write_migration_files migration_string = writer.as_string() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/migrations/writer.py", line 141, in as_string operation_string, operation_imports = OperationWriter(operation).serialize() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/migrations/writer.py", line 99, in serialize _write(arg_name, arg_value) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/migrations/writer.py", line 51, in _write arg_string, arg_imports = MigrationWriter.serialize(item) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/migrations/writer.py", line 271, in serialize return serializer_factory(value).serialize() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/migrations/serializer.py", line 37, in serialize item_string, item_imports = serializer_factory(item).serialize() File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/migrations/serializer.py", line 199, in serialize return self.serialize_deconstructed(path, args, kwargs) File "/home/michael/PycharmProjects/ads6/venv/lib/python3.8/site-packages/django/db/migrations/serializer.py", line 86, in serialize_deconstructed arg_string, arg_imports … -
Can I control how often the pre-ping connection check is done in SqlAlchemy connection pooling?
Environment / usage case info I have a SqlAlchemy django-postgrespool2 connection pool used to connect to a PostgreSQL database. Problem I'm considering using the pre-ping feature in my SqlAlchemy connection pool. However, I read that the pre-ping check is done for every pool connection checkout. I have done some tests, to me this checkout seems to occur for every SQL command I send to the database. I'm concerned all those pre-ping checks will cause a big overhead/delay if the check is made for every SQL command sent to the database. Question Is there a way to configure how often or after what time the pre-ping check should be made? Or do I have to implement my own solution to customize how often the connection is checked? How? Thanks! -
How should I develop the front-end? (help!) [closed]
So basically I have this idea for a web application where users can upload 'posts' which than will be upload to the 'feed'. So pretty much like all forums, social media applications, etc. Just like for example Reddit, I want the user to have specific options in de 'make-a-post-template' that he/she can fill in. It's a pretty complicated concept if I go in the dept of it, but my real question here is: How should I develop the front-end? Here are some key-points that I take in for the decision: I have never used a front-end framework before (basic knowledge of Javascript). But I'm willing to learn if there is much benefit to gain from it. It's going to be a forum website like Reddit, but for a specific audience. I want to use Django Please help me out here, I'm worried that if I don't use a front-end framework, that the speed of the website will dramatically decrease, and because I'm using diffrent content blocks, to create a 'dashboard' kind of style, that something like React will be very suitable for this. Take a look at the images to get some idea of how it's going to work and … -
How to use existing mysql DB along with its migrations in sql, in the Django? What changes will need to do in the django for using the mysql db?
I am already having one mysql database with a lot of data, of which tables and migrations are written in sql. Now I want to use the same mysql database in django so that I can use the data in that database.I am expecting that there will not be need for making the migrations as I am not going to write the models in Django again, also what will be the changes/modification I will have to do. For eg: as in middlewares?. Can anyone please help me in this? -
Asynchronous computation and save in django 3 models
I have a problem making part of my models asynchronous in Django 3. This is my models.py: class ModelImages(models.Model): case = models.ForeignKey(Case, on_delete=models.CASCADE, related_name="slice_img") img = models.ImageField(editable=False) #other def get_slices(instance): # operations return images_array_list def process_3d_image(sender, instance, created, **kwargs): if created: imgs = get_slices(instance) for img in imgs: # other operations case_img = ModelImages(case=instance, img=name) with transaction.atomic(): case_img.save() post_save.connect(process_3d_image, sender=Case) The code is longer but I reported only the crucial parts. It works correctly but I want to make 'process_3d_image' function asynchronous. I tried Celery, Trio, and others without any result. How could I do it? -
Docker containing a Django application a not saving database after stopping container
I have build a Django application with SQLite database. The database is reinitialized and migrated every time the container is started using docker-compose up losing all the previous data. It also not creating db or any other files. Using the latest version of docker. -
How to display a list of posts in a list of categories in Django
I am looking for my web page to display a list of categories and a list of each post within the category. For example: However, it is looping through and displaying each category and associated post separately, like this: Here is Template: <ul> {% for p in object_list %} <li> {{p.category.name}} <ul> <li> {{p.title}} </li> </ul> </li> {% endfor %} </ul> Model class Category(models.Model): name = models.CharField(max_length=200, blank=True, null=True) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category', null=False) Views class CategoryList(ListView): template_name = 'category_list.html' def get_queryset(self): return Post.objects.all().select_related('category') -
Overriding get() method in Django UpdateView gives 'str' has no attribute get error
I have a Stats model which is related to Django User model with a OneToOne Field. I have an UpdateView: class StatsUpdateView(UpdateView): model = Stats fields = ('stat1', 'stat2', 'stat3') It works fine, but any User is allowed to modify the Stats related to any User, I want a User to onlyupdate the Stats related to him. So I override the get() method in StatsUpdateView like this: def get(self, *args, **kwargs): if self.request.user != Stats.objects.get(pk=kwargs['pk']).user: #checks if the user logged in is the same user related to the Stats with the onetoone field. Works fine. return redirect('homepage:home') else: # if the user match, he can access the update view for his own stats print('user match') return reverse('user:updatestats', kwargs={'pk': kwargs['pk']}) The code runs fine until the else statement, 'user match' gets printed into the console but I get this error while running the server: 'str' object has no attribute 'get' Here's the path: path('updatestats/<int:pk>/', StatisticheUpdateView.as_view(), name='updatestats') -
Logging Output for Session on Webclient
I'm using Django to deploy some of my calculations-modules and allow registered and unregistered users to make use of them. Now I happen so see on the serverlogs sometimes invalid files are uploaded and during the process I'm able to fix it to some degree. These calculation-modules are separated from the Django-Project, but still on the same server. My first thought would be to pass on logging-variables through them and return them in the end of the calculation in the server response. This seems to be a dirty and rather invasive solution as everything is basically protocolled with with the basic logging. Any of my methods would with that get an additional logging-variable. Apparently Output log file through Ajax in Django seems to somewhat fit to what I am looking for but this appears only to show the full logs and not by session (given the case one user has two sessions). The modules in the backend don't have any session-ID, but it wouldn't be too difficult to add it just in the constructors. The Ajax-Module on the Client doesn't seem to be the problem (plenty of sources, like: Django - How to show messages under ajax function), but how … -
Django static files not updating inside docker container
My Django project uses Docker, gunicorn, and whitenoise. I recently altered settings to prepare for deployment, most notably adding configurations for AWS-hosted media files. Now when I run the project locally and collectstatic the static files do not update in the browser. I do, however, see the changes where static files are collected. Things I've tried/double checked: Ensuring I have a shared volume between the container and where static files are kept/updated Adding a step to collectstatic in my Dockerfile Confirming my static files settings Is something about django-storages causing the issue? I thought that previously I was able to make SCSS changes and have them show up by refreshing the browser. But that's not happening. Even running collectstatic inside the container has no effect. # relevant settings.py INSTALLED_APPS = [ ... "whitenoise.runserver_nostatic", "storages", ... ] MIDDLEWARE = [ "django.middleware.cache.UpdateCacheMiddleware", "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", ... ] # AWS config (use in production only) USE_S3 = env.bool("USE_S3", default=not DEBUG) if USE_S3: AWS_ACCESS_KEY_ID = env.str("AWS_ACCESS_KEY_ID", default="") AWS_SECRET_ACCESS_KEY = env.str("AWS_SECRET_ACCESS_KEY", default="") AWS_STORAGE_BUCKET_NAME = env.str("AWS_STORAGE_BUCKET_NAME", default="") AWS_DEFAULT_ACL = None AWS_S3_REGION_NAME = env.str("AWS_S3_REGION_NAME", default="us-east-2") AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } # S3 Public Media Settings PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' # … -
Django_tables2 + django_filter, edit template of table, reload after POST
I am using django_tables2 and django_filter in my website. I use standard template bootstrap.html but slightly modified. The problem is i can not use 'querystring' or 'render_attrs' anywhere. When I use simply: {% render_table table %} everything works fine. Also when I only display data, it works. Here's my html and the code. First of all, code that works: (home.html) {% if filter %} <form action="" method="get" class="form form-inline"> {% bootstrap_form filter.form layout='inline' %} {% bootstrap_button 'filter' %} </form> {% endif %} {% block table-wrapper %} <div class="table-container"> {% block table %} <table class="table table-bordered table-hover w-100 shadow-lg p-3 mb-5 bg-white"> {% block table.thead %} {% if table.show_header %} <thead class="table-dark" {{ table.attrs.thead.as_html }}> <tr> {% for column in table.columns %} <th {{ column.attrs.th.as_html }}>{{ column.header }}</th> {% endfor %} <th style="width:11%">Akcja</th> </tr> </thead> {% endif %} {% endblock table.thead %} {% block table.tbody %} <tbody {{ table.attrs.tbody.as_html }}> {% for row in table.paginated_rows %} {% block table.tbody.row %} <form method="post" action="."> {% csrf_token %} {% for column, cell in row.items %} <td {{ column.attrs.td.as_html }}> {{ cell }} </td> {% endfor %} <td> {% if row.record.zam_status == 0 %} <button type="submit" name="zatwierdz_zam" value ={{row.record.pk}} class="btn btn-dark btn-sm">Zatwierdź</button> <button type="submit" … -
using React JS components in django teamplates though static files (hybrid model) - what's wrong? (newbie JS/React question)
I am new to JS/React/npm/webpack, and fairly new to Django. I am trying to build search experience (i.e. front-end) for my existing Django web application, and I am planning to use elastic/search-ui components for that. I did some research (How to get Django and ReactJS to work together?) and I am following the hybrid model guide (https://www.saaspegasus.com/guides/modern-javascript-for-django-developers/integrating-javascript-pipeline/) where static JS files are used in Django templates. I got to the point where I could display some text from JS script in Django template, now I am trying to display imported JS component and I got stuck. This is my code: package.json: ... "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "dev": "webpack --mode development" }, ... "devDependencies": { "@elastic/search-ui": "^1.5.1", "babel": "^6.23.0", "babel-loader": "^8.1.0", "react": "^17.0.1", "react-dom": "^17.0.1", "react-scripts": "^4.0.3", "webpack": "^5.26.3", "webpack-cli": "^4.5.0" } webpack.config.js: const path = require('path'); module.exports = { entry: './ui-react-src/index.js', // path to our input file output: { filename: 'index-bundle.js', // output bundle file name path: path.resolve(__dirname, './reviewer/static/ui-react-build'), // path to our Django static directory }, }; django html template I want to load React components to: {% extends "base_generic.html" %} {% block content %} Test React component <hr> {% load static … -
Django _set.all() filter in QuerySet
I have database and I want to extract specific data of specific user from queryset. Now i have this VIEW def index(request): customerByName = Customer.objects.get(name='pablo') shopListById = ShopList.objects.get(transaction_id=1) shpoListSpecific = customerByName.shoplist_set.all() specificProducts = shopListById.shoplistproduct_set.all() context = {'customerByName':customerByName, 'shpoListSpecific':shpoListSpecific, 'shopListById':shopListById, 'specificProducts': specificProducts} return render(request, 'QuickShopperApp/home.html', context) MODELS class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True, blank=True) email = models.CharField(max_length=200, null=True, blank=True) device = models.CharField(max_length=200, null=True, blank=True) def __str__(self): if self.name: name = self.name else: name = self.device return str(name) class Product(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class ShopList(models.Model): # cart customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) #product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) class ShopListProduct(models.Model): # each ShopList will have multiple ShopListProduct product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) shopList = models.ForeignKey(ShopList, on_delete=models.SET_NULL, null=True) #shoplistitem.shoplist quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.product) template.html <h3>specificProducts: {{specificProducts}}</h3> On my side i see items of specific customer. specificProducts: <QuerySet [<ShopListProduct: Apple>, <ShopListProduct: Cucumber>, <ShopListProduct: Cucumber>]> How can i get only Apple, Cucumber, Cucumber? -
How do I run Lighthouse CLI during tests in Django?
I would like to run Lighthouse CLI during tests in Django. By default, Django tests don't run a server that can respond to HTTP requests, so this is not possible. How can I run Lighthouse CLI during Django tests? -
Elastic Beanstalk: ModuleNotFoundError: No module named 'OpenSSL'
When deploying my app to Elastic Beanstalk it keep returning the error ModuleNotFoundError: No module named 'OpenSSL' when it is installing the python secrets module. I had the same error on my local machine and installed PyOpenSSL to resolve it. I however keep getting this error in elastic beanstalk despite installing PyOpenSSL first in my requirements.txt file .. error log 2021/03/19 11:37:57.559862 [INFO] Collecting pyOpenSSL Using cached pyOpenSSL-20.0.1-py2.py3-none-any.whl (54 kB) Collecting freezegun==1.1.0 Using cached freezegun-1.1.0-py2.py3-none-any.whl (16 kB) Collecting pytest==6.2.2 Using cached pytest-6.2.2-py3-none-any.whl (280 kB) Collecting secrets Using cached secrets-1.0.2.tar.gz (7.9 kB) 2021/03/19 11:37:57.559967 [ERROR] An error occurred during execution of command [app-deploy] - [InstallDependency]. Stop running the command. Error: fail to install dependencies with requirements.txt file with error Command /bin/sh -c /var/app/venv/staging-LQM1lest/bin/pip install -r requirements.txt failed with error exit status 1. Stderr: ERROR: Command errored out with exit status 1: command: /var/app/venv/staging-LQM1lest/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-t7gr8k3l/secrets_09ec5a31c91b4f23a5c5a182f4962855/setup.py'"'"'; __file__='"'"'/tmp/pip-install-t7gr8k3l/secrets_09ec5a31c91b4f23a5c5a182f4962855/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-azo2b_35 cwd: /tmp/pip-install-t7gr8k3l/secrets_09ec5a31c91b4f23a5c5a182f4962855/ Complete output (12 lines): Traceback (most recent call last): File "/tmp/pip-install-t7gr8k3l/secrets_09ec5a31c91b4f23a5c5a182f4962855/setup.py", line 10, in <module> import OpenSSL ModuleNotFoundError: No module named 'OpenSSL' requirements.txt pyOpenSSL freezegun pytest secrets -
Custom field in Django ArrayField throws an error
PROBLEM I have CustomField nested in ArrayField. CustomField itself works well, also migrations throw no error. When I try to save MyModel(code=[StandardCode(...), ...]), why I get the following error: TypeError: asdict() should be called on dataclass instances I know that for some reason django tries to call my DataClassField get_prep_value() with value=[StandardCode(...), ...] Why that happens? How could this behaviour got fixed? FIELD DEFINITION class DataClassField(models.CharField): description = "Map python dataclasses to model." def __init__(self, dataClass, *args, **kwargs): self.dataClass = dataClass kwargs['max_length'] = 1024 super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() kwargs['dataClass'] = self.dataClass return name, path, args, kwargs def from_db_value(self, value, expression, connection): if value is None: return value obj = json.loads(value) return from_dict(data_class=self.dataClass, data=obj) def to_python(self, value): if isinstance(value, self.dataClass): return value if value is None: return value obj = json.loads(value) return from_dict(data_class=self.dataClass, data=obj) def get_prep_value(self, value): try: if value is None: return value return json.dumps(asdict(value)) except Exception as e: print(value) raise e DATACLASS DEFINITION: @dataclass class StandardCode: code: str codeSystem: str displayName: str MODEL DEFINITION from django.contrib.postgres.fields import ArrayField class MyModel code = ArrayField(DataClassField(dataClass=StandardCode, null=True), size=2, default=list) -
How to send csrf token in xmlHttpRequest?
Using Ajax or xmlHttpRequest I want to download excel file from django backend. Backend creates file in memory and returns it to user. According to this answer I should use for this xmlHttpRequest, but there is no info how to set csrf middleware token in post request. I tried: To set request.setRequestHeader like this: request.setRequestHeader('x-csrf-token, window.CSRF_TOKEN) - token is missing and in data: request.send({'csrfmiddlewaretoken': window.CSRF_TOKEN, 'req': 'ExportAllMessages'}); I can't find any working solution with Ajax. -
How to have different expiry times for Web and Mobile Apps in Django simple jwt?
I am currently using Django Rest Framework to serve a React JS application, but recently, we are adding support for a React Native application as well. Now, as I use Django Simple jwt, here's the code for the expiry of the refresh and access tokens: settings.py ACCESS_TOKEN_LIFETIME = datetime.timedelta(hours=2) REFRESH_TOKEN_LIFETIME = datetime.timedelta(days=3) SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': ACCESS_TOKEN_LIFETIME, 'REFRESH_TOKEN_LIFETIME': REFRESH_TOKEN_LIFETIME, ... } While this works really well on web, I do not want the phone app users to have to get logged out automatically every 3 days. Is there a way to alter the refresh token lifetime based on the device that is asking for the tokens? If yes, how? -
Django Signals: How To Create Objects On Object Creation
I am trying to create an object on another model's object creation but i dont know what to put in the function save_collection_list_item to make this work. I am getting the error: 'Collection' object has no attribute 'collection_list_item' so what should i replace it with? models: class Collection(models.Model): posts = models.ManyToManyField(Post, related_name='collection_posts', blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) collection_name = models.CharField(max_length=100) collection_description = models.CharField(max_length=1000, blank=True) collection_likes = models.ManyToManyField(User, related_name='liked_collections', blank=True) collection_image = models.ImageField(upload_to="images/") private = models.BooleanField(default=False) follows = models.ManyToManyField(User, related_name='collection_follows', blank=True) def __str__(self): return self.collection_name class Collection_List_Item(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) collection = models.ForeignKey(Collection, on_delete=models.CASCADE, null=True) saved = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) def __str__(self): return self.collection.collection_name signals: @receiver(post_save, sender=Collection) def create_collection_list_item(sender, instance, created, **kwargs): if created: #collection_list_item = Collection_List_Item.objects.create(collection=instance, user=instance.author) Collection_List_Item.objects.create(collection=instance, user=instance.author) @receiver(post_save, sender=Collection) def save_collection_list_item(sender, instance, **kwargs): instance.collection_list_item.save() # What should i change this to? -
Django how to get model values inside another model?
I want the value of username from forms that I get as a string so that when I upload an image it is stored in a subdirectory with that username. i.e. if 'bob' registers the image should be saved in 'static/auth_image/bob/image_name.extension'. Also if I could it during the registration form filling that would be great. models.py class User_data(models.Model): username = models.CharField(max_length=256, null=True, blank=True) email = models.EmailField(max_length=254, null=True, blank=True) four_digit_pass = models.CharField(max_length=256, null=True, blank=True) private_key = models.CharField(max_length=256, null=True, blank=True) profile_pic = models.ImageField(upload_to='static/profilepic', null=True) def getUsername(self): return self.username def __str__(self): return str(self.username) class AuthImages(models.Model): owner = models.ForeignKey('User_data', null=True, on_delete=models.CASCADE) uname=owner. def save_auth_image(self): uname = self.username self.auth_image_file = models.ImageField( upload_to='static/auth_image/%s' % uname, null=True) forms.py class RegistrationForm(forms.ModelForm): four_digit_pass = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User_data fields = ['username', 'email', 'four_digit_pass', 'profile_pic', 'private_key'] register.html {% extends "storage_app/base.html" %} {% block body_block %} <div class="jumbotron"> <h1>Register Page</h1> </div> <div> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <p>Private Key should not be changed or shared with anyone</p> <button type="submit">Upload</button> </form> </div> {% endblock body_block %} here in HTML, i want to take input for the second i.e. auth_image directly from webcam if possible This is my first question also I am new to Django so … -
After adding custom validation in AUTH_PASSWORD_VALIDATORS django admin change password removes password1 field
After adding custom validation in AUTH_PASSWORD_VALIDATORS django admin change password removes password1 field.