Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 = … -
Form is returning invalid for username value
I am trying to submit a username as default value for a model form but after submitting the value field turns blank after submit. Hence the form doesn't validate. This is my form: class WeeklyForm(ModelForm): class Meta: model = wreport fields = [ 'tname' ,'classes', 'fdate', 'tdate', 'objective', 'tplan', 'how', 'material', 'extra'] required = False widgets = { 'tname' : TextInput(attrs= {'class' : 'form-control', 'disabled' : True}), 'classes' : Select(attrs= {'class' : 'form-control'}), 'fdate' : DateInput(attrs= {'class' : 'form-control'}), 'tdate' : DateInput(attrs= {'class' : 'form-control'}), 'objective' : Textarea(attrs= {'class' : 'form-control'}), 'tplan' : Textarea(attrs= {'class' : 'form-control'}), 'how' : Textarea(attrs= {'class' : 'form-control'}), 'material' : Textarea(attrs= {'class' : 'form-control'}), 'extra' : Textarea(attrs= {'class' : 'form-control'}), } This is my view: @login_required(login_url='login') def weekly(request): context = '' weekly_form = WeeklyForm() daily_form = DailyForm() if request.method == 'POST' and 'weekly' in request.POST: initial = {'tname' : request.user.username} form = WeeklyForm(request.POST or None, initial = initial) # print(form['tname']) if form.is_valid(): # print(form) # form.save(commit=False) # form.tname = request.user.username form.save() # print(form.tname) messages.success(request, "Your report was submitted Successfully.") else: messages.error(request, form.errors) # print(form.errors) else: initial = {'tname' : request.user.username} weekly_form = WeeklyForm(initial = initial) I have tried sending value from form via kwargs but … -
How to display sum of disctinct items in django?
I would like to display sum all the distinct categories of the products that belongs to the user. I searched on the web, but all the things that I tried doensn't work. You may find the models,view and template below. It doesn't give me anything at the html. Model: class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,related_name='products') category = models.CharField(max_length=120) brand = models.CharField(max_length=120) product = models.CharField(max_length=120) price = models.DecimalField(decimal_places=2,max_digits=100) class Comp_Product(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE, related_name="comp_products") competitor = models.URLField() price = models.DecimalField(decimal_places=2,max_digits=100) change = models.FloatField() stock = models.BooleanField() last_update = models.DateField(auto_now_add=True) View: class DashboardList(ListView): template_name='dashboard_by_user.html' def get_queryset(self): return Product.objects.filter(user=self.request.user).annotate(count_category=Count('category',distinct=True)).aggregate(sum_category=Sum('count_category')) template: {% for product in product_list %} {{product.sum_category}} {%endfor%} -
How to filter database table using link <a href=''> in django?
I try to show a page with posts from that category when the user clicks on a link to a certain category This is mine urls.py file: from django.urls import path from .views import PostHomeView,PostDetail,NavFooter,PostPageView urlpatterns = [ path('navbar', NavFooter, name='Nav_Footer'), path('', PostHomeView.as_view(), name ='home'), path('PostDetail/<int:pk>', PostDetail.as_view(), name ='post_detail'), path('PostPage/', PostPageView, name ='post_page'), ] This is mine view.py file from django.shortcuts import render from django.http import HttpResponse from django.views.generic import ListView,DetailView from .models import Post, TaskCategory def NavFooter(request): return render(request,"nav_footer.html", {}) class PostHomeView(ListView): model = Post context_object_name = 'post' template_name = 'home.html' def get_queryset(self): return Post.objects.order_by('task_title')[:9] def PostPageView(reguest): posts = Post.objects.all() category = TaskCategory.objects.all() return render(reguest,'post_page.html',{'posts':posts,'category':category}) class PostDetail(DetailView): model = Post template_name = 'post_detail.html' This is models.py file: from django.contrib.auth.models import User from django.db import models class TaskCategory(models.Model): category_title = models.CharField(max_length=50) def __str__(self): return self.category_title class Post(models.Model): task_category = models.ForeignKey(TaskCategory, on_delete=models.CASCADE) recommended_tools = models.CharField(max_length=250) budget = models.CharField(max_length=250) def __str__(self): return self.task_title + ' | ' + self.task_discription + ' | ' + str(self.task_category) + ' | ' + self.recommended_tools + ' | ' + self.budget The fastest way to access this file via html -
django CBV's CreateView upload image into the folder that is created by object id
How do I, in class-based views CreateView can implement upload logic. I would like to first save the object, get its saved id, Then gets that object back, Update the folder_name field Once it's done I would like to upload the file to that newly created folder. Plus any suggestions on the code below: class MemberCreateView(PermissionRequiredMixin, CreateView): raise_exception = False permission_required = 'members.add_member' redirect_field_name = 'next' model = models.Member form_class = AddMember template_name = 'members/create.html' # success_url = '/members/' def get_initial(self, *args, **kwargs): initial = super().get_initial(**kwargs) # initial['name'] = 'Add a name' return initial def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super(ModelFormMixin, self).form_valid(form) def get_success_url(self): current_id = self.object.id memb = models.Member.objects.get(pk=current_id) memb.folder_name = str(current_id) + "_" + slugify(self.object.name) memb.save() return '/members/'+str(current_id) + "/add_family/" any suggestions on how can I improve my code Regards -
Django permissions: custom logic-based checks
Simplified example: # foo/models.py class Bar(models.Model): author = models.ForeignKey(User) # foo/views.py class BarEditView(PermissionRequiredMixin, UpdateView): permission_required = 'foo.change_bar' model = Bar success_url = '/' I want the BarEditView to be accessible by: users who have foo.change_bar permission in the database (already accomplished by the first line of that class) the author of that particular Bar record The first is easily handled by basic permissions/groups. How do I achieve the second? I need to write some custom permission check logic, but I can't find anything in the docs or google. I don't want to have to "manually" add a permission to the database every time a Bar author is set/changed/removed. To be clear, I am not asking how to create a "custom permission". I want am trying to augment the logic for determining who has permission. -
How does one log in multiple users in django
Am developing a school management system using Django. The project has got 5 apps, namely student, teacher, parent, blog and finance. The super admin an add, delete, update or edit students, parent, blog and finance (student school fees). How can i design the models so that the system can be used to log in different users and send them in different pages. For example when a student logs in should be redirected to the student dashboard while when a teacher logs in should be redirected to the teachers dashboard and for the super admin can access all the students and teachers.