Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change Django to use EmailMultiAlternatives instead of send_mail() by default (all-auth)
So I am using django-all-auth for my authentication and using its in-built functionality for mailing reset passwords, confirmations of registration, etc. I have designed templates that include images. For the regular emails, I am explicitly using functions that use EmailMultiAlternatives instead of send_mail() since that allows inline images and background images. Django-all-auth however automatically uses send_mail() and my emails are arriving with the images missing. How can I override it so it uses EmailMultiAlternatives? -
Collapsed field in Django Admin's change view
The table Content has a field compressed_string that stores a very long string in the compressed form. This is what I have to display the original decompressed string in the Django Admin's change view: class ContentAdmin(admin.ModelAdmin): fields = ( [f.name for f in Content._meta.fields if f.name not in ['compressed_string']] + ['original_string']) readonly_fields = ['original_string'] list_display = [f.name for f in Content._meta.fields] def original_string(self, obj): return pickle.loads(brotli.decompress(obj.compressed_string)) I would like original_string to be displayed collapsed, with the possibility to expand and view the whole string. How can I accomplish this? -
I am getting "NoReverseMatch" error for my 'results' page
I am creating a quiz website. After the user answers all the questions he is redirected to the results page. But if he clicks the back button in Chrome he goes back to the questions in the quiz. But since the quiz is submitted i don't want him to go there. Instead It should redirect him into the home page where a list of all quizzes is available. So in the templates of the results page I included the following JavaScript code. <script> window.onload = function() { // Check if the referring URL matches the results page URL console.log('Referrer:', document.referrer); var expectedReferringURL = '{% url "quizquestions" %}'; // Check if the referring URL contains the expected URL pattern name if (document.referrer.includes(expectedReferringURL)) { // Replace the current history entry with the home page URL window.history.replaceState(null, null, '{% url "quizlist" %}'); } }; </script> The url pattern of the name "quizquestions" is path('quizzes/<int:quiz_id>/question/<int:question_id>',user_views.quizquestions,name='quizquestions') But when I go to the results page it shows this error Reverse for 'quizquestions' with no arguments not found. 1 pattern(s) tried: ['quizzes/(?P<quiz_id>[0-9]+)/question/(?P<question_id>[0-9]+)\\Z'] Any thoughts on why is this happening? -
Update Django via settings to new domain
I'm new to Django and nginx. I have built a default Django app and my setup uses a nginx server as a reverse proxy. My application was previously reached via https://myapplication.intranet and every internal link referred to this link (e.g. href "/" points to "https://myapplication.intranet/" and href points to "/test" "https://myapplication.intranet/test") - so everything worked. Now nginx changed the domain link to "https://myapplication.intranet/new/", and everything broke: redirect (e.g. in view.py) href (in html templates. For example href "/test" incorrectly points to "https://myapplication.intranet/test" instead of "https://myapplication.intranet/new/test") css sheets not found My question is the following: What adjustments have to be made (for Django) in order to make the application work again? Is there an easier (and more general) way than rewriting all links in all files to make the urls specific? Thank you very much. -
Invoke Django reload manually
I would like to force a reload of Django similar to when Django reloads after a file has changed. e.g. Watching for file changes with StatReloader This answer has the desired result but it involves a reload on "file changing": https://stackoverflow.com/a/43593959/12446456 However, I would specifically like to invoke the reload behaviour manually after a get request has been handled by Django. -
Basic Django image runs locally but fail inside Kubernetes?
I created a bare minimal Django project using django-admin startproject I then dockerized it using the following Dockerfile FROM python:3 ENV PYTHONUNBUFFRED=1 COPY . . RUN pip install -r requirements.txt EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] I built and pushed the image to ACR. I am able to run it locally using docker run -p 8000:8000 <image_name> and I am able access the site at localhost:8000. However, when I try to deploy it inside a Kubernetes deployment with the following yml file, it just crashed and restart over and over. apiVersion: apps/v1 kind: Deployment metadata: name: demodjango-deployment labels: app: demodjango spec: replicas: 1 selector: matchLabels: app: demodjango template: metadata: labels: app: demodjango spec: containers: - name: demodjango image: djangonba.azurecr.io/demodjango:latest imagePullPolicy: "Always" ports: - containerPort: 8000 --- apiVersion: v1 kind: Service metadata: name: demodjango-service spec: type: LoadBalancer selector: app: demodjango ports: - protocol: TCP port: 8000 targetPort: 8000 I am unable to access the page through the external IP address of the service demodjango-service either even at time where it somehow didn't crash. I already made the following modification ALLOWED_HOSTS = ['*'] I believe there is something fundamentally wrong with my approach? Can anyone tell me theoretically why it works … -
How can i raise a message error when introducing the same company and username
Hi guys I'm creating a django form I'm introducing companies and users to create a license, I would like that you cannot register the same user with the same company class UserForm(forms.Form): """User form model.""" company = forms.ModelChoiceField( queryset=models.CompanyInfo.objects.all(), empty_label=None, error_messages={"required": "Please enter customer company."}, ) user_name = forms.CharField( error_messages={"required": "Please enter username."}, empty_label=None, ) full_name = forms.CharField( error_messages={"required": "Please enter customer full name."} ) email = forms.EmailField(required=True) I would like to create the validaton here, I've been trying to use "unique" direct to de field in the form but i noticed i cannot use it, how can i create that kind of validation directly in the form? -
How to solve django.db.utils.OperationalError: (1060, "Duplicate column name 'country_id'")
I was trying to delete some of the fields of my model and I tried to migrate them, but I got the error: Operations to perform: Apply all migrations: admin, auth, contenttypes, leads, order, sessions Running migrations: Applying leads.0023_auto_20230823_0043...Traceback (most recent call last): File "/web/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/web/.local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 74, in execute return self.cursor.execute(query, args) File "/web/.local/lib/python3.6/site-packages/pymysql/cursors.py", line 148, in execute result = self._query(query) File "/web/.local/lib/python3.6/site-packages/pymysql/cursors.py", line 310, in _query conn.query(q) File "/web/.local/lib/python3.6/site-packages/pymysql/connections.py", line 548, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/web/.local/lib/python3.6/site-packages/pymysql/connections.py", line 775, in _read_query_result result.read() File "/web/.local/lib/python3.6/site-packages/pymysql/connections.py", line 1156, in read first_packet = self.connection._read_packet() File "/web/.local/lib/python3.6/site-packages/pymysql/connections.py", line 725, in _read_packet packet.raise_for_error() File "/web/.local/lib/python3.6/site-packages/pymysql/protocol.py", line 221, in raise_for_error err.raise_mysql_exception(self._data) File "/web/.local/lib/python3.6/site-packages/pymysql/err.py", line 143, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.OperationalError: (1060, "Duplicate column name 'country_id'") The above exception was the direct cause of the following exception: 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 "/web/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/web/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/web/.local/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/web/.local/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/web/.local/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res … -
Django ModelForm: how do I pre-populate data for a ModelForm overriding a field's widget? (Some working, some not.)
I have a model form with a number of fields that need to use widgets other than the default widget for the model data type. Loading the update form before adding custom widgets, all the data pre-populates for the current object correctly. As soon as I add a custom widget for any field, the pre-population for that field breaks. For example, this works as expected: class ChecklistForm(forms.ModelForm): class Meta: model = Checklist fields = [ "expected_time", #TimeField "completed", #BooleanField, nullable ] But I want control over the widgets used. I'd like the boolean completed field to render as a checkbox even though it is nullable, so I add: class ChecklistForm(forms.ModelForm): class Meta: model = Checklist fields = [ "expected_time", #TimeField "completed", #BooleanField, nullable "date", #DateField ] widgets = { 'expected_time': forms.TimeInput(format='%H:%M',attrs={'type': 'time'}), 'completed': forms.CheckboxInput(), 'date': forms.DateInput(format=('%m/%d/%Y'), attrs={'placeholder':'Select a date', 'type':'date'}), } When I load an update form, completed pre-populates correctly, while expected_time and date do not. Why? And is there a way to pre-populate these fields automatically? -
Memory never releases on Heroku, slow memory leak from models in Django?
I have been troubleshooting memory leak issues on my Django application deployed to Heroku. Basically, when the app is deployed/dyno restarted RAM hovers around 40% then as soon as someone gets on, it goes to 80% usage then stays there and never goes back down. Here is a screenshot of my last 24 hours: Things I have tried: Caching expensive things that are called often (using @cached_property), like checking a users subscription that is tied to their organization. Optimizing my queries, so far the biggest queryset I bring back is ~20 rows and isn't particularly big. Ran a memory profiler (pympler) that has a tab on Django Debug Toolbar. Admittedly am unsure of what I am looking at. Lowered gunicorn workers to 2 instead of 4 Checked that database connections weren't going haywire (currently 2 connections) Some other ideas of what it could be but unsure how to properly troubleshoot: I have middleware where I check for a subscription that runs on most pages, could this be somehow leaking/storing data? If I hit a 3rd party API (which isn't that often in this app) do I have to actively run del to get it out of memory? Has anyone else … -
How to remove `b'\x80\x05\x95\x08\...` from the contents of cache in Django?
I set 4 cache values with LocMemCache as shown below: from django.core.cache import cache cache.set("first_name", "John") cache.set("last_name", "Smith", version=2) cache.set("age", 36, version=3) cache.set("gender", "Male") Then, I tried to see the contents of the cache with cache._cache as shown below: from django.core.cache import cache print(cache._cache) # Here But, each key's value contains b'\x80\x05\x95\x08\... as shown below: OrderedDict([(':1:gender', b'\x80\x05\x95\x08\x00\x00\x00\x00\x00\x00\x00\x8c\x04Male\x94.'), (':3:age', b'\x80\x05K$.'), (':2:last_name', b'\x80\x05\x95\t\x00\x00\x00\x00\x00\x00\x00\x8c\x05Smith\x94.'), (':1:first_name', b'\x80\x05\x95\x08\x00\x00\x00\x00\x00\x00\x00\x8c\x04John\x94.')]) And, I tried to see the contents of the cache with cache._cache.items() as shown below: from django.core.cache import cache print(cache._cache.items()) # Here But again, each key's value contains b'\x80\x05\x95\x08\... as shown below: odict_items([(':1:gender', b'\x80\x05\x95\x08\x00\x00\x00\x00\x00\x00\x00\x8c\x04Male\x94.'), (':3:age', b'\x80\x05K$.'), (':2:last_name', b'\x80\x05\x95\t\x00\x00\x00\x00\x00\x00\x00\x8c\x05Smith\x94.'), (':1:first_name', b'\x80\x05\x95\x08\x00\x00\x00\x00\x00\x00\x00\x8c\x04John\x94.')]) Lastly, I tried to see the contents of the cache with locmem._caches as shown below: from django.core.cache.backends import locmem print(locmem._caches) # Here But again, each key's value contains b'\x80\x05\x95\x08\... as shown below: {'': OrderedDict([(':1:gender', b'\x80\x05\x95\x08\x00\x00\x00\x00\x00\x00\x00\x8c\x04Male\x94.'), (':3:age', b'\x80\x05K$.'), (':2:last_name', b'\x80\x05\x95\t\x00\x00\x00\x00\x00\x00\x00\x8c\x05Smith\x94.'), (':1:first_name', b'\x80\x05\x95\x08\x00\x00\x00\x00\x00\x00\x00\x8c\x04John\x94.')])} My questions: How can I remove b'\x80\x05\x95\x08\... from the contents of the cache? What is b'\x80\x05\x95\x08\...? -
Django admin: displaying computed property when viewing a single item
I store compressed strings in the database. I would like to see the actual string when in Django Admin. Since the strings are very long, I don't want them to appear in the list view, but only when viewing a single item (row). So, I can define: @property def short_my_field(self): return pickle.loads(brotly.decompress(self.my_field))[:80] @property def original_my_field(self): return pickle.loads(brotly.decompress(self.my_field)) I will then put short_my_field into list_display. But how do I cause original_my_field to display when viewing a single item? -
Got an lint error while running a dockerised project on github actions
I don't understand the error and I tried any times (https://i.stack.imgur.com/xNs3G.png) Here is my setup for github actions: --- name: Checks on: [push] jobs: test-lint: name: Test and Lint runs-on: ubuntu-20.04 steps: - name: Checkout uses: actions/checkout@v2 - name: Test run: docker-compose run --rm app sh -c "python manage.py wait_for_db && python manage.py test" - name: Lint run: docker-compose run --rm app sh -c "flake8" -
How to display the chapters of the Bible from django-bible package?
I'm trying to display the chapters of the bible from the bible package available here https://github.com/davisd/django-bible. Some of the codes are deprecated and I have refactored some. Now, I have the JSON file of the bible loaded in my database. I'm also able to display a list of the books of the Bible. The problem I'm facing is how to display the chapters of each book from my database. I have tried the following: models.py from django.db import models from .managers import BookManager class Book(models.Model): """ Book of the Bible """ number = models.PositiveIntegerField(primary_key=True, unique=True, db_index=True) slug = models.SlugField(unique=True) name = models.CharField(max_length=64, db_index=True) is_new_testament = models.BooleanField() objects = BookManager() def get_absolute_url(self): """ Returns the absolute url """ return reverse('book_detail', [self.slug,]) def __unicode__(self): return self.name class Meta: ordering = ['number',] class Chapter(models.Model): """ Chapter of the Bible """ book = models.ForeignKey(Book, related_name='chapters', on_delete=models.CASCADE) number = models.PositiveIntegerField(db_index=True) def __unicode__(self): return '%s %s' % (self.book.name, self.number) def get_next_chapter(self): try: return Chapter.objects.filter( book=self.book,number__gt=self.number).order_by( 'number')[0] except IndexError: return None def get_previous_chapter(self): try: return Chapter.objects.filter( book=self.book,number__lt=self.number).order_by( '-number')[0] except IndexError: return None def get_absolute_url(self): """ Returns the absolute url """ return reverse('chapter_detail', [self.book.slug, self.number]) class Meta: ordering = ['number',] unique_together=(('book','number',),) views.py from django.http import HttpResponse, Http404 from … -
Python Libraries (Twisted, regex, cryptography, hiredis)
These are all the libraries I used in my project. aioredis==1.3.1 alabaster==0.7.12 amqp==2.6.0 appdirs==1.4.4 Arpeggio==1.9.2 asgi-redis==1.4.3 asgiref==3.2.7 async-timeout==3.0.1 atomicwrites==1.4.1 attrs==19.3.0 autobahn==20.4.3 autoflake==1.3.1 Automat==20.2.0 autopep8==1.5.2 Babel==2.8.0 backcall==0.2.0 backports.shutil-get-terminal-size==1.0.0 bandit==1.6.2 billiard==3.6.3.0 black==19.10b0 bleach==3.1.5 boto3==1.17.0 botocore==1.20.0 bumpversion==0.5.3 celery==4.4.5 certifi==2020.4.5.2 cffi==1.15.1 channels==2.4.0 channels-redis==2.4.2 chardet==3.0.4 Click==7.0 colorama==0.4.6 colour==0.1.5 constantly==15.1.0 coverage==5.0.3 coveralls==1.10.0 cryptography==41.0.3 daphne==2.5.0 decorator==4.4.2 distlib==0.3.0 Django==3.0.7 django-admin-inline-paginator==0.3.0 django-admin-logs==1.0.1 django-admin-sortable2==0.7.6 django-ckeditor==5.9.0 django-cors-headers==3.11.0 django-debug-toolbar==2.2 django-dotenv==1.4.2 django-environ==0.4.5 django-fernet-fields==0.6 django-impersonate==1.9.1 django-js-asset==1.2.2 django-mapper==1.1.11 django-modelclone==0.7.1 django-mysql==3.7.1 django-pagination-bootstrap==2.3.0 django-redis==5.2.0 django-safedelete==1.0.0 django-silk==4.1.0 django-slack==5.17.6 django-solo==1.1.3 django-storages==1.11.1 djangorestframework==3.12.1 doc8==0.8.0 docopt==0.6.2 docutils==0.15.2 docxcompose==1.4.0 docxtpl==0.16.5 EasyProcess==0.3 entrypoint2==0.2.1 entrypoints==0.3 enum34==1.1.10 et-xmlfile==1.0.1 filelock==3.0.12 flake8==3.7.9 flake8-2020==1.5.0 flake8-bandit==2.1.2 flake8-broken-line==0.1.1 flake8-bugbear==20.1.4 flake8-builtins==1.4.2 flake8-comprehensions==3.2.2 flake8-debugger==3.2.1 flake8-fixme==1.1.1 flake8-isort==2.8.0 flake8-logging-format==0.6.0 flake8-mutable==1.2.0 flake8-polyfill==1.0.2 flake8-variables-names==0.0.3 flower==0.9.7 future==0.18.2 gitdb==4.0.5 GitPython==3.1.3 gprof2dot==2019.11.30 gunicorn==20.0.4 hiredis==2.2.3 humanize==3.9.0 hyperlink==19.0.0 idna==2.9 imagesize==1.2.0 importlib-metadata==1.6.1 incremental==17.5.0 ipython==7.15.0 ipython-genutils==0.2.0 isort==4.3.21 jdcal==1.4.1 jedi==0.17.0 jeepney==0.4.3 Jinja2==2.11.2 jmespath==0.10.0 keyring==21.2.1 kombu==4.6.10 lxml==4.9.3 MarkupSafe==1.1.1 mccabe==0.6.1 more-itertools==8.3.0 msgpack==0.6.2 msgpack-python==0.5.6 numpy==1.23.5 olefile==0.46 openpyxl==3.0.4 packaging==20.4 pandas==1.5.2 parso==0.7.0 pathlib2==2.3.5 pathspec==0.8.0 pbr==5.4.5 pep8-naming==0.9.1 pexpect==4.8.0 pickleshare==0.7.5 Pillow==9.4.0 pillow-heif==0.13.0 pkginfo==1.5.0.1 platformdirs==3.10.0 pluggy==0.13.1 prometheus-client==0.8.0 prompt-toolkit==3.0.5 ptyprocess==0.6.0 py==1.8.1 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycodestyle==2.5.0 pycparser==2.20 pydocstyle==5.0.2 pyflakes==2.1.1 Pygments==2.6.1 PyHamcrest==2.0.2 pyOpenSSL==19.1.0 pyparsing==2.4.7 pypdf2==3.0.1 pytest==5.3.5 pytest-cov==2.8.1 pytest-runner==5.2 python-dateutil==2.8.1 python-dev-tools==2020.2.5 python-docx==0.8.11 pytz==2020.1 pyunpack==0.2.1 pyupgrade==1.26.2 pywin32-ctypes==0.2.2 PyYAML==5.3.1 readme-renderer==26.0 redis==2.10.6 regex==2023.8.8 requests==2.23.0 requests-toolbelt==0.9.1 restructuredtext-lint==1.3.1 s3transfer==0.3.4 scandir==1.10.0 SecretStorage==3.1.2 sentry-sdk==0.17.0 service-identity==18.1.0 simplegeneric==0.8.1 six==1.16.0 smmap==3.0.4 snowballstemmer==2.0.0 Sphinx==2.3.1 sphinxcontrib-applehelp==1.0.2 sphinxcontrib-devhelp==1.0.2 sphinxcontrib-htmlhelp==1.0.3 sphinxcontrib-jsmath==1.0.1 sphinxcontrib-qthelp==1.0.3 sphinxcontrib-serializinghtml==1.1.4 sqlparse==0.3.1 stevedore==2.0.0 testfixtures==6.14.1 textX==2.1.0 tokenize-rt==4.0.0 toml==0.10.1 tornado==6.1 tox==3.14.3 … -
How to notify a User whenever an object is Created in Django model
I would like to tell a user automatically whenever a new game or a movie is uploaded or published on the website. below is my models. #games model GAME_TYPE=( ("action", "action"), ("adventure", "adventure"), ("racing", "racing"), ("puzzle", "puzzle"), ) MOV_TYPE=( ("action", "action"), ("adventure", "adventure"), ("sci-fi", "sci-fi"), ("horror", "horror"), ("drama", "drama"), ) GAME_OS=( ("Windows", "Windows"), ("Android", "Android"), ) class Games(models.Model): name=models.CharField(max_length=50) type=models.CharField(max_length=40, choices=GAME_TYPE) os=models.CharField(max_length=15, choices=GAME_OS) img=models.ImageField() developer=models.CharField(max_length=50) version=models.CharField(max_length=10) ratings=models.CharField(max_length=10) description=models.TextField() def __str__(self) -> str: return self.name class Movies(models.Model): name=models.CharField(max_length=50) type=models.CharField(max_length=40, choices=MOV_TYPE) description=models.TextField() released=models.DateField() def __str__(self) -> str: return self.name I need direct me on how to create an function to send or notify a user automatically whenever a game is published but l don't know how to do it. Anyone to solve me -
Django ORM Foreign Key Values how to return as single dictionary
How do I return all foreign key values into a single dict in the Django ORM? I understand how to access these values in Python, but I'm looking to retrieve them from a dict, rather than a class. class ChildModel(models.Model): location = models.TextField() class MasterModel(models.Model): town = models.ForeignKey(ChildModel, on_delete=models.CASCADE) To access the location in Python: queryset[0].town.location Accessing the values themselves does not return the location field. queryset.values() = {town: 1} What I want is: queryset.values() = {town: 1, location: some_value} If I run the SQL query in Postgres I get the dict I'm looking for (all inner join fields returned as a single dict). But how to do this in Django? -
Is there is option to cast django subquery object values to one text field
I have ticketing system, and for table view I'm using DataTables, I'm passing queryset values to DT constructor and rendering table view, this provides fast table data filtering and search options data = TicketData.objects.filter(f).values(...) json_data = repr(json.dumps(list(data), default=str)) TicketData object with related fields is big, I can't display all object values in table row, but I'm using them for filtering and search by putting them in hidden block. Each ticket can hold multiple assets and I need to have possibility to search/filter data in table by specific asset values, currently I'm adding them by looping trough all related assets and setting necessary values as new text field for object: for ticket in data: asset_search_data= "" for asset in TicketAssetMap.objects.filter(ticket__id=ticket['id'], edited=True): asset_search_data += str(asset.asset.asset_nr) + " " + str(asset.asset.inventory_nr)+ " " + str(asset.asset.room) + " " ticket['asset_search_data'] = asset_search_data json_data = repr(json.dumps(list(data), default=str)) This approach works, but page load is slow due to many sql requests. I'm thinking to use subquery for main data query, but I cant figure out how to combine queryset in to one text field. asset_data = TicketAssetMap.objects.filter(ticket=OuterRef('pk')).annotate(assets=Concat("asset__asset_nr", Value(" "), "asset__room", Value(" "), output_field=TextField())).values('assets') data = TicketData.objects.filter(f).annotate(assets=Subquery(asset_data)) This will fail as soon as ticket will have more … -
Configure django-tenants to write and read from AzureStorage
As per the django-tenants docs for file handling. I've done everything but if i include this line. DEFAULT_FILE_STORAGE = "django_tenants.files.storage.TenantFileSystemStorage" This will use local file storage path for storage. And when i checked TenantFileSystemStorage this class is inherited from FileSystemStorage. How can i configue TenantFileSystemStorage to use AzureStorage? I don't think any docs available to achieve this. Any help on this is much appreciated. Requirements: Upload should save any file to azure and also read from azure. -
Anyone to help me on how to create an automatic notification system that sends a message to a User whenever an object is created or modified
I have three models below, but l like to create a Notification System to send a message to a User whenever ; An object is created in all those models An object is modified in all those models And l would like to add trick that it sends the Notification Message after 15 minutes of publiction or creation. And I would like to pass the following data if available in the object ; the Name of the Object, the Image of the Object, and the type of the Object. My views from django.shortcuts import render def auto_notification(request): return render (request, "user/dashboard.html") My models from django.db import models from django.contrib.auth.models import User #articles model class Articles(models.Model): title = models.CharField(max_length=300) date= models.DateField() author=models.ForeignKey(User, on_delete=models.CASCADE) body=models.TextField() def __str__(self) -> str: return self.title #games model GAME_TYPE=( ("action", "action"), ("adventure", "adventure"), ("racing", "racing"), ("puzzle", "puzzle"), ) MOV_TYPE=( ("action", "action"), ("adventure", "adventure"), ("sci-fi", "sci-fi"), ("horror", "horror"), ("drama", "drama"), ) GAME_OS=( ("Windows", "Windows"), ("Android", "Android"), ) class Games(models.Model): name=models.CharField(max_length=50) type=models.CharField(max_length=40, choices=GAME_TYPE) os=models.CharField(max_length=15, choices=GAME_OS) img=models.ImageField() developer=models.CharField(max_length=50) version=models.CharField(max_length=10) ratings=models.CharField(max_length=10) description=models.TextField() def __str__(self) -> str: return self.name class Movies(models.Model): name=models.CharField(max_length=50) type=models.CharField(max_length=40, choices=MOV_TYPE) description=models.TextField() released=models.DateField() def __str__(self) -> str: return self.name Lastly I would like to add a : Notification DELETE … -
Where can i find out Python based MCQs and Answers. Please suggest some good references
I am building a Question Bank Model. I need Sample Python based MCQs and Answers to refer as my training data. Please suggest some references I am trying every where and no luck yet. Can one help me with a valid reference to sample Python MCQs covering basics, advanced, data science, AIML Django, Flask. Any great reference will do a great help to me -
How to create a ldap BIND_DN for samba active directory
I am trying to setup samba active directory users authentication for my Django app. I working in linux. I don't have access to windows active directory. I got a docker image smblds for samba AD DC on Ubuntu 22.04 using docker run --name smblds \ --publish 389:389 \ --publish 636:636 \ --detach smblds/smblds:latest The docker started fine. I can see the smb.conf and other tdb files created. But this docker does not set the BIND_DN value. So, I executed the docker and from inside the smblds docker I provisioned the active directory with samba-tool domain provision --use-rfc2307 --interactive I used all the default settings for Realm, Domain, server role, dns backend and Administrator password I see following messages in the output Setting up self join Repacking database from v1 to v2 format (first record CN=ms-WMI-StringSetParam,CN=Schema,CN=Configuration,DC=samdom,DC=example,DC=com) Repack: re-packed 10000 records so far Repacking database from v1 to v2 format (first record CN=server-Display,CN=409,CN=DisplaySpecifiers,CN=Configuration,DC=samdom,DC=example,DC=com) Repacking database from v1 to v2 format (first record CN=51cba88b-99cf-4e16-bef2-c427b38d0767,CN=Operations,CN=DomainUpdates,CN=System,DC=samdom,DC=example,DC=com) Is any of these a BIND_DN. Actually when I try to connect to active directory using python ldap I see invalid credential error. >>> import ldap >>> ldap_server = ldap.initialize("ldap://172.17.0.5/") >>> ldap_server.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) >>> ldap_server.set_option(ldap.OPT_X_TLS_NEWCTX, 0) >>> ldap_server.start_tls_s() >>> … -
Django - pythonanywhere - ProxyConnectionError
I deployed my Django project on pythonanywhere. In the project, I use "storages.backends.s3boto3.S3Boto3Storage" as DEFAULT_FILE_STORAGE. It connects to a cloud storage so that I can upload and save media files on there. It works fine on my local system but on pythonanywhere, it gives this error when a media file is going to be uploaded: ProxyConnectionError Failed to connect to proxy URL: "http://proxy.server:3128" I'm new to this and I don't know what else information is needed on this for someone to answer my question. So let me know to edit my question. -
Testing LDAP authentication in Django
I followed the answer in this question Testing authentication in Django but no one said the result for a successful connection. I copied the same code and got a response which I do not know. Here is the response: Does anyone know what it means? -
Django Multipart Upload with Ajax AWS S3 | How to get presigned URL?
Brother, i cant get it... so i have this: s3fileuploader.py import boto3 from boto3.s3.transfer import TransferConfig from .progresshandler import ProgressHandler from lumen import settings class S3Uploader(object): def __init__(self): self.s3 = boto3.client('s3', aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, ) self.config = TransferConfig( multipart_threshold=1024 * 100, max_concurrency=1, multipart_chunksize=1024 * 100, use_threads=False ) self.folder_name = 'simple_file_upload' self.progress_handler = None def upload(self, file_obj, filename, file_type, file_size): self.progress_handler = ProgressHandler(self.folder_name, filename, file_size) self.s3.upload_fileobj(file_obj, settings.AWS_STORAGE_BUCKET_NAME, # settings.AWS_S3_REGION_NAME, f'{self.folder_name}/{filename}', ExtraArgs={'ContentType': file_type}, Config=self.config, Callback=self.progress_handler) def get_upload_status(self): if self.progress_handler: return self.progress_handler.get_upload_status() return None class S3ParallelMultipartUploader(S3Uploader): def __init__(self): super(S3ParallelMultipartUploader, self).__init__() self.config = TransferConfig( multipart_threshold=1024 * 100, max_concurrency=10, multipart_chunksize=1024 * 100, use_threads=True ) self.folder_name = 'multipart_upload' progresshandler.py import threading from time import perf_counter from django.core.cache import cache class ProgressHandler(object): def __init__(self, cache_key_prefix, filename, size): self._filename = filename self._size = size self.perf_counter_start = perf_counter() self.cache_key = f'{cache_key_prefix}_{self._filename}' cache.set(self.cache_key, { 'uploaded_size': 0, 'progress_perc': 0, 'time_taken_s': 0 }) self._lock = threading.Lock() def __call__(self, bytes_amount): with self._lock: upload_status = cache.get(self.cache_key) upload_status['uploaded_size'] += bytes_amount upload_status['progress_perc'] = int((upload_status['uploaded_size'] / self._size) * 100) upload_status['time_taken_s'] = perf_counter() - self.perf_counter_start cache.set(self.cache_key, upload_status) def get_upload_status(self): upload_status = cache.get(self.cache_key) if upload_status: return {'progress_perc': upload_status['progress_perc'], 'time_taken_s': round(upload_status['time_taken_s'], 2)} return {'progress_perc': 0, 'time_taken_s': 0} views.py s3uploader = S3ParallelMultipartUploader() def create_post_aws(request): if request.method == 'POST': file = request.FILES["file"] title …