Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django admin count numbers of rows before adding a new data in StackedInline mode
In my django project i have a model related to a main model like this one: class Device_Docs(models.Model): id = models.AutoField(primary_key=True) master_id = models.ForeignKey(Device, on_delete=models.CASCADE) device_file = models.FileField(upload_to='uploads/', validators=[FileExtensionValidator(['pdf', 'jpg', 'txt', 'png', 'jpeg']), validate_fsize], verbose_name="Select File", help_text='Allowed formats are PDF, JPG, JPEG, TXT, PNG, max size 3Mb') title = models.CharField(max_length=250, help_text='Document title') description = models.TextField(default='', verbose_name="Descrizione", null=True, blank=True) load_data = models.DateField(default=datetime.now(roma).strftime("%Y-%m-%d %H:%M:%S.%f"), verbose_name="Load data") owner = models.ForeignKey('accounts.CustomUser', related_name='odevdocs', on_delete=models.CASCADE) ... Now i would to show in my admin, for the Device model (main model) using StackedInline option both models data: class DocsInline(admin.StackedInline): model = Device_Docs extra = 1 @admin.register(Device) class DeviceModelAdmin(admin.ModelAdmin): list_display = ('mac_id', 'short_name', 'proj_type', 'polling_interval', 'active', 'autoupdate', 'save_date') list_filter = ('polling_interval','proj_type', 'active', 'autoupdate') search_fields = ('short_name', 'save_date' ) ordering = ('-save_date', 'mac_id') readonly_fields = ('mac_id', ) inlines = [PortinInline, DocsInline] def has_delete_permission(self, request, obj=None): return False def get_form(self, request, obj=None, **kwargs): self.exclude = ("owner", "save_date") form = super(DeviceModelAdmin, self).get_form(request, obj, **kwargs) return form Ok all works good, now my question is, how can i control the numbers ofrows already entered about Device_Docs data before save? For exmple i would block the possibility about insert data if in model there are more then 5 records with the same master_id … -
Django run a command once the server starts [duplicate]
I have a setup function which can only be run once the app has started and is answering requests, but which I would like to run only once when the server starts. Is there a hook or other way to run a setup function after Django has completed the "peforming system checks..." and gotten to the point where it has emitted "Quit the server with CONTROL-C."? -
Django model tab-complete in ipython
I wish to use ipython to create a custom command-line interface to query Django model objects. So for example I'd like to type: my_models.MyModelClass.h <TAB> And have all of the elements of the MyModelClass table that start with "h" be used as the tab complete. I could achieve this by creating a startup script and creating an object heirachy which matches the table structure, however that will be slow, and I'd prefer to only create the request on demand. Is there a more direct way to use ipython's tab complete, for example a function which is called to get the tab complete list when tab is invoked? -
docker-compose can't find django-admin in $PATH, but I can run django-admin commands separately
I'm trying to test a django app in a docker image. I have followed the tutorial until the it starts the django project. When I run, docker-compose run web django-admin startproject composeexample . I get Error response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "django-admin": executable file not found in $PATH: unknown ERROR: 1 It's weird because I can run django-admin createproject ... seperately. Any thoughts? I have added the ..\python39\scripts in the path. Also I have python 3.9.10 from the windows store. -
Django-CMS slug in if statement in HTML
I am trying to write an if statement to change what the link links to, based on the slug URL. I get an error in the if_statement. Shouldn't this work? <div> {% if page_attribute "slug" == 'hjem' or page_attribute "slug" == 'home' %} <a href="/no/">NO</a> / <a href="/en/">EN</a> {% else %} <a href="/no/{% page_attribute 'slug' %}">NO</a> / <a href="/en/{% page_attribute 'slug' %}">EN</a> {% endif %} </div> -
Django admin login wont respect custom next param
I want to redirect to a custom page (next='reports/fooreport') after Django admin login. I have a page in Django to be accessed by authenticated users. If I hit the URL let's say /reports/fooreport and I am redirecting the user to admin login with next='/reports/fooreport' using HttpResponseRedirect('%s?next=%s' % (reverse('admin:index'), '/reports/fooreport')) After successful login, Django is not redirecting to the next URL. However, it works pretty well for its internal apps like if I hit any admin page without login it appends in URL with next param and post login it redirects to this URL. Is there anything we can do to make it work? -
How do I filter wagtail images by a queryset?
I have following page structure: blog_ |_contributor 1 |_Post 1 |_Post 2 |_contributor 2 |_Post 3 |_Post 4 |_Post 5 Editors take the content provided by contributors and upload that content on their behalf. Editors can therefore create posts as children of each contributor. To avoid accidental copyright infringements in the use of image materials, I would like the ImageChooserPanel to only display images uploaded to the pages of a given contributor, i.e. when a post is created as a child of a given contributor, the ImageChooserPanel should only display images uploaded to the pages of that contributor (or allow additional image upload). A manual solution would be to manually create a collection for each contributor and upload and select from that section. However, that would create too much overhead, given a high number of contributors. I've tried to figure out a solution with the use of a custom image model that contains a foreignkey to the contributor in combination with a construct_image_chooser_queryset hook, but have so far fallen short. -
Summation of fields in SQL Query or getting results and then looping in code?
I have more than 100K rows in my table. I want to get the sum of data with id='x' (Filtered data would be 50-100 rows). What should I prefer? SQL Sum or get the filtered data and sum the data using loop. Option 1 query = 'SELECT SUM('field_1) as qunatity_1, SUM(field_2) as quantity_2....SUM(field_15) as quantity_3 from BOOKS where id=10' Should I just hit this query and get the required data Option 2 query = 'SELECT field_1, field_2...field_15 from BOOKS where id=10' loop on the received rows and sum the fields to get required data -
How to perform left join in django?
i like to join two tables using left join operation. this is what i like to do: SELECT * FROM orders LEFT JOIN products ON (orders.product_id = products.id); my model classes: class Orders(models.Model): name = models.CharField(max_length=100, null=False, blank=False) qty = models.IntegerField(null=False, blank=False) product = models.ForeignKey(Products, on_delete=models.CASCADE) customer = models.ForeignKey(Customers, on_delete=models.CASCADE) class Meta: db_table = 'orders' class Products(models.Model): name = models.CharField(max_length=100, null=False) qty = models.IntegerField(default=0, null=True) price = models.FloatField(null=True, default=0) description = models.CharField(max_length=500, null=True, default=None) class Meta: db_table = "products" -
How can increment a variable value in jinja
How can increment a variable value in jinja (django template language).. {% with a=0 %} {% with b=4 %} {% endwith %} {% endwith %} i used above code to assign value to a variable. i want to increment it with 4. -
how to pass SQL output parameter in rest framework
I'm trying to pass the Output parameter @response in Django views but I couldn't able to achieve it. I have tried two approaches here, what I have tried views.py: approach1: @api_view(['POST']) def FetchSuggestionAuditAgent(request): if request.method == 'POST': agents = request.data.get('Agents') Output = request.data.get('Answer') AuditorId = request.data.get('AuditorId') TicketId = request.data.get('TicketId') QId = request.data.get('QId') Answer = request.data.get('Answer') print('Agents--', agents) cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_FetchSuggestionAuditAgent] @agents=%s, @response=%s', (agents, '')) return Response({ 'Agents':agents }) approach2: @api_view(['POST']) def FetchSuggestionAuditAgent(request): if request.method == 'POST': agents = request.data.get('Agents') sql = """\ DECLARE @response nvarchar(max), @agents nvarchar(max); EXEC [dbo].[sp_FetchSuggestionAuditAgent] @agents = ?, @response = @out OUTPUT; SELECT @response AS the_output; """ params = (agents, ) cursor = connection.cursor() cursor.execute(sql, params) rows = cursor.fetchall() while rows: print(rows) if cursor.nextset(): rows = cursor.fetchall() else: rows = None return Response(True) SQL: CREATE [dbo].[sp_FetchSuggestionAuditAgent] @agents nvarchar(max),@response nvarchar(1000) OUTPUT AS BEGIN set @agents = replace(@agents,' ', '%') select @response = FullName from ( select FullName from tblusers where IsActive=1 union all select FullName from tblusers where IsActive=0 and UserRole='Snowuser' )as a where FullName like @agents--('%'+@agents+'%') order by FullName desc END -
use of mixins class defined in Django rest framework
What is the actual use of Mixins class? I don't really get it. All the mixins classes like CreateModelmixin, Listmixin, etc features are already available in class-based view like ListCreateApiView. For eg: class ExampleView(ListCreateAPIView DestroyAPIView, RetrieveUpdateAPIView): queryset = Example.objects.all() serializer_class = ExampleSerializer pagination_class = CustomPageNumberPagination Using mixins we can do it by following: class ExampleView(ListAPIView, mixins.CreateModelMixin): queryset = Example.objects.all() serializer_class = ExampleSerializer pagination_class = CustomPageNumberPagination When I check https://www.cdrf.co/ I see the methods that are available in CreateModelMixing are the following: def create(self, request, *args, **kwargs): def get_success_headers(self, data): def perform_create(self, serializer): These methods are already available in ListCreateApiView, then why Django went to create this useless class?? -
Downloaded file is stored in 2 directories
problem occurs with the code below def creation_download(request, campaign_id, downloaded_file): bucket_file = downloaded_file gcs = GCPStorage() gcs.download_file(GCP_STORAGE_BUCKET_NAME, bucket_file) response = HttpResponse(bucket_file, content_type='application') response['Content-Disposition'] = 'attachment' return response I just want my file to be downloaded only to user/download directory, but it also being downloaded to my repository directory (where manage.py is stored and where is base_dir pointed). How do i manage only to store it in download directory? -
How can open and read GML file with OGR
I'm trying to open a gml file to read it but i can't access to content. models.py: class Plot(ChangesMixin, TimeEntity): gml = models.FileField(verbose_name=_('GML'), upload_to='gml/plot/', blank=True, null=True) parser_gml.py: from osgeo import ogr ... self.element.gml.file.open() file_content = self.element.gml.file.read() reader = ogr.Open(file_content, False) for layer_i in range(reader.GetLayerCount()): ... Anybody could help me please ? Thanks in advance. -
Django form not showing up in template using {{ form }} tag
I have made a basic todo app for my practice in which i want to create a profile page for every user. I have made a profile model, and connect it to a User signal, profile has been created but when I render it in a template, its not showing the profile form. the form for the profile model is form.py: class ProfileForm(ModelForm): class Meta: model = Profile fields = '__all__' exclude = ['user'] model.py --profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, null=True, blank=False) email = models.EmailField(max_length=200, null=True) phone = models.CharField(max_length=40, null=True, blank=True) image = models.ImageField(null=True, blank=True, default='pfp.png', upload_to='images') date_created = models.DateField(auto_now_add=True) def __str__(self): return self.user.username the view to render the profile(note: I am not creating a edit profile form, which i'll do later, that is why i used get in method): def user_profile(request): profile = request.user.profile form = ProfileForm(instance=profile) context = {'form': form} return render(request, 'task/profile.html') profile page template: {% extends 'main.html' %} {% load crispy_forms_tags %} {% block content %} <h3>Profile Page</h3> <style> .profile-pic{ max-width: 200px; max-height: 200px; margin: 0 auto; border-radius: 50%; } body{ background-color: rgba(211, 211, 211, 0.527); } </style> <br> <div class="row"> <div class="col-md-3"> <div class="card card-body"> <a class="btn … -
How to change the default Django Admin Site
I have added a new admin site to my Django Project and I only want some staff members to have access to it: class OtherAdminSite(DjangoAdminSite): site_header = "Some Other Header" site_title = "Some Other Title" index_title = "Some Other Title" def has_permission(self, request): user_in_other_admin_group = request.user.groups.filter( name="OtherAdminGroup" ).exists() return super().has_permission(request) and user_in_core_admin_group I can associate specific ModelAdmins w/ that site as follows: @admin.register(MyModel, site=other_admin_site) class MyModelAdmin(admin.ModelAdmin): pass That works fine. However, I don't want the members of "OtherAdminGroup" to be able to access the default admin site. I do not have the ability to update all of the admins in my project, b/c many of them come from 3rd party libraries. Is there a way to retroactively change the permission of all the default admins? -
Access a serializer via a variable in drf
In the create method in my serializer I'm trying to send a portion of validated data to another serializer as below: new_serializer = NewSerializer(validated_data.get('customer')) new_serializer.save() But in the place of NewSerializer I want to be able to use a variable.This will allow me to choose serializers dynamically. Something like this: the_serializer = "NewSerializer" new_serializer = the_serializer(validated_data.get('customer')) Is there a way to achieve this? -
Using custom manager in M2M serializer in Django Rest Framework
I have three models. I've simplified the case for easier understanding: class Physician(model.Models): name = models.CharField(max_length=255) surname = models.CharField(max_length=255) class Hospital(model.Models): name = models.CharField(max_length=512) physicians = models.ManyToManyField(Physician, through=Membership, related_name='hospitals') class MembershipManager(models.Manager): def get_queryset(self): is_verified = # A very complex annotate case. return super(MembershipManager, self).get_queryset().annotate(is_verified=is_verified) class Membership(model.Models): hospital = models.ForeignKey(Hospital, on_delete=models.CASCADE) physician = models.ForeignKey(Physician, on_delete=models.CASCADE) object = MembershipManager() I use Django Rest Framework to create a read-only API. In this case, a Pyhisician can have many Memberships in different Hospitals. I want to add the is_verified attribute to the Hospital serializer. Of course I could create a function is_verified_for_physician(self, physician) inside the Hospital class, but this field is expensive to calculate (that's why I made the annotate in the manager). The question is, how can I achieve this using Serializers? The natural thing for me, it would be to ask for physician.hospitals.all() and somehow pass the is_verified field from the Membership model to the Hospital. Is this possible? -
getting 505 error while DEBUG = True while pushing to heroku
I'm pushing my django project to heroku. This is what is perturbing me at the moment. in my settings.py when I turn leave my debug like this DEBUG = False and i run the command to push it heroku. I will get a 505 error. but when I reverse it to DEBUG = True it will run smoothly. Meanwhile, I already did heroku config:add DEBUG=False and it's reflecting on my heroku's reveal config var What could be the problem? Because I'm trying to turn off debug while in production -
django model field default value not showing in template with jquery
when i remove the html data- , then django field value is showing there . but when i add the data-id, data-winner etc , django model field default value is not showing in template, how can i fix this . ? models.py class Contest(models.Model): title = models.CharField(max_length=50) name_winner = models.CharField(max_length=50,default="Announce") @property def winner(self): if something ... winner_name = something else: winner_name = something return name_winner html {%for ....%} <td type="hidden" class="winner_click" data-winner="{{contest.winner}}" data-id="{{contest.id}}"> {{contest.name_winner}}</td> {%end for%} <script> $(".winner_click").click(function(){ var get_id = $(this).data('id') var get_data = $(this).data('winner') $(this).html(get_data).css("color","black") $.ajax( { type:"POST", url: "/admin/save_winner", data:{ 'contest_id': get_id, 'contest_winner':get_data, "csrfmiddlewaretoken": '{{ csrf_token }}' }, success: function( data ) { $(this).html(get_data).css("color","black") } }) }); </script> in this case when i remove the data-id and data-winner then that td shows default django field value , in this case there is nothing shows . views: save winner def save_winner(request): if request.method == 'POST': contest_id = request.POST.get('contest_id') contest_winner = request.POST.get('contest_winner') Contest.objects.filter(id=contest_id).update(name_winner=contest_winner) return JsonResponse({"status":"success"}) how can i fix this ? why is this issue ? Thank you -
How to display images of a particular Blog post?
models.py class PostModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date_time = models.DateTimeField(auto_now_add=True) title = models.TextField(null=True) body = models.TextField(null=True) def __str__(self): return str(self.user) class ImagesPostModel(models.Model): post = models.ForeignKey(PostModel, on_delete=models.CASCADE) images = models.I views.py def show_posts(request): posts = PostModel.objects.filter(user=request.user) images = [] for post in posts: images.append(ImagesPostModel.objects.filter(post=post)) context = { 'posts': posts, 'images': images, } return render(request, 'show_posts.html', context) show_posts.html {% extends 'base.html' %} {% block content %} {% for post in posts %} {{post.title}} <br> {{post.body}} <br> {{post.data_time}} <br> {% for imgs in images %} {% for image in imgs %} {{image.post_id}} <img src="{{image.images.url}}" alt="postimage" style="width: 300px;"> <br> {% endfor %} {% endfor %} <hr> <hr> {% endfor %} {% endblock %} I want the images of a post to be displayed which are related to that post only. But here all the images combined for all posts of a particular user are being displayed each time in every post. How to resolve it? -
Adding a django link in pop up django map marker?
I am making a website with the map and markers. When the user presses on to the marker, there should be django link to another page. But, I have a problem in adding a link in my popup in views django. Here is my code views.py def Map(request): data = Data.objects.all() data_list = Data.objects.values_list('latitude', 'longitude') adress_list = Data.objects.values_list('country') map1 = folium.Map(location=[42.8746, 74.5698], zoom_start=13) icon = plugins.BeautifyIcon(icon="marker") for i in range(0,len(data_list)): folium.Marker( location=[data_list[i][0], data_list[i][1]], popup=f"<p>АДРЕС:{adress_list[i]}</p><p>наличие денег:10000</p><p>РЕЖИМ РАБОТЫ: 9.00 до 17.30</p>**<a href="{% url 'application' %}">**<button style='background-color:green;color:white;outline:none;'>ОТПРАВИТЬ ЗАЯВКУ</button></a>").add_to(map1) map1 = map1._repr_html_() context = { 'map1': map1, } return render(request, 'map.html', context) Here as you can see I want to add a link in popup, however because of quotation marks, I can not add django link here. template code <div class="row mt-4 map" style="width:900px;"> <div style="text-align: center;margin-left:40%;margin-top:70px;"><i class="bi bi-chevron-left"><i style="margin-left: 40px;">Bishkek</i></i><i class="bi bi-chevron-right" style="margin-left: 40px;"></i></div> <div class="col-md-10 offset-md-1"> <div class="map-1" style="margin-top: 0px;width:900px;margin-left: -90px;border-radius: 9px;"> {{map1|safe}} </div> </div> </div> </div> Looking forward to get the answer soon. Thanks in advance! -
Micrososoft One drive save files from django
I have been trying to save my files to onedrive from django rest framework. I have tried following documentation of one drive sdk for python but nowhere it seemed to explain how to make it work th django. Documentation can be found at https://github.com/OneDrive/onedrive-sdk-python. I have made a drf model which is as follows: class ReportVersionModel(models.Model): report_version_name = models.CharField(max_length=255) report = models.ForeignKey(ReportModel, on_delete=models.CASCADE) created_by = models.CharField(max_length=255) created_on = models.DateTimeField(auto_now_add=True, null=False, blank=False) file = models.FileField(upload_to='message/%Y/%m/%d/', max_length=100, blank=True) what I need help is regarding how to use this model with the one drive sdk. -
item.delete(force_policy=HARD_DELETE) does not working
I have the following model class User(SafeDeleteModel, AbstractUser, PermissionsMixin, BaseModel): name = models.CharField( blank=True, null=True, max_length=255) I tried this. from safedelete import HARD_DELETE, HARD_DELETE_NOCASCADE item = User.objects.get(id=3) item.delete(force_policy=HARD_DELETE) but when I say User.objects.get(id=3) I am still getting the user instead of a 404 error. -
Hi, I have two problems and I am new
My first problem is that in VS fertilizer when (from django) I put a line in each part below it and it does not recognize it, and my second problem is that I enter my code in the Django file in the Models section And then in the code terminal python (manage.py makemigrations) We make an error, thank you for your help.