Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ListView class pagination filter query not effecting in pagination
i failed to include pagination in django list view pagination count shows without filter query any idea about to include fileter query in pagination calculation? assets_list = Assets.objects.filter(site=self.site,type__icontains="Asset") page = self.request.GET.get('page', 1) paginator = Paginator(assets_list, self.paginate_by) try: asset_data = paginator.page(page) except PageNotAnInteger: asset_data = paginator.page(1) except EmptyPage: asset_data = paginator.page(paginator.num_pages) context['assets'] = asset_data -
ckeditor not working on heroku deployment
I deploy my django blog to heroku but my ckeditor dosent work and after turning DEBUG = False and Add X_FRAME_OPTIONS = 'SAMEORIGIN' . This happend on when trying to runserver aswell when it was working with no problem before when i dident have DEBUG = False or X_FRAME_OPTIONS = 'SAMEORIGIN' . img1 img2 -
Django expected css(css-rparantexpected) when trying to add image to <body id ="bg" >
https://paste.pics/H6N16 So here is how my project is organised, I followed a youtube tutorial and for me it shows that paretentheses are missing, maybe that can be due to the bad folder management, I'm not sure <body id = "bg" style="background-image: url('{% static "image/patient_doctor.png" %}');"> Dont know what to do :/ -
Django - Handle two forms in CBV
I've been struggling the past few days with how to process two forms in the same Class Based View. I cannot get it working. I tried to play with get_context_data and post but I can't get the two forms working. In views.py, the get_context_data method: class UserViewReport(LoginRequiredMixin, TemplateView): """ View to access ONE report """ model = Report template_name = 'tool/single-report.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) slug = self.kwargs['slug'] report_id = get_object_or_404(Report, slug=slug) context['report_title'] = report_id.title reports_details = ReportDetails.objects.filter(report=report_id) dict_errors = {} missing_transporters = [] #Getting supplements and transporter names supplements = Supplement.objects.filter(company=self.request.user.company) context['supplements'] = supplements #Company file form ''' Testing if COMPANY file already exists in REPORT database ''' if not CompanyFile.objects.filter(report=report_id).exists(): context['company_form'] = CompanyFileForm(self.request.POST or None) #Transporter file form context['transporter_form'] = TransporterFileForm(self.request.POST or None) And the post method: def post(self, request, *args, **kwargs): report_id = get_object_or_404(Report, slug=self.kwargs['slug']) transporter_form = TransporterFileForm(request.POST, request.FILES) company_form = CompanyFileForm(request.POST, request.FILES) if transporter_form.is_valid(): obj = transporter_form.save() transporter_name = request.POST.get('transporter_name') transporter = get_object_or_404(Transporter, name=transporter_name) cd = transporter_form.cleaned_data file_name = cd.get('file') transporter_file = TransporterFile.objects.filter(pk=obj.pk).update(name=file_name, transporter=transporter, report=report_id, company=report_id.company, user=request.user) return redirect('tool:single-report', slug=self.kwargs['slug']) elif company_form.is_valid(): obj = company_form.save() cd = company_form.cleaned_data file_name = cd.get('file') company_file = CompanyFile.objects.filter(pk=obj.pk).update(name=file_name, user=request.user, company=report_id.company, report=report_id) return redirect('tool:single-report', slug=self.kwargs['slug']) return render(request, self.template_name, {'company_form': … -
how to configure django-froala-editor to upload images to aws S3 bucket
I am working on Django2.2.6 apps and one of the model filed is FroalaField where users can upload images from their machine local storage, the default Django models.FileField has a defualt upload_to attribute like this models.FileField(upload_to=get_blog_filepath, null=True, blank=True), how can I configure FroalaField to upload images to S3 by passing the url, I have looked at the docs and didn't find something useful in my case. from django.db import models from froala_editor.fields import FroalaField class BlogPost(models.Model): short_title = models.CharField(max_length=200, null=True, blank=False, db_column='db_short_title') title = models.CharField(max_length=200) blurb = FroalaField(max_length=300) # how I can do upload_to S3 report_file = models.FileField(upload_to=get_blog_filepath, null=True, blank=True) -
Django form filter not selecting output
My form shows all the ce_hostname objects in the database with a dropdown. I want to filter the ce_hostname to ones which only have a common order reference. I can't get this working. My dropdown is currently blank. forms.py class Cx_BaseForm(ModelForm): class Meta: model = Cx_Base fields = ['cx_hostname', 'new', 'ce_hostname', 'location', 'manged_module_model', 'slot'] def __init__(self, *args, **kwargs): super(Cx_BaseForm, self).__init__(*args, **kwargs) self.fields['ce_hostname'].queryset = Ce_Base.objects.filter(order_reference=self.instance.order_reference) models.py class Ce_Base(models.Model): ce_hostname = models.CharField(max_length=15, validators=[CE_HOSTNAME_REGEX], verbose_name="CE Hostname", help_text="Hostname of router.") order_reference = models.ForeignKey(Order, null=True, on_delete=models.CASCADE) class Cx_Base(models.Model): order_reference = models.ForeignKey(Order, null=True, on_delete=models.CASCADE) cx_hostname = models.CharField(max_length=15, validators=[CX_HOSTNAME_REGEX], verbose_name="CX Hostname", help_text="Hostname of Switch.") new = models.BooleanField(help_text="Select if installing new hardware. Leave blank if switch exists on DCN.") ce_hostname = models.ForeignKey(Ce_Base, null=True, on_delete=models.CASCADE, verbose_name="CE Hostname", help_text="Hostname of router in which the module will be inserted.") location = models.TextField(null=True, blank=True, help_text="Address of site. Leave blank if not new.") manged_module_model = models.CharField(max_length=200, null=True, blank=True, choices=MANAGED_MODULES, help_text="Hardware model of switch. Leave blank if not new.") slot = models.CharField(max_length=200, null=True, blank=True, choices=SLOT, help_text="Slot in which the module will be inserted. Leave blank if not new.") l2_interfaces = JSONField(null=True) def __str__(self): return self.cx_hostname -
ModuleNotFoundError: No module named 'froala_editor'
I am running django v2.2.6 on docker container, I entered django container and ran installed pip install django-froala-editor and when I run pip freeze it shows django-froala-editor is installed. and add I it into my installed apps INSTALLED_APPS = [ ...., 'froala_editor', ] and I used it into my model files, and actually is working fine but I still get this error every time I run the containers docker compose up and there is a volumes attached to the containers, please note that is working fine but I am curios why it still throwing this error -
How do i upload libraries django app to hosting by cPanel
I want upload django app to hosting by cPanel but i have problem when setup python app configuration files after add requirements.txt gives me an error these libraries are not accepted: matplotlib==3.5.1 pandas==1.3.5 Pillow==9.0.0 psycopg2==2.9.1 scipy==1.7.3 seaborn==0.11.2 Is there a solution? -
Django Project with TWO frontend VUE 3 apps
Django project has two apps. Customers & Operations. I want to separate access to the apps with separated front ends. The user authorization strategy I will follow to achieve this is where I am stuck. My research has is advising against two user models. And I recently found out about Proxy models. I need opinions on best approach for above requirement. the access links requirements are e.g app1 customers.example.com app2 operations.example.com Customers will have its own set of users and authorization. Operations will have its own set of users and authorization. Operations app will create Customers[eg Cust_X, Cust_Y]. Cust_X will have users[eg User_X1, User_X2] Cust_Y will have users[eg User_Y1, User_Y2] -
Django Python List Postmark API
I'm trying to send a list of items to Postmarks API to display items on a template receipt. Here is my query in Python/ Django. items = order.orderitem_set.all() data = items.values("product__name","quanity","product__point_price", "order_id") data_list = list(data) Here is the output: [{'product__name': 'Pokemon 25th Anniversary', 'quanity': 1, 'product__point_price': 100.0, 'order_id': 31}, {'product__name': 'Minecraft - Nintendo Switch', 'quanity': 1, 'product__point_price': 100.0, 'order_id': 31}] [ So what I am trying to do is list these items individually on the postmark API template. Here is the HTML code for this. <table class="purchase" width="100%" cellpadding="0" cellspacing="0"> <tr> <td> <h3>Order ID: {{receipt_id}}</h3></td> <td> <h3 class="align-right">Date: {{date}}</h3></td> </tr> <tr> <td colspan="2"> <table class="purchase_content" width="100%" cellpadding="0" cellspacing="0"> <tr> <th class="purchase_heading"> <p class="align-left">Description</p> </th> <th class="purchase_heading"> <p class="align-right">Amount</p> </th> </tr> {{#each receipt_details}} <tr> <td width="60%" class="align-left purchase_item">{{description}} Quanity: {{quanity}}</td> <td width="40%" class="align-right purchase_item">{{amount}}</td> </tr> {{/each}} <tr> <td width="80%" class="purchase_footer" valign="middle"> <p class="purchase_total purchase_total--label">Total Points</p> </td> <td width="20%" class="purchase_footer" valign="middle"> <p class="purchase_total">{{points}}</p> </td> </tr> </table> Here are my Django views where you send the data to the postmark template. How do I get the items individually out of the list? "receipt_details": [ { "description": data_list.product__name, <--- This obviously doesn't work. How would I do this? "quanity": "quanity_Value", "amount": "amount_Value" } ], -
Django - Using single list objects from a model class
So Create_Watchlist is a model with a Foreignkey to the User Model and 'ticker' is a CharField of Create_Watchlist. Here is my views.py function for the approach def watchlist_one(request, pk): Create_Watchlist.objects.get(id=pk) list_ticker = list(Create_Watchlist.objects.all().values_list('ticker', flat=True)) At the moment list_ticker equals ['AAPL, BTC'] I want to access in this case 'AAPL' and 'BTC' as different list objects, because I want to make an API request with each list item. The list_ticker variable changes with the users input from a form . So there could be smt like ['AAPL, BTC'], but as well smt like ['FB'] (etc.) If I've made a mistake here, an explanation of how to deal with query sets and data types would also help me! Thanks a lot :) -
Django SocketIo problems
I am trying to do a chat app in django with socketio. I tried to do it from this video. I did it but how can I add history to the chat with consume the least space in my computer? With history I mean even for example if I refresh the page or close the computer If I go again I will see the same conversation. But I don't want the messages consume much space in my computer. Also should I don't use socketio and do the chat with something other? Thanks. -
Django 'ModuleNotFoundError: No module named 'blog/wsgi' when deploying to Elastic Beanstalk, as well as 'Error while connecting to Upstream'
I am trying to deploy a static Django website to Elastic Beanstalk via the UI 'upload your code' and not the EB CLI. I have created a zip file of all of my contents and have tried uploading it a million times, only to be met with the errors 'ModuleNotFoundError: No module named 'blog/wsgi' when deploying to Elastic Beanstalk, as well as 'Error while connecting to Upstream'. I think it is an error with the 'django.config' file in my .ebextensions folder. The contents of the 'django.config' file is: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: blog/wsgi:application. The contents of my 'wsgi.py' file is import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'blog.blog.settings') application = get_wsgi_application(). I have attached a screenshot of my folder structure as well. I can attach any other files if necessary. Thank you. -
Trouble saving empty Base64ImageField in Django Restframework
I am using a custom class to store base64 images that are coming via API requests. The class looks like this: class Base64ImageField(serializers.ImageField): def to_internal_value(self, data): if isinstance(data, six.string_types): if 'data:' in data and ';base64,' in data: header, data = data.split(';base64,') try: decoded_file = base64.b64decode(data) except TypeError: self.fail('invalid_image') file_name = str(uuid.uuid4())[:16] file_extension = self.get_file_extension(file_name, decoded_file) complete_file_name = "%s.%s" % (file_name, file_extension, ) data = ContentFile(decoded_file, name=complete_file_name) return super(Base64ImageField, self).to_internal_value(data) def get_file_extension(self, file_name, decoded_file): import imghdr extension = imghdr.what(file_name, decoded_file) extension = "jpg" if extension == "jpeg" else extension return extension def to_representation(self, instance): if instance.name: return(settings.BASE_URL+reverse('download', args=[instance.name])) else: return None In my serializer.py file I am using it like this: logo = Base64ImageField(max_length=None, use_url=True, required=False, allow_null=True, allow_empty_file=True) Lets assume a logo has already been saved and now I am deleting it, I want to send an empty string. Unfortunately this is always ending up in an error message: The submitted file is empty. I am thankful for any clue. -
Delete an object in django by passing two id parameters by ajax call
When I try to delete an object by ajax call both ID's are not passing to url Am getting url like 127.0.0:8000/delete// urls.py path('delete/<int:a_id>/<int:b_id>',views.delete,name="delete") views.py def delete(request,a_id,b_id): obj=Table.objects.get(a_id=a_id,b_id=b_id) obj.delete() return render(request,"delete.html") delete.html <input type="hidden" id="a_id" data-value="{{obj.a_id}}"> <input type="hidden" id="b_id" data-value="{{obj.b_id}}"> script.js var a_id=$("#a_id").data("value"); var b_id=$("#b_id").data("value"); #some code $.ajax({ url:'delete/'+ a_id +'/' + b_id, #some code }); -
How to serialize large query set and write it to json?
Django 3.2.10, python 3.9 I have a QuerySet of 100 000 users. I need to serialize them and write into json file. queryset = Users.objects.all() # 100 000 users with open('output.json', 'w') as f: serializer = MySerializer(queryset, many=True) dump(serializer.data, f) I tried a .iterator() method, but I didn't understand how it should work. Also I tried next, but it is to slow. queryset = Users.objects.all() # 100 000 users with open('output.json', 'w') as f: for user in queryset: serializer = MySerializer(user) dump(serializer.data, f) -
DRF: Changing a value based on related model
I want to set a value into a field, which depends on another field from another model. I'm having a model CollectionObject and Transaction, those have a many-to-many relationship. My code looks like this: collectionobject/model.py: from django.db import models from collectingevent.models import CollectingEvent # Create your models here. ## Collection Object class CollectionObject(models.Model): ID = models.IntegerField(primary_key=True, editable=False) inventory_number = models.CharField(max_length=500) remarks = models.CharField(max_length=500) collecting_event = models.ForeignKey(CollectingEvent, related_name='collection_object', on_delete=models.DO_NOTHING) # many-to-1 class Meta: #ordering = ['pk'] db_table = 'collection_object' transaction/models.py: from django.db import models from collectionobject.models import CollectionObject ## Transaction class Transaction(models.Model): class TransactionType(models.TextChoices): LOAN = 'loan', DIGITIZATION = 'digitization', MOVEMENT = 'movement', RESAMPLING = 'resampling' ID = models.IntegerField(primary_key=True, unique=True, editable=False) collection_object_ID = models.ManyToManyField(CollectionObject, related_name='status')#, on_delete=models.DO_NOTHING)#CollectionObject, related_name='transaction')#, on_delete=models.DO_NOTHING) # many-to-many transaction_type = models.CharField(max_length=500) # TODO: here choices transaction_date = models.DateTimeField() remarks = models.CharField(max_length=500) class Meta: db_table = 'transaction' collectionobject/serializer.py: from rest_framework import serializers from .models import * from collectingevent.models import CollectingEvent from transaction.serializers import TransactionSerializer class CollectionObjectSerializer(serializers.ModelSerializer): # many-to-1 collecting_event = serializers.PrimaryKeyRelatedField(queryset=CollectingEvent.objects.all(), many=False) # 1-to-many determination = serializers.PrimaryKeyRelatedField(many=True, read_only=True) # transaction available = serializers.BooleanField(default=True) status = TransactionSerializer(many=True) class Meta: model = CollectionObject #fields = "__all__" fields = ( 'ID', 'inventory_number', 'available', 'status', 'remarks', 'collecting_event', 'determination', ) And transaction/serializer.py: from rest_framework import … -
ValueError: invalid literal for int() with base 10: '' only on Windows [closed]
I'm getting this error on Windows 10 native Python 3.8 + Django 2.2.7 setup. Doesn't throw any error in Docker or VirtualBox setup. ValueError: invalid literal for int() with base 10: '' -
django user queryset to profile queryset
I am trying to convert a query set to one to one related query set. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) one user must have one profile in the database. from django.contrib.auth.models import User us = User.objects.all() # is there a way t o convert user query set to profile query set? PS: I need profiles to be a query set instead of a list to perform future functioning. I have read the query set api reference and tried prefetch_related but did not work. I will be very glad with your help. -
How to make FK field in Django Admin not a link?
So...I am trying to alter the highlighted field as visible in the attached snip, in order to make it such it's not a link (does not redirect to the /change form - link visible in the lower part of the snip). The aforementioned field is a PK in another table and a FK in this table. And the end result would be that the field can be edited and is visible as a link for the users with the is_superuser flag and not editable and visible only as a string for the users that have the is_staff flag. I was already here and down the rabbit whole. Using readonly_fields makes the field uneditable, which is good, but does not remove the link. From the info that I found until now, it would seem that setting the list_display_links() to None does not work for the add/change forms that come out of the box with Django and it can only be used in the general list/table templates that show the model elements/entries/records from the db. Looking forward to getting some help if possible. Thank you. snip with the current behavior -
Django Admin, show inline based on slug
Have the following models class FootballWebsite(models.Model): """Football service website.""" url = models.URLField, unique=True) #football service id = models.CharField(primary_key=True, #is this domain blocked blocked = models.BooleanField(default=False) #is it online or offline online = models.BooleanField(default=False) updated = models.DateTimeField(auto_now=True, auto_now_add=True) sub_categories = models.ForeignKey(SubCategory, default=1) referral = models.TextField(blank=True) mirror = models.ForeignKey('FootballWebsite', blank=True, null=True) rank = models.PositiveIntegerField(default=0, blank=True, null=True) screenshot = models.BooleanField(default=False) class Meta: """Meta class.""" app_label = 'ahmia' def __unicode__(self): return u'%s' % (self.url) """The datetime when the football service was last seen online""" try: return self.footballwebsitestatus_set.filter(online=True).latest('time').time except FootballWebsiteStatus.DoesNotExist: return None class FootballWebsiteDescription(models.Model): """Football service website description.""" about = models.ForeignKey(Footballebsite) title = models.TextField(blank=True, null=True) keywords = models.TextField(blank=True, null=True) description = models.TextField(blank=True, null=True) relation = models.URLField(blank=True, null=True) subject = models.TextField(blank=True, null=True) type = models.TextField(blank=True, null=True) updated = models.DateTimeField(auto_now=True, auto_now_add=True) language = models.TextField(null=True, blank=True) contactInformation = models.TextField(null=True, blank=True) officialInfo = models.BooleanField(default=False) slug = AutoSlugField(populate_from=['title'], allow_duplicates=True, null=True) class Meta: """Meta class.""" app_label = 'ahmia' def __unicode__(self): return unicode(self.about.url) def save(self, *args, **kwargs): self.slug = slugify(self.title) super(FootballebsiteDescription, self).save(*args, **kwargs) def __unicode__(self): return u'%s' % (self.title) I have a huge amount of links, and i would like to bulk assign them into a category or mark them as blocked based on identical title slug. Managed to at least get … -
Django ORM if subquery
Is it possible in Django ORM use CASE with subquery? I want to change my query string if subquery gives me exact value. something like this subq = NetData.objects.filter(port=OuterRef('abc')).values('value') query_string = Sometable.objects.annotate(another_value=Case (When(Subquery(subq) = 'value', then = Value('123')), default=Value('123'))).filter(**finder) -
Aggregate tag names in Django Taggit
I am using the django taggit library. I have a Queryset that lists objects, which have a few tags attached to each object. How to get them all in one query? While I know how to get tags for each objects on model level, I haven't found a way to do so at Queryset level. How to get all objects tags in Queryset in the same query? Something like Book.objects.filter(year=2020).values('bookname', 'published_at', 'tag_names_list')[:] -
Gmail less secure app access is no longer available I am getting errors
I am sending mail using django as EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = "ali412514n@gmail.com" EMAIL_HOST_PASSWORD = env("GMAIL_PASSWORD") now that google turned off less secure app, I am getting errors. any solutions? -
Django User specific page
I m creating a Leave Web Application. I want to show each user's leave status according to the user who is logged in. from django.db import models from django.contrib.auth.models import User types_of_leaves = ( ('Sick Leave', 'Sick Leave'), ('Earned Leave', 'Earned Leave'), ('Annual Leave', 'Annual Leave'), ) # Create your models here. class LeaveApp(models.Model): authuser = models.ForeignKey(User, on_delete=models.CASCADE) fdate = models.DateField() tdate=models.DateField() type_of_leave=models.CharField(max_length=20 ,choices =types_of_leaves, default = "" ) reason = models.CharField(max_length=500) def __str__(self): return self.reason class Sick_leave(models.Model): leave=models.CharField(max_length = 40) def __str__(self): return self.leave