Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django exclude users with same email
I have 2 user models in my django project. So it set up like this: UserModel1 has 500 users with email and UserModel2 has 2000 users with email. And 300 users are both registered inn UserModel1 and UserModel2. So that means the two models share 300 users. UserModel1 has 200 excluding the users they both have in common, and UserModel2 has 1700 users exluded the users they have in common. I wanted to make a query that gets all the useres from UserModel2 that are not registered in UserModel1. So i want to get the 1700 useres they dont have in common. After som research i landed on this: from django.db.models import Q not_matching = UserModel2.objects.filter(~Q((email__in=UserModel1.objects.values('email'))) but no luck, any ideas? -
DJANGO - How to display multiple database rows in one row in view
I'm working with a 1-N relationship (1 ticket has N messages), in the admin view I'm trying to pull things from the database, but the N msg's related to ticket X, are coming as N lines (one line for each msg from ticket X) in the view (I display it in a table), I need the N messages to be passed in one line only, below is an example of how this is happening and how I need it to be. Current output: | Ticket id | Msg id | Content | Status | |:---------:|:-------:|:-----------------:|:------:| | 1 | 1 | msg 1 of ticket 1 | Open | | 2 | 2 | msg 1 of ticket 2 | Closed | | 2 | 3 | msg 2 of ticket 2 | Closed | | 3 | 4 | ticket 3 - msg 1 | Open | | 4 | 5 | msg 1 of ticket 2 | Closed | | 3 | 6 | ticket 3 - msg 2 | Open | How I need it to be: | Ticket id | Msg id | Content | Status | |:---------:|:-------:|:------------------------------------:|:------:| | 1 | 1 | msg 1 of ticket … -
Remove of alphabet letters from Charfield Django
How I can remove letters from charfield. The charfield is already implemented now i have to remove the letters how i should do that. source[enter image description here][1] = models.CharField(max_length=1, help_text=_("A, B, C, ...")) -
Python Setup on NameCheap showing Error 503. Service Unavailable
I am new to NameCheap and I need help deploying a Django application. I just tried installing python on Namecheap's Cpanel using Python 3.7.12 with the desired Application URL, but I get the Error 503. Service Unavailable when I visit the Application URL after creating the python app. From the resources I have seen, I am supposed to get a python signification that the python app works and not an error. Thanks in advance. python app setup on Namecheap's Cpanel error page when i visit the application's Url -
How to display the keys of a python dictionary as HTML table headers and values of each key as a row under that table header?
I'm currently working in a django project in which I do some data analysis using pandas library and want to display the data (which is converted into a dictionary) as a HTML table. dictionary that I want to display: my_dict = { 'id': [1, 2, 3, 4, 5], 'product_name': [product1, product2, product3, product4, product5], 'value': [200, 400, 600, 800, 1000], 'available_qty': [1, 2, 3, 2, 4] } I want to display the above dictionary like this table in django template. id product_name value available_qty 1 product1 200 1 2 product2 400 2 3 product3 600 3 4 product4 800 2 5 product5 1000 4 I have tried the below code. <table> <thead><h2><b>my dictionary</b></h2></thead> {% for key, values in my_dict.items %} <th><b>{{ key }}</b></th> {% for value in values %} <tr> {{value}} </tr> {% endfor %} {% endfor %} </table> I get the results as, (There is some space between each row displayed in the table) -
How to allow REST filters for non-DB fields in django
My problem is this: I'm working on a django project that has a lot of DB tables representing many different objects. This project has a GUI interface that is mostly a table that is a rough representation of each DB table. This table I got from google images can be used as an example Unlike this table, mine has filters on top of each column so for example you can type a name you're looking for and it will only show relevant rows. The problem starts here - Not all columns in the GUI are really columns in the DB. For example let's say the "Location" column isn't a DB column, but a property on the django model like this @property def location(self): return f"{self.city}, {self.state}" So obviously sending to my django backend this URL won't work just like that https://mywebsite/api/people/?location__icontains=Chicago My workaround for this is going to the View and overriding filter_queryset to handle this specific case . Something like this: def filter_queryset(self, queryset): if "location__icontains" in self.request.query_params: filter = self.request.query_params["location__icontains"] q = Q(city__icontains=filter ) | Q(state__icontains=filter) queryset = queryset.filter(q) The issue is that this doesn't even really cover all cases, it only works if the user filter input … -
Django: Is a super user without a password safe?
I'm trying to create an interactive website with Django for a chat bot. I have a model that stores the chat logs, ChatLogs. It has two fields: sender and message. sender, as the name might suggest, is a foreign key denoting who the sender of message is. It can be either the bot or a user. Here's how I have it set up: class ChatLogs(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE) message = models.CharField(max_length=255) Since the sender can be the bot or a user, I thought to create a record in the User table for the bot: $ python3 manage.py shell >>> from django.contrib.auth.models import User >>> User.objects.create_user("Bot") I created the user without a password because, according to the Django documentation for createsuperuser, an account created as such can't be used to login. Which I think is a secure way to handle this. My question is, is there any reason I should not be doing this? From the Django documentation (for createsuperuser): When run non-interactively, you can provide a password by setting the DJANGO_SUPERUSER_PASSWORD environment variable. Otherwise, no password will be set, and the superuser account will not be able to log in until a password has been manually set for it. -
How to format Error message in Json Django
So, I want to format error messages in a json format instead of the HTML it is coming in. models.py # AUTH = Regex specified class Player(models.Model): CHEERING_MODE_CHOICES = [ (1, "Before FFPQ"), (2, "After FFPQ"), (3, "In exercise"), ] SEX = [ (1, "Male"), (2, "Female"), ] FFPQ_READY = [("Yes", "YES"), ("No", "NO")] auth = models.CharField( max_length=36, null=True, unique=True, validators=[AUTH, MinLengthValidator(36)], ) area = models.ForeignKey( "master.UserType", on_delete=models.PROTECT, validators=[MinValueValidator(1)] ) serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' The error format I want { "type": "validation_error", "code": "invalid_input", "detail": "Crossing the maximum length", "attr": "auth" } It is coming in HTML format -
How it is possible to implement full-fledged search in several models and in several fields of each model in Django-based web-app?
I'm working on an admin panel for a site with courses And I need to implement a search by users, plans, exercises, etc. Maybe there are ready-made modules for this? Of course, I found solutions for StackOverflow, but I don’t understand how to insert this data into the template later Btw , here is link for this solution: Django search fields in multiple models -
Change django-ckeditor UI language to Persian
I'm trying to change the UI language of django-ckeditor in Admin site to Persian which is an rtl language. I'm expecting to see the tooltip of toolbar icons in Persian and the editor area ready for RTL. One option of course is to change the LANGUAGE_CODE of my project to fa-ir but this will switch the whole Admin site to Persian with a - in my opinion - dull translation. So I study the documentation and make the following changes to my project: SETTINGS.PY MIDDLEWARE = [ ... 'django.middleware.locale.LocaleMiddleware', ... ] from django.utils.translation import gettext_lazy as _ LANGUAGES = [ ('en', _('English')), ('fa', -('Persian')), CKEDITOR CONFIG (INSIDE SETTINGS.PY): Add 'Language' to the toolbar -> It appears on the toolbar. Add fa:Persian:rtl and en:English to language_list -> I see them in the dropdown when I click on the Language toolbar. Still, The editor area is English and even when I switch the language to Persian nothing happens on the UI - but if I check the source code I see <span lang="fa" dir="rtl"> is added. That's good and useful but not what I need. I'm sure its possible to achieve what I want because I see it in action on CKEditor's … -
Django bulk_create not setting the field with choices
In my model.py file, I have basic and premium coupon like below. coupon_types = ( ("Basic", "basic"), ("Premium", "premium"), ) class Coupon(Stamp): ... type = models.CharField(choices=coupon_types, max_length=256, default=coupon_types[0], null=True, blank=True) In the code below, I am trying to create the coupon objects in the database class ClassName: ... # Some attributes and methods ... def __construct_initiator_object(self, **kwargs): objs = [ self.initiator( ... ... type=coupon_types[0] if self.coupon_type.lower() == 'basic' else coupon_types[1] ) for code in self.coupons ] return objs @transaction.atomic def __create__(self): objs = self.__construct_initiator_object() create_objs = Coupon.objects.bulk_create(objs) return create_objs My problem now is that whenever I call the create method, the bulk_create sets every other field but not the type field. I don't know if it's because I have the choices=coupon_types in the type field. Any help on how to overcome this? -
I am getting None as output, but I want output as 10, 20 30?
<select name="dropdown" method="post" enctype="multipart/form-data"> <option selected="selected" disabled>Objects on page:</option> <option value= 1 >10</option> <option value="20">20</option> <option value="30">30</option> <option value="40">40</option> <option value="50">50</option> </select> def dropdown(request): print(request.POST.get('dropdown')) return render(request, 'ndtgui/dropdown.html') The above one is my html file and below is view in django. Blockquote -
How to use upsert command in django for bulkupdate?
I need to update 1000's of rows each with differant values in timescale db. I found bulk update to do so. list = ModelClass.objects.filter(name = 'bar') obj_to_be_update = [] for obj in list: obj.name = "Dear "+obj.name obj_to_be_update.append(obj) ModelClass.objects.bulk_update(obj_to_be_update, ['name'], batch_size=1000) This takes alot of time to update and even atomic transaction took alot time to update in the db. Instead found upsert for timescale db which does execution faster. Any idea how to do it in django. https://docs.timescale.com/timescaledb/latest/how-to-guides/write-data/upsert/#upsert-functionality -
why docker-compose work and docker run doesn't
I have the following local.yml file version: '3' services: celery-worker-default: image: weapp_app:latest container_name: weapp_celery-worker-default command: celery worker -A WeApp -Q default -n default --loglevel=INFO env_file: - .env volumes: - .:/opt/python/current/app/ When I run docker-compose -f local.yml up celery-worker-default everything work great also running like docker-compose -f local.yml run celery-worker-default celery worker -A WeApp -Q default -n default --loglevel=INFO Everything run OK But If I try to execute with docker with the following command docker run -v "$(pwd):/opt/python/current/app/" -w /opt/python/current/app --env-file .env weapp_app:latest celery worker -A WeApp -Q default -n default --loglevel=INFO I get this error Error: Unable to load celery application. The module "WeApp was not found. I already try change $(pwd) for the local complete local path but I get the same error. In other way I try to pass all the environment value by command line with option -e and get the same error. I try without working directory in the docker options. I try opening a shell inside the container and execute the command, but the same error. -
django-ninja resolvers with access to request
I create an API with django-ninja. For one of the resolver-methods I need to access the request. Example: class ListingSchema(ModelSchema): playback_urls: AnyUrl ... def resolve_playback_urls(self, obj): return obj.get_playback(request) How can I access the request-object? (Where should I add the request to access it later?) -
Django recommend posts from the same user
How to do anological example on Django You need to show posts from the same creator, except which one is being watched now tasksPosts = [{ 'id': 123433, 'title': 'riddle' }, { 'id': 123333, 'title': 'test' }, { 'id': 723433, 'title': 'text' }, { 'id': 177733, 'title': 'text123' }] def get_additional_posts(): task = { 'id': 123433 } return list(filter(lambda post: post['id'] != task['id'], tasksPosts)) print(get_additional_posts()) models.py class Task(models.Model): user_info = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, name='userInfo') title = models.CharField(max_length=100) text = models.TextField(max_length=10000) -
How to create my own CLI like python scrapy/django command line does?
I'm trying to create my own program and execute it like if we are working using scrapy or django. For an example like the line below? scrapy shell <optional-url> django-admin startproject <project-name> -
New objects are made every time
I made a single function for register and login with mobile and otp. The register part is in the else part of the function, and the if part is the login function. Every time I log in with the already registered number, it makes a new object in the database, and I don't want that. I want to just update the otp part from when the number was registered in the database. views.py class RegistrationAPIView(APIView): permission_classes = (AllowAny,) serializer_class = ProfileSerializer def post(self, request): mobile = request.data['mobile'] data = Profile.objects.filter(mobile = mobile).first() if data: serializer = self.serializer_class(data=request.data) mobile = request.data['mobile'] if serializer.is_valid(raise_exception=True): instance = serializer.save() content = {'mobile': instance.mobile, 'otp': instance.otp} mobile = instance.mobile otp = instance.otp print("Success") send_otp(mobile,otp) return Response(content, status=status.HTTP_201_CREATED) else: return Response({"Error": "Login in Failed"}, status=status.HTTP_400_BAD_REQUEST) else: serializer = self.serializer_class(data=request.data) mobile = request.data['mobile'] if serializer.is_valid(raise_exception=True): instance = serializer.save() content = {'mobile': instance.mobile, 'otp': instance.otp} mobile = instance.mobile otp = instance.otp send_otp(mobile,otp) return Response(content, status=status.HTTP_201_CREATED) else: return Response({"Error": "Sign Up Failed"}, status=status.HTTP_400_BAD_REQUEST) serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['mobile'] def create(self, validated_data): instance = self.Meta.model(**validated_data) global totp secret = pyotp.random_base32() totp = pyotp.TOTP(secret, interval=300) otp = totp.now() instance.otp = str(random.randint(1000 , 9999)) instance.save() return … -
Django Serialization - Partial update on nested objects
Searched around for a few hours on this and I am surprised I couldn't find an answer but here it goes. Let's say I have the following models: class Mission(models.Model): mission_name = models.CharField(max_length=150) ... class Player(models.Model): player_name = models.CharField(max_length=150, unique = True) state = models.CharField(max_length=150) currentMission = models.ForeignKey(Mission,on_delete=models.SET_NULL, blank=True, null=True)) Objectives: When creating a mission, I would like to provide the players' names that are going to participate on this mission (Names are unique). That means, when mission is created, I have to update the currentMission field of each given player. (Players already exist when mission is created) When I try to GET a mission, I would like to see the names of the players that participate My attempt Class MissionSerializer(serializers.ModelSerializer): #This is to get a list of the players that participate in this mission players = PlayerSerializer(many=True, read_only=True) class Meta: model= Mission fields = ['mission_name','players'] def create(self,validated_data): mission = Mission.objects.create(**validated_data) # Notice that I get the "players" data from "self.initial_data" and not from validated_data # This is because validated_data does not have the "players" field, # (I guess because I didn't provide all the required fields on my request for the player. I just provided the players' names ) … -
Django query set filter reverse startswith on charfield
Image some kind of product-rule which has 2 conditions: name are equal sku's have partial match, starts with. The rule model looks like this: class CreateAndAssignRule(models.Model): name_equals = models.CharField(max_length=100) sku_starts_with = models.CharField(max_length=100 Now I want to fetch all of the rules with name Product 1 and match sku sku-b-292 class CreateAndAssignRuleQuerySet(QuerySet): def filter_by_name_and_sku(self, name, sku): # We're looking which of the rules have a matching name, and where the rule have a string which is the string of the sku provided. rules = self.filter(name_equals=name) approved_ids = [] for rule in rules: # We're looping through the rules to find out which of them has the beginnings of the sku. # a sku_starts_with field would contains value eg: 'sku-a' where as the search string would be the full sku 'sku-a-111'. We want to match 'sku-a-111' but not 'sku-b-222'. if sku.startswith(rule.sku_starts_with): approved.append(rule.id) return self.filter(id__in=approved_ids) although the above works, it's hardly efficient especially as the number of rule is starting to grow a lot. How can I resolve this with a queryset? Filtering on __startswith doesn't do the trick as it the reverse. -
Using Django DeleteView and getting a 404 after delete confirmation
After clicking on "confirm" in my organism_delete.html form, I used to be redirected back to the list of organisms (organism_list.html template) as specified in the view. But now I get a 404 error instead. Page not found (404) Request Method: GET Request URL: http://localhost:8000/library/organisms/ABC1233/delete/post?csrfmiddlewaretoken=Rdk575IEp5bbvrriJ1szlYNjmq8V1DvuYzNWEWz07s78IJSal9foHdkvxwcimIEp Using the URLconf defined in itslibrary.urls, Django tried these URL patterns, in this order: admin/ accounts/ [name='home'] library/ organisms/ [name='organism_list'] library/ organisms/new/ [name='organism_new'] library/ organisms/ [name='organism_detail'] library/ organisms//update/ [name='organism_update'] library/ organisms//delete/ [name='organism_delete'] ^media/(?P.*)$ The current path, library/organisms/ABC1233/delete/post, didn’t match any of these. Two things that stand out to me is first that the error says it's a GET request, not a POST as the form specifies. And second is why is it trying to get to .../delete/post...? It might be important to know that I changed my model and added "Primary Key = True" to a unique CharField, and I've been modifying the rest of the app to match that. It may not be related because I can list the organisms and I can get to the delete page, I just can't submit it. I don't know how to debug this, it seems to be hidden behind the Django magic, any guidance will be very appreciated. … -
Trigger multi-configuration jenkins' job remotely using python
I'm developping a django dashboard that trigger a multi-configurations job in jenkins remotely, I tried everything and i read the jenkinsapi documentation but in vain. Any one have an idea please? -
Django annotate with frequency
(django 3.2.12, python 3.9.3, MySQL 8.0.28) Imagine models like the following: class User(models.Model): email = models.EmailField(...) created_datetime = models.DatetimeField(...) class UserLog(models.Model): created_datetime = models.DatetimeField(...) user = models.ForeignKey('user.User' ...) login = models.BooleanField('Log in' ..) And the following query, destined to annotate each user in the queryset with the frequency of their logs(when log.login=True): users = User.objects.filter( Q(...) ).annotate( login_count=Count('userlog', filter=Q(userlog__login=True)), login_duration_over=Now() - F('created_datetime'), login_frequency=ExpressionWrapper( F('login_duration_over') / F('login_count'), output_field=models.DurationField() ), ) This results in a SQL error: (1064, "You have an error in your SQL syntax;) The generated SQL (fragment for login_frequency) looks like this: ( INTERVAL TIMESTAMPDIFF( MICROSECOND, `user_user`.`created_datetime`, CURRENT_TIMESTAMP ) MICROSECOND / ( COUNT( CASE WHEN `user_userlog`.`login` THEN `user_userlog`.`id` ELSE NULL END ) ) ) AS `login_frequency`, and MySQL does not seem to like it. A similar code works on SQLlite and, I am told on PG. What is wrong with the ExpressionWrapper on MySQL, any idea? -
request.META.get('HTTP_REFERER') isn't working when prefix_default_language=True
url = request.META.get('HTTP_REFERER') worked when prefix_default_language=False. But when I make prefix_default_language=True, it isn't getting anything. Help please. -
How to display the product of multiple models in a model using foreign key or something else
I want to display my product offers and monthly plans in the single model Theres products and monthly plan model class Monthlyplan(models.Model): ... name = models.CharField(max_length=220) class Product(models.Model): ... name = models.CharField(max_length=220) class Customers(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) monthly_plan = models.ForeignKey(Monthlyplan, on_delete=models.CASCADE) Packages = GenericForeignKey('product', 'frozen_food') error core.Customers.Packages: (contenttypes.E004) 'Customers.product' is not a ForeignKey to 'contenttypes.ContentType'. HINT: GenericForeignKeys must use a ForeignKey to 'contenttypes.ContentType' as the 'content_type' field.