Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Error receiving POST request and uploading to db from form Django
I ran into a problem when entering data into the form. Nothing is added to the database, although there are no errors in the terminal (but the POST request is not highlighted in green, I attach a screenshot) . Created "else:return render(request, "food/test.html ")" to check for an error, I've already searched half the Internet, I can't understand what the error is (there is a suggestion that it's about adding an image) I'm fixing all the files. models.py from django.db import models class Recipe(models.Model): recipe_title = models.CharField(max_length=20) recipe_time = models.IntegerField() recipe_ingridients = models.IntegerField() author_name = models.CharField(max_length=30) image = models.FileField(upload_to='') recipe = models.TextField(max_length=300) forms.py from django.forms import ModelForm, TextInput, Textarea, NumberInput, FileInput from .models import Recipe class FoodForm(ModelForm): class Meta: model = Recipe fields = ["recipe_title", "recipe", "recipe_time", "recipe_ingridients", "author_name", "image"] widgets = { "recipe_title" : TextInput( attrs={ "class" : "title_form", "placeholder" : "Введите название рецепта" } ), "recipe": Textarea( attrs={ "class": "form_of_all", "placeholder": "Введите ваш рецепт" } ), "recipe_time" : NumberInput( attrs={ "class" : "ingr", "placeholder" : "Введите время" } ), "recipe_ingridients": NumberInput( attrs={ "class": "ingr", "placeholder": "Введите кол-во ингридиентов" } ), "author_name" : TextInput( attrs={ "placeholder" : "enter quthor name" } ), "image" : FileInput( attrs={ 'type' : "file", … -
i am trying to develop a web app using django framework i uploaded an excel file now iam looking to find the top 10 values from it. tell me the logic
This is the code for uploading an excel file in django. i want to take the top 10 values and least 10 values and print it in a page. how can i do that? views.py def excel(request): if "GET" == request.method: return render(request, 'blog/excel.html', {}) else: excel_file = request.FILES["excel_file"] # you may put validations here to check extension or file size wb = openpyxl.load_workbook(excel_file) # getting all sheets sheets = wb.sheetnames print(sheets) # getting a particular sheet worksheet = wb["report"] print(worksheet) # getting active sheet active_sheet = wb.active print(active_sheet) # reading a cell print(worksheet["A1"].value) excel_data = list() # iterating over the rows and # getting value from each cell in row for row in worksheet.iter_rows(): row_data = list() for cell in row: row_data.append(str(cell.value)) print(cell.value) excel_data.append(row_data) return render(request, 'blog/excel.html', {"excel_data":excel_data}) -
Edit multiple Models using one form or view in Django
I am using the default User model in Django and a OneToOneField in a Profile model where extra info such as user bio is stored. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) I am able to create basic forms for the two models independently from django.contrib.auth.models import User class UserForm(ModelForm): class Meta: model = User fields = ['username', 'email'] class ProfileForm(ModelForm): class Meta: model = Profile fields = ['bio'] What is the best method to create a page where a user can edit fields of either model? So a User can edit Username,Email or Bio on the same page? -
Read data from the google sheets and dump into the different tables of database python django
I am looking for direction in which I can dump data from the google sheets(which have more than one sheet). I have a database in which there is a many-to-many relationship, one-to-one relationship, etc. so I am looking for any blog, documentation, or video tutorial for this purpose. My stack is Python, Django and Postgresql -
how to submit a selected option of a drop-down list in django?
I'm trying to create a list of jenkins' jobs and build the sected one in django but I didn't know how to implement the right code of the submit button in the views.py to build the job. index.html the index.html views.py the views.py file Any help please?!!! -
How to query additional databases using cursor in Django Pytests
I am developing a Django app that uses cursor to perform raw queries to my secondary DB: my_db2, but when running tests, all the queries return empty results, like if they were running on parallel transactions. My test file: @pytest.mark.django_db(transaction=True, databases=['default', 'my_db2']) class TestItems: def test_something(self): person1 = PeopleFactory() # Adds 1 person to my_db2 assert fetch_all_persons() == 1 # Fails Returns 0 My function: from django.db import connections def fetch_all_persons(): with connections['my_db2'].cursor() as cursor: cursor.execute(f"SELECT * FROM Persons") return len(list(cursor.fetchall())): According documentation transaction=True should prevent this issue, but it doesn't, does somebody know how to fix it?