Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-guardian has_perm("codename", obj) is False even if group has the permission
I'm trying to implement django-guardian permissions in my project. In the TestCase below, I assigned view_income permission to staff group. That means, also user_c has the permission. The problem is that self.user_c.has_perm("view_income", income) returns False. To be clear, I understand how it works and that I can check first the group permission without object. I'm curious if there is a shortcut that will tell me whether a given user has a permission to a given object no matter if it is defined in a group, if it is an object permission or general permission etc... I don't want to write multiple different checks every time I want to check permissions. class IncomePermissionsTestCase(TestCase): def setUp(self): self.user_a = baker.make(settings.AUTH_USER_MODEL) self.user_c = baker.make(settings.AUTH_USER_MODEL) staff_group:Group = baker.make('Group', name='staff') assign_perm('view_income', staff_group) self.user_c.groups.add(staff_group) def test_permissions(self): income = baker.make("clients.Income", client=self.user_a) self.assertTrue(self.user_a.has_perm("view_income", income)) self.assertTrue(self.user_c.has_perm("view_income", income)) -
How can I optimize this code and/or make it DRYer?
I'm just getting started with the django ORM and i have this code. # if UP object exists, update it if UserProgress.objects.filter( user=current_user, card=Card.objects.get(id=submitted_card_id) ).exists(): # if card is understood, update the date_understood datetime field if submitted_understood == True: UserProgress.objects.filter( user=current_user, card=Card.objects.get(id=submitted_card_id) ).update( is_understood=submitted_understood, date_understood=datetime.now(), times_seen=F("times_seen") + 1, ) # if not, simply update the object else: UserProgress.objects.filter( user=current_user, card=Card.objects.get(id=submitted_card_id) ).update( is_understood=submitted_understood, times_seen=F("times_seen") + 1, ) # if UP object does NOT exist, create it else: if submitted_understood == True: UserProgress.objects.create( user=current_user, card=Card.objects.get(id=submitted_card_id), is_understood=submitted_understood, date_understood=datetime.now(), times_seen=1, ) else: UserProgress.objects.create( user=current_user, card=Card.objects.get(id=submitted_card_id), is_understood=submitted_understood, times_seen=1, ) i've tried to make this code a little cleaner and potentially optimize how many times the DB is being queried, but can't think of any other way to do it. both submitted_card_id and submitted_understood are form fields. -
Custom permission in django rest framework
I want to write a custom permission to restrict access to the display picture of a user. My user profile model is called Member and the implementation is as follows: # imports class Member(models.Model): created_at = models.DateTimeField(auto_now_add=True) user = models.OneToOneField(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE, unique=True) sex = models.IntegerField(choices=[(0, 'Unknown'), (1, 'Male'), (2, 'Female'), (9, 'Not Applicable')]) date_of_birth = models.DateField() bio = models.TextField(null=True) def __str__(self) -> str: return self.user.username def _display_picture_upload_path(instance, filename: str): return f'members/display/{instance.member}.jpg' class MemberDisplayPicture(models.Model): created_at = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to=_display_picture_upload_path) member = models.OneToOneField(to=Member, on_delete=models.CASCADE, related_name='display_picture', unique=True) The serializer for MemberDisplayPicture: class MemberDisplayPictureSerializer(serializers.ModelSerializer): class Meta: model = MemberDisplayPicture fields = ['id', 'image'] def create(self, validated_data): member_id = self.context['member_id'] instance = MemberDisplayPicture.objects.create(member_id=member_id, **validated_data) return instance A view at /{app_name}/members/{pk}/display-picture/ allows to retrieve, create and delete a display picture: class MemberDisplayPictureAPI(RetrieveModelMixin, CreateModelMixin, DestroyModelMixin, GenericAPIView): http_method_names = ['get', 'post', 'delete'] serializer_class = MemberDisplayPictureSerializer def get_member_id(self): member_id = self.kwargs['pk'] return member_id def get_queryset(self): return MemberDisplayPicture.objects.filter(member_id=self.get_member_id()) def get_object(self): queryset = self.filter_queryset(queryset=self.get_queryset()) obj = get_object_or_404(queryset) self.check_object_permissions(self.request, obj) return obj def get_serializer_context(self): return {'member_id': self.get_member_id()} def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) The custom permission should: Only allow authenticated … -
Persist user options, React
I am using JWT in a React-Django app to handle user authentication. I can register, login, and logout successfully. However, user data does not persist on the frontend. All of the tutorials and articles I've seen online suggest storing user data in local storage to persist the data, but I've also heard this isn't an excellent choice. Is there a better option? Can y'all point me towards articles/resources that cover any better options? Thanks -
Relative path import not working in main.js inside Django project
I have a javascript file main.js inside my Django project. I need to import into main.js the papaparse javascript module. I downloaded and saved papaparse.min.js inside my static folder. When I try to import papaparse into main.js, my script fails. My folder structure is set up like this: static .....js ..........main.js ..........papaparse.min.js I should mention, I tried running papaparse functions in-line in my html file and it works. So, I know there is no problem with the papaparse.min.js itself. Additionally, my settings life should be good since the main.js file is read in perfectly fine in my index.html: </div> <script src="{% static 'js/main.js' %}"></script> </body> </html> ^ This works fine. I've tried to do the import several ways. import * as pp from './papaparse.min.js'; console.log('made it past import'); import Papa from './papaparse.min.js'; console.log('made it past import'); import {Papa} from './papaparse.min.js'; console.log('made it past import'); When commenting out the import statement, the console will print "made it past import." If left uncommented, the console prints nothing. For troubleshooting purposes, the import statement and the console.log state are the only uncommented lines in main.js to verify that it's the import statement that's the problem. I've had some more experienced javascript coders (I'm … -
How to pass Django template language variables to JavaScript files
The question is partially related to this one here. In addition it should be noted that the notation used below is no safe. For more details see this blog post. I have a Django project that references multiple JS files. Initial the contents of those files were in the HTML but it slowly became too cluttered. The problem is that inside these files I am referencing image files, which are used for creating button elements (in my case easyButton instances from Leaflet). I am looking for a way to somehow fix these references. Note that I have called collectstatic and my HTML is using {% load static %} to load the static content. My JS files are also defined as Django template language variables themselves. I am thinking of perhaps at least loading all the references to the static files inside the HTML and then using those inside my JS files. Here is an example code: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="Content-Type" content="text/application/html; charset=iso-8859-1"> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="shortcut icon" href="#" /> <title>Test</title> </head> <body> ... </body> </html> <script> const TEST = {{ test }}; // The 'test' variable unwraps … -
Django queryset show english translations
This is my Django models.py: from django.db import models class Blog(models.Model): pub_date = models.DateTimeField('date published') def __str__(self): return self.pub_date class LanguagesCode(models.Model): code = models.CharField(max_length=5) def __str__(self): return self.code class BlogTranslation(models.Model): name = models.CharField(max_length=250) content = models.TextField(blank=True, null=True) blog_id = models.ForeignKey(Blog, related_name='translations', on_delete=models.CASCADE) language_code = models.ForeignKey(LanguagesCode, related_name='languages', on_delete=models.DO_NOTHING) class Meta: unique_together = ('blog_id', 'language_code') def __str__(self): return self.name I want to show the list of blogs those have english translation, with name in english. How do I need to write my query to get this data: [ { "name": "1st Blog name in english", "content": "content in english", "pub_date": "XXX" }, { "name": "2nd Blog name in english", "content": "content in english", "pub_date": "XXX" }, ] I use Django 4 with Django Rest Framework. This is my best try, which doesn't give me the result I want: Blog.objects.filter(translations__language_code = 2) -
Having both .filter() on query_param and .all() functionality without adding another ViewSet and end-point
I'm trying to avoid making another end-point to handle this query, but thinking there isn't a way around it. Wanted to run it by ya'll before doing so. Basically, I have Documents related to Customers and Products. I want to retrieve only the Documents for a specific Customer and Product. Here are the views.py: class DocumentsViewSet(viewsets.ModelViewSet): filter_backends = [StrictDjangoFilterBackend] filterset_fields = [ 'id', 'filename', ] queryset = Documents.objects.all() serializer_class = DocumentsSerializer class DocumentToCustomerViewSet(viewsets.ModelViewSet): filter_backends = [StrictDjangoFilterBackend] filterset_fields = [ 'id', 'customer_id', 'document_id' ] queryset = DocumentToCustomer.objects.all() serializer_class = DocumentToCustomerSerializer class DocumentToProductViewSet(viewsets.ModelViewSet): filter_backends = [StrictDjangoFilterBackend] filter_fields = [ 'id', 'product_id', 'document_id' ] queryset = DocumentToProduct.objects.all() serializer_class = DocumentToProductSerializer I'm thinking I can do something like this shorthand: class DocumentsViewSet(viewsets.ModelViewSet): filter_backends = [StrictDjangoFilterBackend] filterset_fields = [ 'id', 'filename' ] queryset = Documents.objects.filter(document_to_product__product_id=id, document_to_customer__customer_id=id) serializer_class = DocumentsSerializer Which does seem to work when I tested it. But then it I think I'd need to make another end-point to accommodate both the .all() and .filter()... I think. Additionally, haven't been able to get the filter_fields = [] to work with the relationship either. Trying to do something like /api/documents/?customer_id=123&product_id=123. I get a: TypeError: 'Meta.fields' must not contain non-model field names: Here are the models … -
Why doesn't my article send after I wrote two mixins?
I have written a view to send my form, but I had to level users, so I wrote two mixins, but now my author user can't send an article. View: from .mixins import FieldsMixin, FromValidMixin class ArticleCreate(LoginRequiredMixin, FromValidMixin , FieldsMixin , CreateView): model = Article template_name = "registration/article-create-update.html" Mixins: from django.http import Http404 class FieldsMixin(): def dispatch(self, request, *args, **kwargs): if request.user.is_superuser: self.fields = ["author" ,"title" , "slug" , "category" , "description" , "thumbnail" , "publish" , "status"] elif request.user.is_author: self.fields = ["title" , "slug" , "category" , "description" , "thumbnail" , "publish" , "status"] else: raise Http404("You can't see this page") return super().dispatch(request, *args, **kwargs) class FromValidMixin(): def form_valid(self, form): if self.request.user.is_superuser: form.save() else: self.obj = form.save(commit=False) self.obj.author = self.request.user self.obj.status = 'd' return super().form_valid(form) -
How do I not be placing login_required() in each of my views AND Place for all without having to write it in each one Python (Django)
Ej: **Quiero saber si hay alguna forma de indicarle a login_required algunas vistas en especificas sin tener que hacer esto en cada una Gracias ** ` @login_required() def vista1(request): pass @login_required() def vista2(request): pass @login_required() def vista3(request): pass @login_required() def vista4(request): pass @login_required() def vista5(request): pass ` algo Asi: nose si exista esa posibilidad ` login_required(vista1,vista2,vista3...etc) ` -
Acces static files in javascript on django
i am bilding a online music player from scrach and i moved to django . but i cant change my music from my js file like music.src = "{% static 'music/music.mp3' %}:" and i am loading the static files to , how can i accces the my music folder from inside the js file , btw my js and music are in the same static folder i have the music folder then the assets folder where my js files are . or can i just use music.src = "music/music.mp3" i loaded the files with {% load static %} and tryed to load the files with music.src = "{% static 'music/music.mp3' %}" but no results -
The calculated field on my django admin page is returning the average grade for the wrong column
I'm trying to add a computed column to one of my models on the admin page, specifically adding an average mark from a foreign key in my Mark model, and adding it to the relevant Student in my student model. When I run an aggregate avg command within my StudentAdmin class, it returns the average of the grades id field, not the mark field. Here is the relevant code: models.py class Student(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True) def __str__(self) -> str: return self.last_name class Meta: ordering = ['last_name'] class Module(models.Model): module = models.CharField(max_length=255) class Grade(models.Model): mark = models.PositiveSmallIntegerField(null=True) module_id = models.ForeignKey(Module, on_delete=models.PROTECT) student_id = models.ForeignKey(Student, on_delete=models.PROTECT) def __str__(self) -> str: return self.mark ... admin.py ... @admin.register(models.Student) class StudentAdmin(admin.ModelAdmin): list_display = ['id', 'first_name', 'last_name', 'average_grade'] def average_grade(self, student): return student.average_grade def get_queryset(self, request): return super().get_queryset(request).annotate( average_grade = Avg('grade') ) How do I specify which column from Grade to use? -
how can I change a button value to remove from cart if product is already in session
I been trying to changing the button add to cart to remove from cart if it happens that products is in session. This is the template: products.html ... <div id="products-list" class="grid grid-cols-4 gap-4"> {% for product in products %} <div class="card"> <div class="image-container"> <img class="img" src="{% static product.image %}" alt="Card image cap"> </div> <div class="container"> <h5 class="card-title">{{ product.product_name }}</h5> <p class="card-text">{{ product.description }}</p> <p class="card-text">Price - &#8358;{{ product.price }}</p> <form action="{% url "add-cart" %}" method="POST"> {% csrf_token %} <input type="hidden" name="product_id" value= "{{ product.id }}"> from here is where I have problems. I am trying to put an if condition that changes the value of the button e.g if product is in session it will show the remove from cart button, else it will show the add to cart button. {% comment %} {% if {{ request.session.stored_item }} %} {% endif %} {% endcomment %} {% comment %} document.getElementById("btn-green").addEventListener("click", function() { document.getElementById("btn-green").innerText = "remove from cart" }) {% endcomment %} </form> </div> </div> {% endfor %} # views.py # def products(request): # stored_items = request.session.get("stored_items") # product_item = Product.objects.filter(id__in=stored_items) products = Product.objects.all() if 'query' in request.GET: query = request.GET['query'] multiple_q = Q(Q(product_name__icontains=query) | Q(description__icontains=query)) products = Product.objects.filter(multiple_q) # products = … -
InMemoryUploadedFile Django File Read in Bytes - str vs utf8
I'm looking to read the binary content of a Django type InMemoryUploadedFile. The file type/encoding is a variable, so I don't want to assume UTF8, I simply want to read the binary content, then I want to encode with UTF8. Here's what I've tried: str(file.read()).replace('\n', '\r\n') This looks to work, except the string still has the binary 'b' character. To fix this, I tried: file.read().decode('utf8').replace('\n', '\r\n') This works well for reading .txt files. Any other file types fail to read properly, understandably. How can I read the binary content of type "InMemoryUploadedFile" without specifying an encoding? -
{%static %} the page displays the line itself {%load static %} instead of loading the desired file
I wanted to connect a css file to this html file, I wanted to add it via {%load struct%} `{% load static %} <!DOCTYPE html> <html lang="ru"> <head> <title>Brewtopia Cafe form</title> <meta charset="UTF-8"> <link rel="stylesheet" href="{% static 'css/style_contact.css' %}"> </head> <body> <header>` this is urls.py in the app `from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.Brewtopia_view, name='brewtopia'), path('Contact/', views.Contact_view, name='contact') ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ` these are views.py in the app `from django.shortcuts import render def Brewtopia_view(request): return render(request, 'Brewtopia.html') def Contact_view(request): return render(request, 'Contact.html') ` settings.py settings in static `STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ]` the css file is located in the folder C:\Projects\brew\brewtopia\users\static\users\css I added struct and wanted to upload a css file, but the error is in the screenshot enter image description here but even if you delete {%loadstruct%} it won't work -
When the checkbox is checked then immediately get the result in Django
This is my View.py def weight(request): selected_values = request.GET.get('selected_values[]') p = Product.objects.filter(load = selected_values) context = {'prod_fil_by_weight':p} return render(request, 'product-filter.html', context) This is my Template I just want to render the data on same html template. `<div class="checkbox"> {% for w in weight %} {{ w.name }} {% for n in prod_fil_by_weight %} <h5>{{ n.name }}</h5> <h5>{{ n.price }}</h5> <h5>{{ n.old_price }}</h5> <h5>{{ n.image.url }}</h5> <h5>{% endfor %} {% endfor %}` This is my AJAX which I was Created. <script type="text/javascript"> $(document).ready(function() { $('.myCheckbox').change(function() { var selectedValues = []; $('.myCheckbox:checked').each(function() { selectedValues.push($(this).val()); }); $.ajax({ url: "/weight/", data: { 'selected_values[]': selectedValues }, success: function(response) { $('#data-container').html(response.result); } }); }); }); </script> I just want to get immediate result and render the data in the same template. when the checkbox is checked no matter only one checkbox is checked or multiple checkboxes is checked I just want the data get and render to the same template (Most of the website use this feature like when you check the checkbox then immediately you get the result without redirecting any other page. the feature name is Real Time Feedback if I am right). I research a lot but I fail my last hope is … -
how i can fix an smtp error in Django im using gmail
i have this error this morning after a year using it. Anyone knows how i can fix this?Error here I was looking for a solution but i cant find anything -
Fast CGI Handler not installed in Windows IIS
I am trying to run a Django app with IIS server. Here are my settings: Windows Server 2019, IIS 10.\ I am following this tutorial. I am setting up my server and added CGI as shown in the image. enter image description here But, when i deploy the app, i get an error saying that the "FastCgiModule" is not in the list. enter image description here I looked in HandlerMappings to find that the FastCgiModule was indeed not in the list of modules that IIS considers. Help and understanding about this is much appreciated. Things tried Added wfastcgi.exe path to the system path. Expectation: In case that was the reason FastCGI wasn't being built, this would fix it. Result: No change. Installed ASP.net and .NET frameworks. Expectations: If these are dependencies for the FastCGI framework, it might help install it. Result: No change. -
Django Rest Framework - Data is Not Refreshed from Table When Inserted directly from Oracle
When I am manually inserting some records from Oracle directly, it is not refreshed from my Django Rest API application. Only the data that is inserted from POST request from the application is shown in the GET requests. I can see all the rows in the oracle table but it is not showing up in django application. I have created this table from Django itself by migrating all the changes. How can I refresh the queryset to ensure it fetches all the table records no matter where the data was inserted from? Below is my code: Model: class Genre(models.Model): genre_id = models.AutoField(primary_key=True) genre_name = models.CharField(max_length=60) def __str__(self): return self.genre_name class Meta: db_table = "GENRE" Serializer: class GenreSerializer(serializers.ModelSerializer): class Meta: model = Genre fields = "__all__" ViewSet: class GenreViewSet(viewsets.ModelViewSet): queryset = Genre.objects.all() serializer_class = GenreSerializer -
Slow "waiting for server response" in django-plotly-dash
I have a django project that includes many dash apps through django-plotly-dash. I noticed a strange increase in callback update latency recently and cannot identify the cause. I put together a simple dash app with three sequential callbacks below as an example. When I run the app locally in my main project, each callback takes about 500 ms to run. When I run the same app in a brand new django project, each callback only takes 50 ms to run. Looking at the performance monitor in my browser, the difference appears to be in the dash_renderer js "waiting for server response." Is there a way to identify what is happening for the server to respond quickly in one django project versus another? views.py: from django.shortcuts import render from . import lightning def thunder(request): return render(request, 'dpd/thunder.html') lightning.py (the dash app): from dash import dcc, html from dash.dependencies import Input, Output from django_plotly_dash import DjangoDash app = DjangoDash('lightning', external_stylesheets=['https://codepen.io/chriddyp/pen/bWLwgP.css']) app.layout = html.Div([ dcc.Input( id='x0', type='number', value=0 ), html.Table([ html.Tr([html.Td(['x+1']), html.Td(id='x1')]), html.Tr([html.Td(['x+2']), html.Td(id='x2')]), html.Tr([html.Td(['x+3']), html.Td(id='x3')]), ]), ]) @app.callback( Output('x1', 'children'), Input('x0', 'value') ) def callback1(x): return x+1 @app.callback( Output('x2', 'children'), Input('x1', 'children') ) def callback2(x): return x+1 @app.callback( Output('x3', 'children'), Input('x2', 'children') … -
Hola tengo un error con el admin de django en jazzmin [closed]
Cuando entro a una aplicacion en la tabla me aparece con este bug y no se como solucionarlo enter image description here necesito ayuda lo antes posible -
About the URL.createObjectURL
I am a beginner in django with python, there is a problem i confronting now is that I have a image URL e.g. "http://127.0.0.1:8000/media/images/user_1/XXXX.jpg" and I am trying to use URL.createObjectURL to do a preview, but it is not work. There is the error message: companymanage:1278 Uncaught TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed. at Object.success (companymanage:1278:73) at c (datatables.min.js:14:28327) at Object.fireWith [as resolveWith] (datatables.min.js:14:29072) at l (datatables.min.js:14:79901) at XMLHttpRequest.<anonymous> (datatables.min.js:14:82355) I already try the image URL in chrome browser and arrived the image successfully. So why i can not use the path in URL.createObjectURL? Is the createObjectURL only accept File, Blob only and i enter the path so case this problem?? Is any solution suggest ??? -
MultiValueDictKeyError at /register/ request method post
MultiValueDictKeyError at /register/ 'name' Request Method: POST Request URL: http://127.0.0.1:8000/register/ Django Version: 4.1.7 Exception Type: MultiValueDictKeyError Exception Value: 'name' Exception Location: C:\Users\vaibh\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\datastructures.py, line 86, in getitem Raised during: main.views.register Python Executable: C:\Users\vaibh\AppData\Local\Programs\Python\Python311\python.exe Python Version: 3.11.2 Python Path: ['V:\MEMEPROJECT\meme', 'C:\Users\vaibh\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\vaibh\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\vaibh\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\vaibh\AppData\Local\Programs\Python\Python311', 'C:\Users\vaibh\AppData\Local\Programs\Python\Python311\Lib\site-packages'] Server time: Fri, 24 Feb 2023 17:10:06 +0000 here i M TRYING TO GET USER DETAILS but this error MultiValueDictKeyError at /register/ is coming -
How do I stop logs before Django sets up logging
I have a call to Initialization() in wsgi.py in my django app that gets made before django calls setup(). Within that call to Initialization(), there is another call made to IdentityService() which is an imported library. This results in the logs from IdentityService() going to STDOUT when my django app initializes and I want to suppress these logs. The django app uses the normal LOGGING setting, configured by dictConfig(). Am I right in assuming that because the call on the Initialisation class gets made before configure_logging is called by setup(), the LOGGING dictionary can't control the logs of IdentityService() going to STDOUT? Any suggestions for how I can stop these logs being sent to STDOUT? -
Pytest not recognizing tests in some installed apps in django
I have an issue with pytest in which it executes tests in some installed apps but ignores some even after specifically trying to run tests on that said app it still won't recognize the app. The app that's not recognize currently is named file_upload when ever i run pytest with pytest it detects all tests in other apps (collected 52 items) excludes file_upload , when i also run pytest -k file_upload still says it collected 52 items and deselected 52 items, i named the test file with test_endpoints.py and in my pytest.ini i have the following configurations: [pytest] addopts = --ds=config.settings.test --reuse-db python_files = tests.py test_*.py i added file_storage to my installed apps and works perfectly when running migrations and the rest so it's probably a pytest issue but i can't figure exactly what.