Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django filter by empty string or empty string made of spaces
I would like to filter by a given name that is either an empty string or a string of only blank spaces For example, I have these names name1 = '' name2 = ' ' name3 = ' ' name4 = 'john door' I would like the query to return all values without characters but made of only spaces which in this case name 1, 2 and 3 Here is my initial attempt but I think it can be made more accurate. missing_names = Loan.objects.filter( Q(Q(name__startswith=' ') & Q(name__endswith=' ')) | Q(name__exact='') ) -
In my django project wanted to show specific data on bootstrap modal as per project grid clicking but it's showing first grid data only
Here's my Model View Template enter image description here -
Calculation is producing wrong result in annotate using Django ORM
I am using this query to calculate the total amount, but also deducting discount and adding Sales tax. But in second annotate I am not getting correct results, as you can see the query is straight forward to calculate sales tax (price + price * tax_percentage / 100). After struggling for hours, I couldn't figure it out, Am I doing something wrong ? Order.objects.filter(customer__zone__distribution=get_user_distribution(request.user.id)) .annotate(trade_price=ExpressionWrapper( Sum(F('items__trade_price') * ExpressionWrapper(0.01 * (100 - F('items__discount__discount')), output_field=DecimalField()) * F('items__quantity') ) , output_field=DecimalField() ) ).annotate(total_price=F('trade_price') + F('trade_price') * Sum(F('items__sales_tax__percentage') / 100)) -
Django Form Date Input Field Not Showing Errors
I have a form on a registration page that requires a date to be entered, along with a few other fields. If the user enters non-valid information into the date field (like a string) and submits the form, Django rejects the form as non-valid, but I don't get any error messages on the page - But for the other fields on the form, I do get error messages (ex: Passwords Don't Match, User Already Registered, etc). Here is what the form looks like: Link to image of registration form Here is my forms.py file - I'm using two classes to create the form on the registration page: from django import forms from users.models import Profile from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class CustomUserCreationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta(UserCreationForm.Meta): model = User #fields = UserCreationForm.Meta.fields + ("email",) fields = ['username', 'email', 'password1', 'password2'] class EmployeeForm(forms.ModelForm): hireDate = forms.DateField( required=False, error_messages={'required': 'Please enter a valid date'}, input_formats=[ '%Y-%m-%d', # '2006-10-25' '%m/%d/%Y', # '10/25/2006' '%m/%d/%y' ]) # '10/25/06') class Meta: model = Profile fields = ['hireDate', 'employeeNumber'] Here is the models.py field with the model for the profile: from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class … -
SSE streaming api call more the 50 at a time in django
I have created a simple SSE streaming URL in Django(3.2.13). def index(request): def chunks(): c = 0 while True: c += 1 yield "\ndata: {}\n\n".format(c) time.sleep(1) return StreamingHttpResponse(chunks(), content_type='text/event-stream') my query is when I run this on a single tab on the browser it frequently. but when I run more than 6 tabs it does not work on the 7th tab and more, so how to create an SSE streaming URL that runs more than 50 tabs at a time.