Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to remove white space within an html page
It automatically generates this "empty space" for me and I can't figure out how to remove it. This is the code I wrote in my file: HTML CODE: <div class="btn my-btnmenu btn-danger"> <i class="bi bi-bag"></i> </div> CSS CODE: .my-btnmenu { padding: .325rem .60rem; border-radius: 1.5rem; } .btn-danger { color: #fff; background-color: #dc3545; border-color: #dc3545; } and this is the image of the element inspection generated by my browser: -
why do we need get_absolute_url() in Django?
Can Anyone explain me in simple terms why do we need get_absolute_url() method in django? what is the purpose of defining get_absolute_url() in our django models? -
Pulling data from an existing database ( DJANGO // PYTHON )
I am trying to create a Web App that handles account data and prints said data to account statements and age analysis' The data will need to be fetched from an existing Sage Evolution database and printed to a web page through Django I have had a look at the Django documentation, however, the inspectdb function it gives does not give too much information on how to fetch data through a database IP address. Does anyone have a code example/tutorial on how to fetch this data through an IP address, almost with the same procedure as the below .BAT code import pymssql user = '[User ]' password = '[Password]' server = '[IP]' #username: [Username]_dev_ro #password: [Password] #database name: DB_Name databaseName = 'DB_Name' conn = pymssql.connect(server, user, password, databaseName) cursor = conn.cursor(as_dict=True) cursor.execute('SELECT top 10 * FROM [DB_Name].[dbo].[_etblGLAccountTypes]') for row in cursor: print(row) conn.close() -
drf filter by multiple ManyToManyField ids
Here is my models class Mediums(models.Model): medium_name = models.CharField(max_length=255) class Artwork(models.Model): title = models.CharField(max_length=255, blank=True, null=True) mediums = models.ManyToManyField(Mediums, blank=True, related_name="artwork") class Meta: db_table = 'artwork' I am using django-reft-framework . How can i fetch artwork by filtering multiple medium_id. I checked drf doc could not find option to filter ManyToManyField Pse take a look -
Handle permission cache in django user model
I stumbled upon a weird behaviour: I add a permission to a user object but the permission check fails. permission = Permission.objects.get_by_natural_key(app_label='myapp', codename='my_codename', model='mymodel') user.user_permissions.add(permission) user.has_permission('myapp.my_codename') # this is False! I found some posts about user permission caching here and here and the solution seems to be to completely reload the object from the database. # Request new instance of User user = get_object_or_404(pk=user_id) # Now note how the permissions have been updated user.has_perms('myapp.my_codename') # now it's True This seems really overkill for me and very un-django-like. Is there really no way to either clear the permission cache oder reload the foreign keys like you can do for an object with refresh_from_db()? Thanks in advance! Ronny -
Django - Return a list of primary keys with another attribute of the entity it's referencing
I have this FollowUser and User model below and there's a URL that gets a list of people the user is following (followees). I'd like to return a list of the followees (A User model) that has their UUID and the followees username. How can I do this in a fast and efficient way? models.py class User(AbstractBaseModel): username = models.CharField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(max_length=255, unique=True, primary_key=True) class FollowUser(AbstractSimpleModel): follower_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follower_following") followee_id = models.OneToOneField(User, on_delete=models.CASCADE, related_name="followee_followed_by") views.py def get_followees(request, follower_id): try: followees = FollowUser.objects.filter(follower_id=follower_id).values_list('followee_id', flat=True) data = dict(followee_ids=list(followees)) return JsonResponse(data, status=status.HTTP_200_OK) except FollowUser.DoesNotExist: return Response(dict(error=f'follower id: {follower_id} does not exist'), status=status.HTTP_400_BAD_REQUEST) -
How to get cookies (basically I need jwt token) in Ember.js which was set in Django?
Django Rest Framework class LoginView(APIView): password = request.data['password'] user = User.objects.filter(email=request.data['email']).first() if user is None: return Response({ 'success': False, 'message': 'Username or password is invalid', 'errors': 'Username or password is invalid', }, status=status.HTTP_401_UNAUTHORIZED) if not user.check_password(password): return Response({ 'success': False, 'message': 'Username or password is invalid', 'errors': {'username-or-password': ['Username or password is invalid']}, }, status=status.HTTP_401_UNAUTHORIZED) payload = { 'id': user.id, 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload, 'secret', algorithm='HS256') response = Response() response.set_cookie(key='token', value=token, httponly=True) response.data = { 'success': True, 'data': { 'token': token } } return response Here I send token in response data and also set token in cookies. How can I get/receive/retrieve token from cookies in Ember.js? -
Django admin - add extra fields using ModelForm of another model
Is it possible to add extra fields in Django Admin using a ModelForm of another model? Here my models: class ModelOne(Model): field_1_1 = models.SmallIntegerField() field_1_2 = models.ForeignKey(AnotherMyModel) field_1_3 = models.BooleanField(default=True) field_1_4 = models.ManyToManyField(to="TestModel", through="ModelTwo") class ModelTwo(Model): field_2_1 = models.ForeignKey(MyModel, on_delete=models.CASCADE) field_2_2 = models.ForeignKey(ModelOne, on_delete=models.CASCADE) field_2_3 = models.BooleanField(default=True) And the admin looks like: class ModelOneAdmin(admin.TabularInline): model = ModelOne form = forms.ModelTwoForm fields = ('field_1_1', 'field_1_2', 'field_1_3', 'field_2_1', 'field_2_3') Here the form instead: class ModelTwoForm(ModelForm): class Meta: model = ModelTwo fields = "__all__" This code raises the following error: FieldError: Unknown field(s) (field_2_1) specified for ModelOneAdmin I know that this is the case of the inline pattern, but i cannot use it becasue ModelOneAdmin is already inside a inline model (and i don't want to include extra python package to achieve this). Is there a way to fix this problem and achieve this goal? (Working with Python2.7 and Django 1.11) -
Django to allow to upload multiple files for a single record
I am having a requirement in my django application, where user will fill a form with few fields, which also includes the attachments field, my requirement is that attachments should accept multiple files , but these files should be tagged to single record, but now it's creating multiple rows in table based on number of attachments, please help. Thanks in advance -
Deploying with docker
I am new to deploying with docker. Actually, I am running my django app in my computer inside docker container, and it is running successfully on port localhost:8080. Then I pulled the code to remote server and started docker-compose up, and app is running successfully there as well. What I want to ask is that, how can I see the app with the help of ip adress of the server? For example, if the ip adress is 123.45.67.89 I think the app should be running in 123.45.67.89:8080 but it does not run there. How can I access to the app running in container in remote server? P.S. I have not used nginx, should I use it? -
IntegrityError at /create_invoice NOT NULL constraint failed: invoiceAPI_invoice.buyer_id
I am trying to create a invoice which has two foreign keys seller, and buyer and one many to many to field for items. I have create serializer for seller, buyer, and items and nested serialzer for invoice and when I am creating the invoice I am getting the error IntegrityError at /create_invoice NOT NULL constraint failed: invoiceAPI_invoice.buyer_id. data which I have passed don't have the id in that. Because I don't want to pass id through JSON, could it is possible that Django create the primary key for all the models. This is my serializers.py file class SellerSerializer(serializers.ModelSerializer): class Meta: model = Seller fields = ('__all__') class BuyerSerializer(serializers.ModelSerializer): class Meta: model = Buyer fields = ('__all__') class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('name', 'price', 'quantity', 'tax') class InvoiceSerializer(serializers.ModelSerializer): seller = SellerSerializer(many=False, read_only=True) buyer = BuyerSerializer(many=False, read_only=True) items = ItemSerializer(many=True, read_only=True) class Meta: model = Invoice fields = ('seller', 'buyer', 'items', 'date') def create(self, validated_data): seller_data = validated_data.pop('seller') buyer_data = validated_data.pop('buyer') items_data = validated_data.pop('items') seller = Seller.objects.create(**seller_data) buyer = Buyer.objects.create(**buyer_data) items = [] for item_data in items_data: items.append(Item.objects.create(**item_data)) invoice = Invoice.objects.create(seller=seller, buyer = buyer, item=items) return invoice``` This is the models.py file. **models.py** ``` class Seller(models.Model): id … -
Why is my django core.serializers so slow
I have my a serializer from core.serializers in my django view. It does work, but it sometimes takes over 1 minute to show my results table. Any ideas how to get it faster? # views.py from django.core import serializers def search_institution(request): form = SearchInstitutionsForm() qs = Institution.objects.all() if request.method == "POST": form = SearchInstitutionsForm(request.POST) if form.is_valid(): cd = form.cleaned_data if cd['name']: qs = Institution.objects.filter(name__contains=cd['name']) print(f"Before requesting from db: {datetime.now()}") print(f"After requesting from db, before serializing: {datetime.now()}") context = { "result_data": SafeString(serializers.serialize("json", qs)), 'form': form } print(f"After serializing, before rendering: {datetime.now()}") return render(request, "landing/result_table.html", context) else: context = { "form": SearchInstitutionsForm } return render(request, "stakeholders/institution_form.html", context) -
Unable to implement Azure Adfs authentication in Django
I have been trying to use the authentication system of azure and for that I have followed the below link https://django-auth-adfs.readthedocs.io/en/latest/azure_ad_config_guide.html#step-1-register-a-backend-application but Im kinda of stuck and don't know where the problem lies . I keep getting the below error message. For any more information please ask in comment I will try to provide it. Any help or guidance will be a great help -
Need to Fetch specific foreign key object product from database in Django
Hi everyone I am new at Django and working on e-commerce site. I create a model name category and pass it to model shop by using foreign key. In Category model I have category Sale and i want to fetch all products that have category sale in my landing page and rest of us in shop page. Any one please help me how I do it? My model.py code is: class category(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class shop(models.Model): s_id = models.AutoField(primary_key=True) s_name = models.CharField(max_length=50) s_category = models.ForeignKey(category, on_delete= models.CASCADE) s_artical_no = models.IntegerField(default=0) View.py: def index(request): prod = shop.objects.get(s_category = 4) params = {'prod': prod} return render(request, "main/index.html", params ) -
How Can I get related instance in formfield_for_dbfield method of TabularInline class of django admin?
Is it possible to get inline instance in formfield_for_dbfield method of TabularInline class in django admin? -
Can't use minutes from DateTimeField in django templates
M or m is month. How can i use |date so it gives me minutes. {{ client.time_of_receipt|date:"M, d h" }} -
Unable to get images in list in Django views.py context, Throws List AttributeError
I am using below code to get a list of all image and then display it: def index(request): data = cos.list_objects(Bucket='pixmedia') di = data['Contents'] endpoint="https://s3.us.cloud-object-storage.XXXXX.cloud/XXX/" #print(di) image_list=[] for key in di: print("Key is--->",key['Key']) res=key['Key'] res=endpoint + res print("Res is ---->",res) #context = { # 'image': res, #} image_list=image_list.append(res) print("Image List is",image_list) context = { {'image_list': image_list,} } return render(request, "index.html", context) But, i am getting below error on launching 127.0.0.1:8000: image_list=image_list.append(res) AttributeError: 'NoneType' object has no attribute 'append'. Please Help. -
How should I pass a raw query response to a Serializer class?
I am trying to fetch data using raw sql query but I am facing issues when I am trying to pass the raw sql response to the Serializer class. Serializer class User_Serializer(serializers.ModelSerializer): class Meta: model = Users fields = '__all__' View class UserView(APIView): def get(self, request, emailId, format=None): with connection.cursor() as cursor: cursor.execute("SELECT * FROM users") resRow = cursor.fetchone() serializerResponse = User_Serializer(resRow) return Response(serializerResponse.data) I realise that the Serializer class cannot work with the ModelSerialzier class in this scenerio. How should I build my Serializer considering the fact that I need to post and save data to the concerned model using this Serializer class. -
How to Redirect URLs to a certain URL Django Regex
In my URLs.py, I'm setting my URL like this url(r'^mobile/$', views.mobile, name='mobile') Navigating to localhost:8000/mobile works as expected but if typed in the URL: localhost:8000/mobile/hello/world/234234hjhf8sc3 it should redirect to localhost:8000/mobile however this does not happen because my regex is incorrect (I'm not sure) How could I do this/what is the correct regex to do this? Another example would be localhost:8000/mobile/send/help/as792lp should redirect to localhost:8000/mobile -
How do I prevent Django Channels routing error?
The route for the Django Channels project I'm building isn't working and at this point, I can't tell why. Everything seems fine to me yet I'm getting the same error from the server over and over again. I know there's something I'm missing, but what could that be?. ASG Setting import os from channels.routing import ProtocolTypeRouter from channels.routing import URLRouter from channels.auth import AuthMiddlewareStack from django.core.asgi import get_asgi_application from chat import routing os.environ.setdefault("DJANGO_SETTINGS_MODULE", "base_app.settings") # Handles routing protocols for Django Channels application = ProtocolTypeRouter( { "http": get_asgi_application(), # Points root routing to chat/routing.py "websocket": AuthMiddlewareStack(URLRouter(routing.websocket_urlpatterns)), } ) Channels route # chat/routing.py from django.urls import re_path, path from .consumer import ChatConsumer websocket_urlpatterns = [ re_path(r"ws/chat/(?P<chat_id>\d+)/$", ChatConsumer.as_asgi()), ] Channels consumer # chat/consumer.py import json from django.contrib.auth import get_user_model from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync from chat.models import Message from chat.views import last_10_messages # Instantiate user model User = get_user_model() class ChatConsumer(WebsocketConsumer): """Chat consumer class process data sent from WebSocket routing""" # === Utility === <---------------- Scroll down to see main Channel's methods def fetch_messages(self, data): """Fetch last messages from database""" messages = last_10_messages(data["chatID"]) serialized_messages = { "command": "fetch_messages", "messages": self.messages_to_json(messages), } # Send fetched messages self.send_message(message=serialized_messages) def new_message(self, data): """Stores … -
DRF & React: "login with google" doesn't create any Social Account in database
I don't know what I'm doing. I'm trying to Login with Google from React app. So I've created a project in Google cloud platform, set Authorized JavaScript origins url: http://localhost:3000 and Authorized redirect URIs http://127.0.0.1:8000/accounts/google/login/callback/ and got Clint Id and Secret key. Then I've created a Social application from Django Admin site with these ID and Key. then I write this code: settings.py: INSTALLED_APPS = [ 'myapp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', #google ] SITE_ID = 1 REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_FILTER_BACKENDS':['django_filters.rest_framework.DjangoFilterBackend'], } urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), path('api/rest-auth/', include('rest_auth.urls')), path('api/rest-auth/registration/', include('rest_auth.registration.urls')), path('accounts/', include('allauth.urls')), in Reactjs: //...code responseGoogle = (response) => { console.log(response); } //..code <GoogleLogin clientId="634453711672-3lf3sk6g4dl74q428n14jc4n6n592d99.apps.googleusercontent.com" buttonText="Login" onSuccess={this.responseGoogle} onFailure={this.responseGoogle} cookiePolicy={'single_host_origin'} /> when i click this Login button, then select my gmail account, it console log an object. kx{Os: mx {$R: "**************", Ne: "Asif Biswas", ET: "Asif", GR: "Biswas",....}...}. but doesn't create any Social Account in database. My goal is: click the Login button > authenticate user > Create Social account and application token (in database). any suggestion? -
How to filter in django using condition
I have 4 file uploading fields (only one file is mandatory for uploading) and 4 status corresponding to each file. There is a filter in front end called 'Completed' to filter the dashboard. How to filter records which are completed (Completed status only if there is a file and its status need to be True, if 4 file are uploaded then all of the corresponding status of each file need to be True to consider as completed.No matter the person uploaded 1 or 4 files based on the files uploaded the corresponding file status need to be true. Table column example file1 | file1_status | file2 | file2_status | file3 | file3_status | file4 | file4_status -
django bulk insert using value from parent table instead of ID
I have 2 models -- AssetType and Asset (both have IDs and Asset has a foreign key point to AssetType) I want to bulk insert rows in the Asset table using Asset Type NAME, instead of ID. I tried to do df.to_sql() but it can't work because my df contains "asset type name" instead of asset type id. Is there a way to convert it easily? Expected Output The asset type table looks like this: id | name | description 1 | at1 | desc1 The Asset table should look like this asset_name | display_name | asset_type_id n1 | d1 | 1 The dataframe I want to insert in the Asset table looks like this (Input): asset_name | display_name | asset_type_name n1 | d1 | at1 So, I am passing in at1 in my dataframe but want to insert it as "id=1" for asset type. Is this possible in django? My models are: class AssetType(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=80, unique=True) description = models.CharField(max_length=80) class Asset(models.Model): asset_type = models.ForeignKey(AssetType, on_delete=models.CASCADE) asset_name = models.CharField(max_length=80) display_name = models.CharField(max_length=80) My serializer looks like this: class AssetTypeSerializer(serializers.ModelSerializer): class Meta: model = AssetType fields = "__all__" class AssetSerializer(serializers.ModelSerializer): asset_type_name = serializers.CharField(source='asset_type.name') class Meta: model … -
how to insert a floating value as binary numbers and retrieve as floating value in MySQL
how to insert a floating value as binary numbers and retrieve as floating value in MySQL, python, Django like I have a floating value 2000.252 I need store it on MySQL column as binary 010101 or string 'sddg121fg' or encryption 'dgdfggdfgttzzd' but when I retrieve this value it will be 2000.252 -
How to Use Django Queryset update() function with foreign key field cited by F()?
I want to make a simple query: with transaction.atomic(): Account.objects.select_for_update().filter(payments__status='PENDING', payments__created_date__lt=timezone.now()-timedelta(days=14)).update(balance=F('balance')+Sum(F('payments__amount') - F('payments__payment_fee__fee_amount')), payments__status='COMPLETED') It turned out it wasn't simple at all. I've tried Subquery but alternatively get "Joined field references are not permitted in this query" or "FOR UPDATE is not allowed with GROUP BY clause" Subquery doesn't work because aggregation doesn't work with select_for_update() locks. F() doesn't work because it is referencing foreign key fields... What's the best way to make this query work? Any idea? I am using postgresql behind the ORM.