Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to remove currently, change, clear from Form and still retain instance of UpdateView
I have a task at my internship program where I need to remove change and clear from my form filefield. What I don't get is they don't show up in the createview. As far as I understand both create and update use the same form, the template is the same, the only difference is update is passing an object. I tried from django.forms.widgets import FileInput class SomeForm(forms.Form): foofile = forms.FileField(widget=FileInput) in the form, but then I lost the initial value of the object in update totally. There were no widgets, but there was no file either, which is no good. So what needs to be done here? -
Django TemplateDoesNotExist at /meetups/
error when Django server is run directory installed apps for Django -
How can dropdown list beside search box this on django admin panel?
I want to search things by Dropdown list AND searched text in django model. How can i achieve this for perticular Model in DjangoAdmin section? -
Django Query How to compare field with _set filter condition?
I have following model class Reply(BaseModel): reply_to = models.OneToOneField( Review, on_delete=models.CASCADE, error_messages={'unique': 'Reply to this review already exists.'}) replied_by = models.ForeignKey(HotelUser, on_delete=models.CASCADE) Basically Review model is linked with foreign key with reservation class Review(BaseModel): reservation = models.ForeignKey(Reservation, on_delete=models.CASCADE) and My Reservation Model has Room as Foreign Key as class Reservation(BaseModel): room = models.ForeignKey(Room, on_delete=models.CASCADE) and Room is linked with Hotel in Foreign key class Room(BaseModel): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE) and I have certain staff model which have hotel as Foreign key in this way class Staff(BaseModel): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE) user = models.OneToOneField(HotelUser, on_delete=models.CASCADE) My problem is I want the replied by user which is basically ->hotel user lets say XYZ is Staff of `XYZ' hotel. I tried this in clean method: def clean(self): if not self.replied_by.reservation.room.hotel.staff_set.filter(user=replied_by) == self.replied_by: raiseError but there is no any change on restrication any help will be helpful. -
Local development Django static files coming from library directory rather than my project
I have a Django (3.1) app that I've set up to serve static files, that is, DEBUG = True . . . INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', . . . ] . . . STATIC_URL = '/static/' STATIC_ROOT = 'static/' But instead of serving files from the static directory of myapp, it's serving static files from /Library/Python/3.7/site-packages/django/contrib/admin/static/. I have tested this by adding files to both directories, ~/Projects/myapp/static/file-from-project.js /Library/Python/3.7/site-packages/django/contrib/admin/static/file-from-library.js and then python3 manage.py runserver with a template including the lines <script src="{% static 'file-from-project.js' %}"></script> <script src="{% static 'file-from-library.js' %}"></script> and file-from-library.js loads fine but I get a 404 for file-from-project.js. What am I doing wrong here? -
How to avoid redundant database queries while using serailizer validation and APIViews
There is situation where, in Django serializer, validation of a field needs to query the database for getting an object or a queryset. After successful validation, the APIView again requires to access the same object or query set. In such case how can we avoid duplicate queries? Should we just avoid the validation in the serializer and instead do it in the APIView? Or can we pass the fetched object or queryset to the validated_data attribute of the serializer, so that we can get it in the APIView? Or else, is there a better way? -
Is there any way to customize django-treebeard admin interface for separate dashboard?
Django-treebeard has an awesome admin interface with drag and drop feature. I have implemented it in my project but the requirement is that user won't be given access to django admin and a separate dashboard is created for crud like operations. Is there any way i can use that admin interface in my custom dashboard without losing all the functionality? -
How to make django recognise lines in a TextField
everyone. I have a blog model with the attribute description = models.TextField(). I made a blog the using the django admin interface. On my website, I print all the blogs. In admin, I left newlines (just by pressing enter) in between the paragraphs, but they are displayed as a single paragraph on the website. I know this question is answered here newline in models.TextField() not rendered in template and here New Line on Django admin Text Field, but these solutions use the template tags linebreak and safe and requires you to use \n in your TextField. For any non-programmer using my website, they wouldn't know to use \n. Basically, what I am trying to say is, is there any solution which doesn't require \n in theTextField. I use Django 3.2 and SQLite3. Thanks in advance. -
Register user in django rest framework with connect to database phpmyadmin
I was following this step: https://stackoverflow.com/a/29391122/13240914 to create user registration and login with return jwt. Here is part of the code class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) def create(self, validated_data): user = UserModel.objects.create_user( username=validated_data['username'], password=validated_data['password'], ) return user class Meta: model = UserModel # Tuple of serialized model fields (see link [2]) fields = ( "id", "username", "password", ) So, instead of using validated_data, is there a way to validate username using data inside database phpmyadmin (so when user have been save their username in database, it will return error.. other than that, the username will be save in database) ? I have created database in phpmyadmin, but I didn't know yet how to replace validated_data with validation to check in database -
How to generate JSON from a pandas data frame for dynamic d3.js tree
I'm new to Pandas and have a complex requirement. I have a data frame, which contains multiple columns like the one below Parent Child Color IT;Programming;Trending;Demand Python #6200ea IT;Programming;Trending;Demand Docker #7c4dff IT;Programming;Testing Selenium #b388ff IT;Programming;Old C/C++/C# #ff1744 IT-Tools;Testing HP UFT #aa00ff IT-Tools;IDE PyCharm #9c27b0 I've used str.split(';') to generate multiple Parent columns in the data frame df = df.join(df.Parent.str.split(";", expand=True).add_prefix('branch')) df.drop(columns=['Parent'], inplace=True) print(df) Output: branch0 branch1 branch2 branch3 Child Color IT Programming Trending Demand Python #6200ea IT Programming Trending Demand Docker #7c4dff IT Programming Testing None Selenium #b388ff IT Programming Old None C/C++/C# #ff1744 IT-Tools Testing None None HP UFT #aa00ff IT-Tools IDE None None PyCharm #9c27b0 I need to generate a classification tree for which I need to generate a JSON (along with color value) which is mentioned on the below website https://bl.ocks.org/swayvil/b86f8d4941bdfcbfff8f69619cd2f460#data-example.json Can somebody please help me Thank you! -
date filtering in django with __gte does not add apostrophe
when filtering using __gte on models.DateTimeField the printed query doesn't wrap the searched date with an apostrophe ' this may lead to undesired results in postgres database: WHERE ("appname_tablename"."creation_date" >= 2021-06-27 11:08:29.311284+00:00 AND "appname_tablename"."node_id" = 111) switching to a raw query set which requires further processing since the result needs to go though aggregation and so on, any ideas? -
disable dark mode in django admin
The Problem I installed Django after couple of months. Current version is 3.2.4. Earlier Django-admin was just light-mode. Current Django-admin switches automatically to dark or light according to system theme. Well, I do not want this behaviour. I want Django-admin to be light theme irrespective of system theme. I am Not using 3rd party theme for Django-admin. What I Tried? As per one of the comment in this answer, I decided to comment "@media (prefers-color-scheme: dark)" section in /static/admin/css/base.css . Not sure that it's good solution but the fastest one. I tried commenting the code as shown here but does not work. I tried clearing cache and even tried switching browser but none of them seems to work. In browsers, I always prefer light theme. How can I achieve this? Any help is appreciable. Thanks in advance :) System Details: OS: Fedora 5.11.12-300.fc34.x86_64 Python-Verion: 3.9.5 -
Django - expected type pk, received str [Many to many]
I have a webapp where we can create communities with django as a backend, but when i try to send a POST to create a community, I get: community_configuration: ["Incorrect type. Expected pk value, received str."] My POST: { title: knkn kn .k jbjnmn, logo: [object File], is_active: true, description: test, welcome_message: Welcome message, org_id: 114, community_configuration: About us,Community news,FAQs,Supporters,Resources, } Here are my serializers: class MicroConfigurationSerializer(serializers.ModelSerializer): class Meta: model = MicroConfiguration fields = [ 'name', ] def to_representation(self, instance): return instance.name class CommunityConfigurationSerializer(serializers.ModelSerializer): micro_configurations = MicroConfigurationSerializer(many=True, read_only=True) class Meta: model = CommunityConfiguration fields = '__all__' class CommunitySerializer(serializers.ModelSerializer): logo = serializers.SerializerMethodField() organisation = serializers.SerializerMethodField() community_configuration = CommunityConfigurationSerializer() class Meta: model = Community fields = ( ... etcetc ... ) Heres my model: class MicroConfiguration(core_models.BaseModel): name = models.CharField(max_length=32, unique=True) permissions = models.ManyToManyField(Permission) def __str__(self): return self.name class CommunityConfiguration(core_models.BaseModel): name = models.CharField(max_length=32) micro_configurations = models.ManyToManyField(MicroConfiguration) permission_group = models.ForeignKey( Group, on_delete=models.SET_NULL, null=True ) def __str__(self): return self.name class Community(core_models.BaseModel): accounts = models.ManyToManyField( settings.AUTH_USER_MODEL, through='associates.AccountCommunity', through_fields=('community', 'account') ) goals = models.ManyToManyField(Goal, through='associates.CommunityGoal') type = models.ManyToManyField(CommunityType, through='CommunityAttribute') communities = models.ManyToManyField( 'self', through='associates.CommunityCommunity', symmetrical=False, ) crossposts = models.ManyToManyField( Action, through='activities.CommunityCrosspost', through_fields=('community', 'action'), related_name='communities', ) title = models.CharField(max_length=64) logo = models.ImageField(null=True, blank=True) intro_media = models.ForeignKey( 'associates.MediaStore', null=True, … -
django - prefetch a specific item of a one-to-many relationship
Let's say I have the following simple models. One BlogPost can have multiple BlogPostImages. The BlogPostImages have a field which specifies the order of the images. The image with order=1 is defined as the preview image My goal: For a given queryset of BlogPosts (with various filters applied) I want to prefetch the corresponding preview images (i.e. order=1) from django.db import models class BlogPost(models.Model): name = models.CharField(max_length=50) class BlogPostImage(models.Model): image = models.ImageField() order = models.IntegerField() blogpost = models.ForeignKey( BlogPost, related_name="images", on_delete=models.CASCADE, ) First attempt: Prefetch all images results = BlogPost.objects.filter(...).prefetch_related("images").all() for result in results: # 1.1 Triggers query for each blogpost preview_image = result.images.filter(order=1) # 1.2 Prefetch works, no extra query, but seems inefficient to needlessly iterate over all images for image in result.images.all(): if image.order == 1: preview_image = image Second attempt: Prefetch only the preview image sq = (BlogPostImage.objects .filter(blogpost=models.OuterRef('pk'), order=1) .values("image") ) results = (BlogPost.objects.filter(...) .annotate(_preview_image=models.Subquery(sq, output_field=models.CharField())) ) for result in results: # 2.1 No extra query, but only the image name preview_image = result._preview_image How can I prefetch the preview image and let the database do the work? -
I need help in the cmd django [duplicate]
so i was working in a to do list website using Django .. i saw this tutorial in YouTube so for the setup he used command prompt for setup i already downloaded Django Downloads (they choose desktop but i wanna downloads >Downloads>django-admin start project todo_list and when i press enter it says 'Django admin' is not recognized as an internal or external command -
Django and NGINX: How to serve protected media files to internal viewer?
currently I protect my media files against unauthorized access like described e.g. here with the following configuration: Media files are located in /home/mysite/dproject/media/ In the nginx configuration the location to the media files is set like this: ... location /protected/ { internal; alias ../mysite/dproject/media/; } ... In urls.py I redirect requests to /media/ to an access denied view: urlpatterns = [ ... re_path(r'^media/', login_required(PermissiondeniedView.as_view()), name='directmediaaccessdenied') ] In settings.py the paths MEDIA_URL and MEDIA_ROOT are set: MEDIA_ROOT = str(PROJ_DIR('media')) MEDIA_URL = '/media/' To serve files for download, I use the following code in my views: response = HttpResponse() path = os.path.normcase( '/protected/' + filepath ) del response['Content-Type'] response['Content-Disposition'] = 'attachment; filename="%s"' % path response['X-Accel-Redirect'] = path return response So far everything works as expected, but I am not able to provide the data to embedded PDF or 3D viewers. For example I use a viewer to show 3D files (source taken from here). The path to the file is passed with a hash parameter, so a valid URL to the view with the embedded viewer looks like this: https://mysite.mydomain.com/3Dview/#model=/media/path/to/file.ext With the configuration described above, the viewer fails to load the file. The viewer works when I change the nginx config to: … -
how can i set the id of product to their own group?
Problem The problem I'm facing is that i have a same products with different descriptions, so i had to group them in a dropdown respectively. Now when i change the value in the dropdown of the product, it changes the values in only the first product retrieved. The code and the screenshot of the issues are attached below. Code <script> $(document).on("change", '.tranactionID', function (event) { event.preventDefault(); $('#id_price').text($(this).children(":selected").attr("price")); $('#id_sale_price').text($(this).children(":selected").attr("sale_price")); let id = $('#ItemID').find(":selected").attr('transID'); console.log('Id : ',id) let Url = `{% url 'cart:cart_add' 0 %}`.replace(0,id); $('#transactionIDValue').attr('action', Url); let formAction = $('#transactionIDValue').attr('action') let formAction2 = $('#transactionIDValue').prop('action') console.log('form action relative url : ',formAction) console.log('form action full url : ',formAction2) }); </script> {% regroup transaction by productID as ProductList %} {% for productID in ProductList %} <div class="col-sm-3" id="productID" > <div class="product"> <a href="{% url 'main:product-detail' productID.grouper.id %}" class="img-prod"><img class="img-fluid" src={{productID.grouper.product_image.url}} alt="" height="200px"> <span class="status" id="discount">%</span> <div class="overlay"></div> </a> <div class="text py-3 pb-4 px-3 text-center"> <h3><a href="#">{{productID.grouper}}</a></h3> <div class="d-flex"> <div class="pricing"> <p class="price"><span class="mr-2 price-dc" id='id_price'>Rs. </span><span class="price-sale" id='id_sale_price'>Rs. </span></p> </div> </div> <select class="tranactionID" id="ItemID" style="width: 250px;"> <option value="none" selected disabled hidden> Select an Option </option> {% for val in productID.list %} <option transID={{val.id}} price={{val.Price}} sale_price={{val.get_sale}} class="price_value" >{{val.AUID}} - {{val.Description}}</option> {% endfor %} </select> <!-- … -
Getting authentication error even after login in Django rest framework authentication?
my models.py from django.db import models from django.contrib.auth.models import AbstractUser class User_model(AbstractUser): user_type = models.CharField(max_length=2, choices=(("MN", "Mentor"), ("NM", "NormalUser"))) my serializers.py from rest_framework import serializers from rest_framework_jwt.settings import api_settings from django.contrib.auth.models import User from .models import User_model class UserSerializer(serializers.ModelSerializer): class Meta: model = User_model fields = ('username',) class UserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class Meta: model = User_model fields = ('token', 'username', 'password') views.py from django.shortcuts import render Create your views here. from django.http import HttpResponseRedirect from django.contrib.auth.models import User from rest_framework import permissions, status from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.views import APIView from .serializers import UserSerializer, UserSerializerWithToken from rest_framework import mixins from rest_framework.generics import GenericAPIView @api_view(['GET']) def current_user(request): """ Determine the current user by their token, and return their data """ serializer = UserSerializer(request.user) return Response(serializer.data) class UserList(mixins.CreateModelMixin, GenericAPIView): """ Create a new user. It's called 'UserList' because normally we'd have a get method here too, for retrieving a list of all User objects. """ permission_classes = … -
Can one override the boolean icons in the django admin while using django suit?
Is there any way I can override the default behaviour of django's icon display? Am using django suit, and for it to work with s3 bucket I had to disable admin default statics. But now on the boolean part of the tables, it is returning an image placeholder with the alt text which is True or False. I just wanted to completely remove that icon and it stays with just True and False. Hope my question was clear -
Can't reach AWS EC2 hosted website with Django app
In EC2 Console everything is working correctly, instance is launching properly and in the console there were no errors but I can't open the website and get ERR_CONNECTION_TIMED_OUT error. A week ago I was able to connect to the website but now I created a new instance and it didn't work. I'm using Django with Docker and Nginx proxy. The issue might be connected with EC2 because as I said previously I've launched an instance and it worked properly. Here's the output: app_1 | Waiting for database... app_1 | Database unavailable, waiting 1 second... app_1 | Database available! app_1 | app_1 | 128 static files copied to '/vol/web/static'. app_1 | Operations to perform: app_1 | Apply all migrations: admin, auth, contenttypes, core, sessions app_1 | Running migrations: app_1 | Applying contenttypes.0001_initial... OK app_1 | Applying auth.0001_initial... OK app_1 | Applying admin.0001_initial... OK app_1 | Applying admin.0002_logentry_remove_auto_add... OK app_1 | Applying admin.0003_logentry_add_action_flag_choices... OK app_1 | Applying contenttypes.0002_remove_content_type_name... OK app_1 | Applying auth.0002_alter_permission_name_max_length... OK app_1 | Applying auth.0003_alter_user_email_max_length... OK app_1 | Applying auth.0004_alter_user_username_opts... OK app_1 | Applying auth.0005_alter_user_last_login_null... OK app_1 | Applying auth.0006_require_contenttypes_0002... OK app_1 | Applying auth.0007_alter_validators_add_error_messages... OK app_1 | Applying auth.0008_alter_user_username_max_length... OK app_1 | Applying auth.0009_alter_user_last_name_max_length... OK app_1 | Applying … -
How to combine 'blocktanslate' with 'humanize' tag in templates?
blocktranslate allows me to display a localized plural, whereas humanize allows me to display a grouped-by-hundred number. Each of them works when used independently but I'd like to have both in the same time. I've tried: (words_number is the integer sent by the view) {% load humanize %} {% blocktranslate count counter=words_number %} 1 word {% plural %} {{ counter|intcomma }} words {% endblocktranslate %} But it displays: words (empty space where the number should be) -
DJANGO Data update problem. No Error Code
I want to update the data I have determined in the database by pulling it with post. However, it is not updated. views.py def bilgilerim_guncel(request): if(request.method=='POST'): name_surname= request.POST['name_surname'] mobile_number= request.POST['mobile_number'] age= request.POST['age'] length= request.POST['length'] weight= request.POST['weight'] foot= request.POST['foot'] position= request.POST['position'] players.objects.filter(user_id=user_id).update(name_surname=name_surname,mobile_number=mobile_number,age=age,foot=foot,length=length,position=position,weight=weight) return render(request, 'profil/bilgilerim.html') players_models.py class players(models.Model): name_surname=models.CharField(max_length=18,null=False,blank=False) mobile_number=models.IntegerField(null=False,blank=False) player_status=models.IntegerField(null=True,blank=True,default=0) team_id=models.IntegerField(null=True,blank=True,default=0) photo=models.ImageField(null=True,blank=True,default='resim-yok.jpg') awards=models.IntegerField(null=True,blank=True) dogecoin=models.IntegerField(null=True,blank=True) age=models.IntegerField(null=False,blank=False) foot=models.CharField(max_length=10,null=False,blank=False) length=models.CharField(max_length=4,null=False,blank=False) weight=models.IntegerField(null=False,blank=False) red_card=models.IntegerField(null=True,blank=True,default=0) position=models.CharField(max_length=2,null=False,blank=False) form_points=models.CharField(max_length=3,null=True,blank=True) user=models.ForeignKey(User,on_delete=models.CASCADE) -
Vs code break point does not not stop at Python-Django API TestCase
Normally, debugging is just working fine with Container. I am spinning up my container at port 8000 and attaching the debugging port which is 3000 to it. But, when I hit my rest_api, although it stops from Swagger when it comes to being hit by TestCase debugger does not stop. I could not figure out the reason. -
How to modify and set rules for fields values in django models?
I need to modify the field values of a Django model just like in the following myfunction but when I tried something like this I got nothing changed also i tride __init__ instead of myfunction and I tride save() but nothing worked. class AllDataStrecture(models.Model): name = models.CharField(max_length=30,blank=True,null=True) codename = models.CharField(max_length=30, blank=True, null=True) content_type =models.OneToOneField(ContentType,on_delete=models.DO_NOTHING,null=True) def create_values(self): #also here I am trying to create values for in Permission.objects.all(): self.name = i.name self.content_type = i.content_type self.codename = i.codename def myfunction(self): if 'Can view' in self.name: self.name = self.name.replace('Can view','') if 'Can change' in self.name: self.delete() my Goal is to create a model for an automation app, in which user can select a model name and say if this model name changed then do this .... what I need here is to use Permission instead of models.Model and override it in which I delete the word Can view, or Can change and keep only the value change modelanem -
How to exclude request with {format} drf-yasg?
everyone. I'm writing docs for my api on drf with using drf-yasing. And each of my requests has a copy with {format}. How i can delete that? screenshot my problem For example my easy view: @swagger_auto_schema(method='GET', manual_parameters=[params_id]) @api_view(['GET']) def get_service_history(request): service = Service.objects.get(id=request.GET['id']) ser = ServiceHistorySerializer(service.service_history.all(), many=True) return Response(ser.data) Url: path('deleted_service/', views.deleted_service) ps sorry for my english :)