Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Download a dynamic html page as pdf on button click
I want to download pdf where the source is a url or a div. I have a database of quizzes based on different categories. These quizzes have MCQ and images. I am able to render the quiz in an HTML however I want to give users a chance to download the quiz on each topic as pdf using "click here to download" On clicking a pdf with the questions and images will be downloaded. I tried using pdfMake using the following code $("#download_quiz").click(function(){ // create the window before the callback // pass the "win" argument var docDefinition={ content:[ "hello world" ] } pdfMake.createPdf(docDefinition).download(); }); however, my content is dynamic. How do I achieve it ? Is there another way to do this. I am using Django as my webdev. -
How do I loop a Django Queryset in Javascript
How can I loop a Django model queryset in javascript. I have a music player that uses javascript and the 'trackUrl' variable inside the javascript lists the track paths, I need to be able to loop through each users uploaded tracks and load them into the player for each user. I basically need to get the track out from the Music model, for each user. Hopefully this makes sense , here's some of the code i have now. models.py class Music(models.Model): track = models.FileField(upload_to='path/to/audio') title = models.TextField(max_length=50) artwork = models.ImageField(upload_to='path/to/img', blank=True) artist = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title music.js <script> $(function() { var playerTrack = $("#player-track"), bgArtwork = $('#bg-artwork'), bgArtworkUrl, albumName = $('#album-name'), trackName = $('#track-name'), albumArt = $('#album-art'), sArea = $('#s-area'), seekBar = $('#seek-bar'), trackTime = $('#track-time'), insTime = $('#ins-time'), sHover = $('#s-hover'), playPauseButton = $("#play-pause-button"), i = playPauseButton.find('i'), tProgress = $('#current-time'), tTime = $('#track-length'), seekT, seekLoc, seekBarPos, cM, ctMinutes, ctSeconds, curMinutes, curSeconds, durMinutes, durSeconds, playProgress, bTime, nTime = 0, buffInterval = null, tFlag = false, albums = ['Dawn','Me & You','Electro Boy','Home','Proxy (Original Mix)'], trackNames = ['Skylike - Dawn','Alex Skrindo - Me & You','Kaaze - Electro Boy','Jordan Schor - Home','Martin Garrix - Proxy'], albumArtworks = ['_1','_2','_3','_4','_5'], trackUrl = … -
Create a Django fixture file that leaves some fields unchanged when loaded into DB
Is it possible to create a fixture that is written to the DB using loaddata, and overwrites some fields of an existing record, but not all of them? For example, suppose I have a table in my DB called app_foo: id bar baz 1 "a" "b" 2 "c" "d" The corresponding YAML fixture file for this would look like: - model: app.foo pk: 1 fields: bar: "a" baz: "b" - model: app.foo pk: 2 fields: bar: "c" baz: "d" How would I modify this fixture such that: Records 1 and 2 have an empty baz field when loading the fixture into a fresh empty database. When the fixture is loaded into a database already containing records 1 and 2 that have values for baz, they aren't overwritten with NULL. I thought that I could do something like this: - model: app.foo pk: 1 fields: bar: "a" - model: app.foo pk: 2 fields: bar: "c" or this: - model: app.foo pk: 1 fields: bar: "a" baz: - model: app.foo pk: 2 fields: bar: "c" baz: But both attempts overwrote the baz field for DB records 1 and 2 with NULL. This isn't specified in the documentation for fixtures, but is an … -
Django form validation clean methods not working
This is my form class class Feedback(forms.Form): name = forms.CharField(validators=[name_validate]) rollno = forms.IntegerField() email = forms.EmailField() feedback = forms.CharField(widget=forms.Textarea) This is clean method def clean_name(self): data = self.cleaned_data['name'] print(len(data)) if len(data)<4: raise forms.ValidationError('Exception') return data The control is entering to if condition but not raising error -
Why does django libraries documentation dive straight into how to implement rather than starting with what it is about?
I was checking out the celery documentation: https://docs.celeryproject.org/en/stable/django/first-steps-with-django.html which of course I found by googling django celery. I read in an article that I can use the asynchronous tools that it provides which serves my purpose. My question is what is the best way to read the celery documentation since it immediately starts with how to use it. Wouldn't it be rather nice from the readers point of view if the documentation started with an overview of what it is about and the major functions it provides. I would like to hear your opinion about it. Thank you in advance! -
Django does not import local site packages on apache
I've pulled my django project onto an apache server and installed all dependecies with requirements.txt. All of the packages have downloaded to a local folder on the server and django appears to be pointing to it (as seen in the picture below) but none of them can actually be imported when running with apache (works fine with the django server). I can definitely see all packages in the /home/bitnami/.local/lib/python3.8/site-packages folder so I'm not sure what could possibly be wrong. I've set up the deployment following djangos but I assume there's some sort of import I'm missing. Any ideas? server .conf file WSGIScriptAlias / /opt/bitnami/projects/my_website/core/wsgi.py WSGIPythonPath /opt/bitnami/projects/my_website <Directory /opt/bitnami/projects/my_website/core> <Files wsgi.py> Require all granted </Files> </Directory> tweepy failed import pic - text below Exception Value: No module named 'tweepy' Exception Location: /opt/bitnami/projects/my_website/twitterapp/controllers/twitter_controller_rename.py, line 2, in <module> Python Executable: /opt/bitnami/python/bin/python3 Python Version: 3.8.5 Python Path: ['/opt/bitnami/projects/my_website', '/opt/bitnami/projects/my_website', '/opt/bitnami/python/lib/python38.zip', '/opt/bitnami/python/lib/python3.8', '/opt/bitnami/python/lib/python3.8/lib-dynload', '/opt/bitnami/python/lib/python3.8/site-packages', '/opt/bitnami/python/lib/python3.8/site-packages/setuptools-46.4.0-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/pip-20.2.1-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/virtualenv-20.0.30-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/six-1.15.0-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/filelock-3.0.12-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/distlib-0.3.1-py3.8.egg', '/opt/bitnami/python/lib/python3.8/site-packages/appdirs-1.4.4-py3.8.egg', (THIS FOLDER) '/home/bitnami/.local/lib/python3.8/site-packages'] -
Django-filer PIL convert and override original
To replace the original file with a converted to webp version I've done the follow in my models.py: django==2.2.17 django-filer==2.0.2 Pillow==8.0.0 class Provaa(File): data = models.DateTimeField(auto_now=True,) class Meta: managed = True verbose_name = 'Allegato' def convert_to_webp(self): extension = ['jpeg', 'png', 'jpg', 'img'] if any(ext in self.file.name.lower() for ext in extension): try: img = Image.open(self.file) correggi_nome = self.file.name.split('.')[0] img.save(correggi_nome + '.webp','webp') logger.error('img.save save another copy of the file not repalce the original!') except Exception as ex: logger.error(ex) def save(self, *args, **kwargs): self.convert_to_webp() super(Provaa, self).save() This correctly save a webp file but in the current project folder not replacing the original file. ipdb> type(self.file.file) <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> ipdb> type(self.file) <class 'filer.fields.multistorage_file.MultiStorageFieldFile'> ipdb> type(img) <class 'PIL.PngImagePlugin.PngImageFile'> I've tried to replace the self.file with img, but it fail. I don't need to keep the original file, only the converted file. -
Can we create multiple views in django
I am doing an online shopping site project in django. I have the following modules -Admin -Moderators -Employees -Service -Users. If i write all the views in single views.py it will be mess, So can I create a Folder named Views and create multiple views (adminViews.py, userviews.py etc) and write functions in it? Is it a good way? Also do i need to create folder that contain multiple Forms file for different modules?? -
Button action in Django
My class Scenario has several actions. I can ejecute the action writting his name in the action bar and typing the button called "Go": But I want to creat a button like this called "Make Mortal": How can I do the botton? -
how to make Django manage.py runserver exit on DB error?
I have a django webapp running in a docker container with the following command: ENTRYPOINT ["python", "manage.py"] CMD ["runserver", "0.0.0.0:8000"] However, sometimes the django "boot" fails because of temporary database errors: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/usr/local/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 185, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.6/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: remaining connection slots are reserved for non-replication superuser connections The problem is, the process doesn't exit and is still running, Plus, it doesn't retry connecting afterwards. So it appears healthy from the orchestrator and isn't restarted automatically. How can I make the command exit when such errors are encountered ? -
Is there a way to add additional project generation options in Cookiecutter Django at a later stage?
I set up a project using Cookiecutter Django and would now like to activate other generation options (Docker, Celery) that I left out during initial setup. Is there a convenient way to do this using the commands/setup guides provided? Or would I have to manually set up additional components? -
How to change label / caption of readonly item in django admin
I just would like to find an answer of how to change label / caption of readonly item in Django admin. When the field / form is not readonly then it is rather easy to do like: class MyModelAdmin(admin.ModelAdmin): readonly_fields=( 'field_ro_1', 'field_ro_2', ) def get_form(self, request, obj=None, change=False, **kwargs): form = super().get_form(request, obj, change=False, **kwargs) form.base_fields['field_xyz'].label = 'This is field XYZ' form.base_fields['field_ro_1'].label = 'This is field readonly 1' # this doesn't work for readonly form and causing an error return form But what to do with readonly forms / fields? Thank you so much in advance for the hints. -
Multiply Django field values to get a total
I have the following models: class Supplier(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True, blank=True) email = models.CharField(max_length=200, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) class Meta: ordering = ('name',) def __str__(self): return self.name class Order(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.supplier.name @property def total(self): orderitems = self.product_set.all() total = sum([item.get_total for item in products]) return total class Product(models.Model): description = models.CharField(max_length=30) costprice = models.FloatField(null=True, max_length=99, blank=True) retailprice = models.FloatField(null=True, max_length=99, blank=True) barcode = models.CharField( null=True, max_length=99, unique=True, blank=True) supplier = models.ForeignKey( Supplier, on_delete=models.CASCADE, default=5) on_order = models.ForeignKey( Order, on_delete=models.CASCADE, null=True, blank=True) on_order_quantity = models.FloatField(null=True, blank=True) class Meta: ordering = ('description',) def __str__(self): return self.description i've created an order object for a given supplier with two products, with different quantities and cost prices. How do I multiply cost x qty and add up those values in order to reach a total order value? this is my view def PurchaseOrder(request, pk_order): orders = Order.objects.get(id=pk_order) products = Product.objects.filter( on_order_id=pk_order).prefetch_related('on_order') total_products = products.count() supplier = Product.objects.filter( on_order_id=pk_order).prefetch_related('on_order') total_value = Product.objects.filter( on_order_id=pk_order).aggregate(Sum('costprice')) context = { 'supplier': supplier, 'products': products, 'orders': orders, 'total_products': total_products, 'total_value': total_value, } return render(request, 'crmapp/purchase_order.html', context) at the moment it returns this: -
Issue with Django service worker: Uncaught SyntaxError: Unexpected token '<'
I try to add service worker to my app. But got an error Uncaught SyntaxError: Unexpected token '<' using debug tool, the first line <!doctype html> is underline for each files with error message I coul not find anywhere explaination for that... hope someone could help -
Bootstrap Accordion with django-tables2 SingleTableMixin
I am trying to create a bootstrap accordion with a django-table2 SingleTableMixin FilterView. The advantage for me with SingleTableMixin is that I can use the ExportMixin. The model has the fields, options and longtext, which I want to display under each row if clicked. view.py class MasterReportList(SingleTableMixin,LoginRequiredMixin, ExportMixin,FilterView): export_formats = ['csv', 'xlsx'] table_class = MasterReportTable #model = MasterReportData filterset_class = MasterReportFilter template_name = 'masterreport.html' paginate_by = 25 table.py class MasterReportTable(tables.Table): class Meta: model = MasterReportData #exclude = ("id","from_file", "exported_at","created_at" ) My question is, how can I access single, specific columns inside the custom template? -
DJANGO: How to create a method that copies an object of a model?
I want to create a method that copies an object of the BlogPost model. my models looks like this: class BlogPost(models.Model): title = models.CharField(max_length=250) body = models.TextField() author = models.ForeignKey(Author, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) def copy(self): pass class Comment(models.Model): blog_post = models.ForeignKey( BlogPost, on_delete=models.CASCADE, related_name="comments" ) text = models.CharField(max_length=500) my challenge is implementing the copy method. The copy method should copy the current object with all the comments related to that and I don't have any idea how to do it. -
TypeError: expected str, bytes or os.PathLike object, not InMemoryUploadedFile
I am getting following error when I am trying to upload image for predictive model- Exception Value: expected str, bytes or os.PathLike object, not InMemoryUploadedFile Exception Location: /Users/ragnar/plant-disease-recognition/lib/python3.8/site-packages/keras_preprocessing/image/utils.py in load_img, line 113 views.py class Predict(generics.CreateAPIView): serializer_class = ImageSerializer def post(self, request): """ post: API to send leaf image and get its health status or disease. """ data = ImageSerializer(data=request.data) if data.is_valid(): photo = request.data['photo'] img = image.load_img(photo, target_size=(224, 224)) img = image.img_to_array(img) img = np.expand_dims(img, axis=0) img = img/255 with graph.as_default(): prediction = model.predict(img) prediction_flatten = prediction.flatten() max_val_index = np.argmax(prediction_flatten) result = output_list[max_val_index] return Response({'result': result}) -
django switch databse user on each subdomain in the same app
i want to make a django application and for a security reasons, i have three types of users (admins, teachers , and students) i want to make a subdomain for each type of users users.domain.com teachers.domain.com admins.domain.com after the loggin i want to switch to a specific database user for each subdomain (the same database) I m new to django and i want some help to do this Thanks -
Deploy django with apache, django channels 3 and daphne in wss
Os Ubuntu 20 LTS i have a problem with my project in production, and i don't understand where and whats it's going wrong, thease are the files and the responses: 000-default.conf: <VirtualHost *:80> ..... RewriteEngine on RewriteCond %{SERVER_NAME} =site.addns.org [OR] RewriteCond %{SERVER_NAME} =www.site.addns.org RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC,OR] RewriteCond %{HTTP:CONNECTION} ^Upgrade$ [NC] RewriteRule .* wss://%{SERVER_NAME}%{REQUEST_URI} [P,QSA,L] ProxyPass /wss/ wss://127.0.0.1:8000/ ProxyPassReverse /wss/ wss://127.0.0.1:8000/ </VirtualHost> <VirtualHost *:443> ..... ProxyPreserveHost On SSLProxyEngine on SSLProxyVerify none SSLProxyCheckPeerCN off SSLProxyCheckPeerName off RewriteEngine on RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC,OR] RewriteCond %{HTTP:CONNECTION} ^Upgrade$ [NC] RewriteRule .* ws://127.0.0.1:8000%{REQUEST_URI} [P,QSA,L] ProxyPass /wss/ wss://127.0.0.1:8000/ ProxyPassReverse /wss/ wss://127.0.0.1:8000/ </VirtualHost> asgi.py: import os from django.urls import re_path, path from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "produzione.settings") django_asgi_app = get_asgi_application() from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.routing import get_default_application from principale import consumers application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AuthMiddlewareStack( URLRouter([ path(r'wss/$', consumers.EchoConsumer.as_asgi()), path(r'ws/chat/$', consumers.EchoConsumer.as_asgi()), ]) ), }) consumers.py: import json from channels.generic.websocket import WebsocketConsumer from channels.consumer import AsyncConsumer class EchoConsumer(WebsocketConsumer): def connect(self): self.accept() settings.py: ... ASGI_APPLICATION = "produzione.asgi.application" CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 8000)], }, }, } ... js file: var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"; var chat_socket … -
How to get username in form automatically in Django Forms?
I want to create a basic comment part for my project. But I cannot figure out how can I get username with forms. I tried to use initial but it did not work. How can I fix it? view.py def ocr(request, id): ... if request.method == 'POST': form_2 = CommentForm(request.POST, request.FILES, instance=pdf) if form_2.is_valid(): initial = {'username': request.user.username} form_2 = CommentFromOthers(initial=initial) form_2.save() else: form_2 = CommentForm() ... models.py class CommentFromOthers(models.Model): comp_name = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True) doc_id = models.ForeignKey(Pdf, on_delete=models.DO_NOTHING, null=True) comments = RichTextField(blank=True) created_date = models.DateTimeField(default=datetime.now()) username = models.CharField(max_length=250, default='') forms.py class CommentForm(forms.ModelForm): comments = RichTextField class Meta: model = CommentFromOthers fields = ('comments',) -
How to store and Retrieve List in database Django
I am trying to store the python List data type value into DB. Please find the below code I am using. Model.py class Counter(models.Model): myList = models.TextField(null=True) # JSON-serialized (text) version of your list views.py import simplejson as json def CTS_upload(request): -----Some logic--- myModel = Counter() listIWantToStore = [0,] -------Some code logic----- i = i + 1 count.append(i) listIWantToStore.append(i) myModel.myList = json.dumps(listIWantToStore) Problem: here each time when I am uploading a .xls file a new list object is getting created. I want changes to happen in the same existing List. Please find the below image. problem2: When I am trying to decode I am getting the below error. Exception Type: TypeError Exception Value: Input string must be text, not bytes def countclear(request): jsonDec = json.decoder.JSONDecoder() myPythonList = jsonDec.decode(Counter().myList) print(type(myPythonList)) print(myPythonList) ------Remaining code--- Any help on this how to create OR edit existing and retrieve values would be very helpful. -
Django - Adding permissions to user group during migration
I have a user group which I'm trying to add permissions to during migration using migrations.RunPython, such that the group is automatically created with appropriate permissions. I have a multi tenant app and would like those groups made upon creation of a new tenant. Creation of groups and permissions works fine but when I try to add a permission to a group that change is not applied after migration is finished. Here's my current code, I already applied some solutions from other questions I found but so far none of them work: portal/migrations/0003_add_group_perms.py def add_group_permissions(apps, schema_editor): db_alias = schema_editor.connection.alias try: emit_post_migrate_signal(2, False, 'default') except TypeError: # Django < 1.8 emit_post_migrate_signal([], 2, False, 'default', db_alias) Permission = apps.get_model("auth", "Permission") Group = apps.get_model("auth", "Group") for group in usergroup_permissions: role, created = Group.objects.get_or_create(name=group) logger.info(f'{group} Group created') for perm in usergroup_permissions[group]: role.permissions.add(Permission.objects.get(codename=perm)) logger.info(f'Permitting {group} to {perm}') role.save() class Migration(migrations.Migration): dependencies = [ ('portal', '0002_import_groups'), ] operations = [ migrations.RunPython(add_group_permissions), ] the usergroup_permissions variable looks like this and contains permission codenames: usergroup_permissions = { "Administrator": [ "add_user", "delete_user", ], When starting the development server I can then see, that the permissions are not applied to group administrator: screenshot I'm using django 3.1.6 and django-tenants 3.2.1 … -
How can I apply grammatical gender in Choices?
I use Model Utils to define statuses in Django : class MetaData(TimeStampedModel, StatusModel, SoftDeletableModel): STATUS = Choices(('Draft', _('Draft')), ('Submitted', _('Submitted')), ('Reviewed', _('Reviewed')), ('Final', _('Final')),) These statuses may eventually apply to a masculine or feminine object (in French), and I don't understand how to define pgettext contexts here. Thank you very much ! -
Django ORM using cursor to memory optimize QuerySets
Is there any way to convince Django ORM to use a database cursor when iterating through a large QuerySet so that it does not load all the objects at once but load them by parts instead? -
DRF- Many to many through model serialization issue
I can't not get the serialised response from create method of profileserializer, it successfully creates the object but while returning serialised reponse, it tries to access the attribute of m2m field instead of throughmodel and shows error mentioned below: The serializer field might be named incorrectly and not match any attribute or key on the State instance. Original exception text was: 'State' object has no attribute 'state'. Models and serializers details are given below. class State(CommonModel): name = models.CharField(max_length=100) code = models.CharField(max_length=2) def __str__(self): return str(self.name) class Profile(CommonModel): states = models.ManyToManyField(State, related_name=“profile_states, through='ProfileStates', through_fields=('profile', 'state', 'license_type'), blank=True) class ProfileStates(models.Model): profile = models.ForeignKey(Profile, on_delete=models.CASCADE) state = models.ForeignKey(State, on_delete=models.CASCADE) license_type = models.ForeignKey(LicenseType, on_delete=models.CASCADE, null=True) class Meta: db_table = "app_name_profile_licensed_states" unique_together = ("profile", "state", 'license_type') class ProfileStatesSerializer(serializers.ModelSerializer): class Meta: model = ProfileStates fields = ("state", "license_type") class ProfileSerializer(serialisers.ModelSerializer): states = ProfileStatesSerializer(models.ProfileStates.objects.all(), many=True) def create(): return instance I have tried adding related_name in serializer and remove states from required field like: class ProfileSerializer(serialisers.ModelSerializer): profile_states = ProfileStatesSerializer(models.ProfileStates.objects.all(), many=True) def create(): return instance def get_field_names(self, declared_fields, info): expanded_fields = super(ProfileSerializer, self).get_field_names(declared_fields, info) if getattr(self.Meta, 'extra_fields', None): return expanded_fields + self.Meta.extra_fields else: return expanded_fields class Meta: model = models.Profile fields = ("__all__") extra_fields = [‘profile_states'] extra_kwargs = …