Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
User permission cache in Django-Webtest
My project uses a custom authentication backend for managing user permissions, leaving the authentication itself intact (to be handled by Django). The backend works fine by itself but started failing in tests, built using Django WebTest. After picking around, I discovered that the culprit is the injection by DWT of another auth backend into the first position in settings.AUTHENTICATION_BACKENDS. My backend directly extends Django’s ModelBackend while DWT’s own backend is based off RemoteUserBackend, which in the end is also an extension of ModelBackend. This bit is important, because while DWT does not define a has_perm method, it is present on its backend nevertheless. The django.contrib.auth.backends.ModelBackend’s get_all_permissions() caches the permissions on the user object in question, when performing a has_perm test: if not hasattr(user_obj, '_perm_cache'): user_obj._perm_cache = { *self.get_user_permissions(user_obj), *self.get_group_permissions(user_obj), } return user_obj._perm_cache Since DWT’s backend comes first in tests, the cache is populated and would not contain the permissions set by my backend, ultimately causing the has_perm test to fail. Ref the code snippet from within Django: def _user_has_perm(user, perm, obj): """ A backend can raise `PermissionDenied` to short-circuit permission checking. """ for backend in auth.get_backends(): if not hasattr(backend, 'has_perm'): continue try: if backend.has_perm(user, perm, obj): return True except PermissionDenied: … -
User permission cache in Django-Webtest
My project uses a custom authentication backend for managing user permissions, leaving the authentication itself intact (to be handled by Django). The backend works fine by itself but started failing in tests, built using Django WebTest. After picking around, I discovered that the culprit is the injection by DWT of another auth backend into the first position in settings.AUTHENTICATION_BACKENDS. My backend directly extends Django’s ModelBackend while DWT’s own backend is based off RemoteUserBackend, which in the end is also an extension of ModelBackend. This bit is important, because while DWT does not define a has_perm method, it is present on its backend nevertheless. The django.contrib.auth.backends.ModelBackend’s get_all_permissions() caches the permissions on the user object in question, when performing a has_perm test: if not hasattr(user_obj, '_perm_cache'): user_obj._perm_cache = { *self.get_user_permissions(user_obj), *self.get_group_permissions(user_obj), } return user_obj._perm_cache Since DWT’s backend comes first in tests, the cache is populated and would not contain the permissions set by my backend, ultimately causing the has_perm test to fail. Ref the code snippet from within Django: def _user_has_perm(user, perm, obj): """ A backend can raise `PermissionDenied` to short-circuit permission checking. """ for backend in auth.get_backends(): if not hasattr(backend, 'has_perm'): continue try: if backend.has_perm(user, perm, obj): return True except PermissionDenied: … -
Render images with Vue.js and Django
I am currently building a LMS where the admin can upload multiple images to a lesson. I am having some issues rendering these images with vue.js. In my models.py I have a Photos model which uses a foreignkey to the lesson model. In the admin I can add the images but in the html the images appear as an empty list with the photo id number e.g [4] In the console I can see the photos array with the length of photos in the lesson object but I cant seem to attach it to the frontend. Here is the vue template: <div class="column is-10"> <template v-if="$store.state.user.isAuthenticated"> <template v-if="activeLesson"> <h2>{{ activeLesson.title }}</h2> {{ activeLesson.long_description }} {{ activeLesson.photos }} <hr> The models.py: class Lesson(models.Model): DRAFT = 'draft' PUBLISHED = 'published' CHOICES_STATUS = ( (DRAFT, 'Draft'), (PUBLISHED, 'Published') ) ARTICLE = 'article' QUIZ = 'quiz' CHOICES_LESSON_TYPE = ( (ARTICLE, 'Article'), (QUIZ, 'Quiz') ) course = models.ForeignKey(Course, related_name='lessons', on_delete=models.CASCADE) title = models.CharField(max_length=255) slug = models.SlugField() short_description = models.TextField(blank=True, null=True) long_description = models.TextField(blank=True, null=True) status = models.CharField(max_length=20, choices=CHOICES_STATUS, default=PUBLISHED) lesson_type = models.CharField(max_length=20, choices=CHOICES_LESSON_TYPE, default=ARTICLE) def __str__(self): return self.title class Photo(models.Model): lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, related_name='photos') photo = models.ImageField(upload_to ='lesson_images') # resizing the image, you can … -
question on django FileField handling and clean method
I have a rather simple model: class Product(models.Model): data = models.JSONField() number = models.PositiveIntegerField() which I can update via a form: class ProductForm(forms.Form): def __init__(self, *args, **kwargs): product = kwargs.pop("product") super().__init__(*args, **kwargs) self.fields["number"] = forms.IntegerField() self.fields[product.data.keys()[0]] = forms.CharField() self.fields[product.data.keys()[1]] = forms.FileField() ... def clean(self): cleaned_data = super().clean() print(cleaned_data.get("image")) ## prints None print(self.files) ## prints: which all works fine, I put the form in the template with an enctype="multipart/form-data" attribute set and then I receive the form in my TemplateView: class ProductUpdateView(TemplateView): template_name = "update_product.html" def post(self, request, *args, **kwargs): obj = Product.objects.get(pk = kwargs["pk"]) print(request.FILES) ## prints the correct filename! ... return render(request, self.template_name, context) Why is self.files printing None, also cleaned_data.get("image") printing <MultiValueDict: {}>, but in the view, request.FILES correctly knows of <MultiValueDict: {'image': [<InMemoryUploadedFile: test.png (image/png)>]}>? -
Django react application Forbidden 403
When added permission class to view, have an error Forbidden 403 @api_view(['GET']) @permission_classes([IsAdminUser]) def getUsers(request): users = User.objects.all() serializer = UserSerializer(users, many=True) return Response(serializer.data) how to fix that? -
Is there any way to re-render/rerun a custom block in HTML again on button Click?
I am trying to change the List Content in HTML in a Section. I want to change List whenever a category is changed . The content needs to be changed without page reload. Cannot call function from js as it will call the main function responsible for rendering the whole page in Views.py SO functionality should be like: 1 Category clicked 2 List of items in that category changes without loading the whole page Q2 Is there any way to re run a part of code in HTML like {% block run_it_again_ %} code {% end block%} -
psycopg2.errors.UndefinedTable: relation "authentication_author" does not exist: Django v4
I tried to start using Postgresql instead of sqlite in my Django project. I installed postgreqL ON MY Windows, creatred a new database, user and password. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'database_name', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': 'localhost', 'PORT': '5432', } } But when I try to migrate or makemigrations, I got this: File "C:\Users\s...\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "authentication_author" does not exist LINE 1: ...hentication_author"."is_doctor" FROM "authentic... here is my model: class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name="author") slug = models.CharField(max_length=50, null=True, blank=True,) is_doctor = models.BooleanField(default=False) And yes, I deleted the sqlite3 database, all the migrations folders and I created new ones with the init.py inside of them. But still get the same problem. -
objects are swapped when running tests in django
I want to apologize right away if I explained something incorrectly. I am writing this via google translate Django shows error in test after one test. The test succeeds once and then fails. If I don't even change anything, then one still passes, and the other does not. Tests def create_category(): return Category.objects.create(category_title='Category title', slug='category-title') def create_news(category, title, text='news text', pub_date=timezone.now()): return News.objects.create(category=category, image=None, title=title, text=text, pub_date=pub_date) class HomePageTestCase(TestCase): def test_no_news(self): response = self.client.get(reverse('news:home')) self.assertEqual(response.status_code, 200) self.assertContains(response, 'News not found') self.assertQuerysetEqual(response.context['last_20_news'], []) def test_one_news(self): category = create_category() news = create_news(category, 'News title') response = self.client.get(reverse('news:home')) self.assertQuerysetEqual(response.context['last_20_news'], ['<News: News title>']) def test_multiple_news(self): category = create_category() news_1 = create_news(category, 'News title 1') news_2 = create_news(category, 'News title 2') response = self.client.get(reverse('news:home')) self.assertQuerysetEqual(response.context['last_20_news'], ['<News: News title 2>', '<News: News title 1>']) class CategoryPageTestCase(TestCase): def test_no_news_from_category(self): category = create_category() response = self.client.get(category.get_absolute_url()) self.assertEqual(response.status_code, 200) self.assertContains(response, 'News not found') self.assertQuerysetEqual(response.context['news_from_category'], []) def test_one_news_from_category(self): category = create_category() news = create_news(category, 'News title') response = self.client.get(category.get_absolute_url()) self.assertQuerysetEqual(response.context['news_from_category'], ['<News: News title>']) def test_multiple_news_from_category(self): category = create_category() news_1 = create_news(category, 'News title 1') news_2 = create_news(category, 'News title 2') response = self.client.get(category.get_absolute_url()) self.assertQuerysetEqual(response.context['news_from_category'], ['<News: News title 2>', '<News: News title 1>']) Views for which tests were created class HomePageView(ListView): … -
405 Method Not Allowed when deployed but locally no problem
I am new on this forum so please excuse me if I am writing in the wrong category or my question is not complete. We have a simple frontend based on VueJS which has been deployed on a VPS (vps1) and a backend based on Djangorestframework which has been deployed on another VPS (vps2). When we run the frontend locally ($ npm run serve) it can connect to the previously-deployed backend but when we deploy the frontend on Debian serving it using NginX, we get the following error when a user wants to login: [HTTP/1.1 405 Not Allowed 29ms] and also Status 405 Method Not Allowed Version HTTP/3 Transferred 2.22 KB (0 B size) Referrer Policystrict-origin-when-cross-origin I would be happy for any help. The method which is being used is POST. Here is the content of vue.config.js (Vue) module.exports = { devServer: { proxy: { "/accounts/": { target: "https://my-api-server-is-here.com", changeOrigin: true, secure: false, }, }, }, }; and here is the content of settings.py (Djangorestframework): CORS_ALLOW_ALL_ORIGINS = False CORS_ALLOWED_ORIGINS = [ "https://my-frontend-url.com", ] CSRF_TRUSTED_ORIGINS = [ "my-frontend-url.com", ] CORS_ALLOW_CREDENTIALS = True -
CustomUser() got an unexpected keyword argument 'profile_pic'
I am getting an error while submitting a form in my webapp. I am not sure where the problem is occurring in Custom user? U have added the profile_pic field in my models, forms and using it in my views function. But when i try to submit the data using the form, the problem occurs. Here are my codes. Forms.py class CustomUserForm(FormSettings): email = forms.EmailField(required=True) gender = forms.ChoiceField(choices=[('M', 'Male'), ('F', 'Female')]) first_name = forms.CharField(required=True) username=forms.CharField(label="Username",max_length=50,widget=forms.TextInput(attrs={"class":"form-control","autocomplete":"off"})) last_name = forms.CharField(required=True) address = forms.CharField(widget=forms.Textarea) password = forms.CharField(widget=forms.PasswordInput) profile_pic = forms.ImageField() widget = { 'password': forms.PasswordInput(), } def __init__(self, *args, **kwargs): super(CustomUserForm, self).__init__(*args, **kwargs) if kwargs.get('instance'): instance = kwargs.get('instance').admin.__dict__ self.fields['password'].required = False for field in CustomUserForm.Meta.fields: self.fields[field].initial = instance.get(field) if self.instance.pk is not None: self.fields['password'].widget.attrs['placeholder'] = "Fill this only if you wish to update password" def clean_email(self, *args, **kwargs): formEmail = self.cleaned_data['email'].lower() if self.instance.pk is None: # Insert if CustomUser.objects.filter(email=formEmail).exists(): raise forms.ValidationError( "The given email is already registered") else: # Update dbEmail = self.Meta.model.objects.get( id=self.instance.pk).admin.email.lower() if dbEmail != formEmail: # There has been changes if CustomUser.objects.filter(email=formEmail).exists(): raise forms.ValidationError("The given email is already registered") return formEmail class Meta: model = CustomUser fields = ['username','first_name','last_name','email', 'gender', 'password','address','profile_pic'] class AddStudentForm(CustomUserForm): def __init__(self, *args, **kwargs): super(AddStudentForm, self).__init__(*args, **kwargs) … -
How to make edit function work in views.py Django
I am creating an edit option for my entry. But instead of redirecting to the entry page, it is taking me to the addpage to create a new form. How do I redirect to the edit page? Also, how do I make sure that the users previous input would reflect when they click on the edit button. I used initials - is this the best way to do it since I'm not using models but rather forms.Form. VIEWS.PY class AddPageForm(forms.Form): title = forms.CharField(max_length=20) content = forms.CharField(widget=forms.Textarea( attrs={ "class": "form-control", "placeholder": "Tell us more!" }) def edit_page(request, title): entry = util.get_entry(title) if request.method == "POST": form = AddPageForm(request.POST, initial={ "title": title, "content": content }) if form.is_valid(): util.save_entry(title, content) return redirect('encyclopedia:entrypage', title=title) else: form = AddPageForm() return render(request, "encyclopedia/editpage.html", {"form":form}) EDIT PAGE {% block body %} <h1>Edit {{ title }}</h1> <form action="" method="post"> {% csrf_token %} {% form %} <input type="submit" value="Submit" class="btn btn-secondary"> </form> ENTRY PAGE {% block body %} {{ content|safe }} <a href="{% url 'encyclopedia:editpage' title=title %}" class="btn btn-primary">Update</a> <!-- <input="text" name="title" value="{{game.title}}" /> <input="text" name="genre" value="{{game.genre}}" /> --> {% endblock %} URLS.PY app_name = "encyclopedia" urlpatterns = [ path("add_page", views.add_page, name="addpage"), path("edit_page/<str:title>", views.edit_page, name="editpage") ] -
Using selected fields from ModelMultipleChoiceField to run a SQL query
I'm learning Django and I'm trying something that may be unorthodox. In forms.py, I have the following class: class CompareFormClient(forms.ModelForm): class Meta: model = OrderFile fields = ['origine'] items = forms.ModelMultipleChoiceField( widget=FilteredSelectMultiple( 'items', False, ), queryset=OrderFile.objects.all().values_list('reference', flat=True) ) In models.py, I have these two classes: class OrderFile(models.Model): uploadedfile = models.ForeignKey(File, on_delete=models.CASCADE, default=1) ean = models.CharField(max_length=50) designation = models.TextField(blank=True) reference = models.CharField(max_length=200) quantite = models.IntegerField() prix_unitaire = models.IntegerField(blank=True) prix_total = models.IntegerField(blank=True) poids_unitaire = models.IntegerField(blank=True) poids_total = models.IntegerField(blank=True) composition = models.TextField(blank=True) origine = models.IntegerField(blank=True) nomenclature_douaniere = models.CharField(max_length=50) reference_transport = models.CharField(max_length=50) class DeliveryFile(models.Model): uploadedfile = models.ForeignKey(File, on_delete=models.CASCADE, default=1, db_constraint=False) ean = models.CharField(max_length=50) designation = models.TextField(blank=True) reference = models.CharField(max_length=200) quantite = models.IntegerField() prix_unitaire = models.IntegerField(blank=True) prix_total = models.IntegerField(blank=True) poids_unitaire = models.IntegerField(blank=True) poids_total = models.IntegerField(blank=True) composition = models.TextField(blank=True) origine = models.IntegerField(blank=True) nomenclature_douaniere = models.CharField(max_length=50) reference_transport = models.CharField(max_length=50) Both models OrderFile and DeliveryFile are already filled with data. In my form, I select values from the following queryset : queryset=OrderFile.objects.all().values_list('reference', flat=True). My objective is to run a SQL query to find any differences with the selected values (from ModelMultipleChoiceField) between two tables. This SQL query would be the following: SELECT id --want to use the selected values from the django form here FROM foo FULL OUTER … -
How to implement SocketIO in Django ASGI
I tried this; https://github.com/ly3too/django-channels-with-socket.io But I keep getting 404 for the socket-io. Are there any other methods to implement the socket io? -
html2canvas javascript screenshot pass to python
would it be possible to use html2canvas to take a picture of the user`s screen but also i wanna use this image with python function. What I want to do is save the image of the html element with javascript and send it to slack with python. function capture() { html2canvas(document.getElementById("main"), { letterRendering: 1, allowTaint: true, useCORS: true, }) .then(function (canvas) { document.getElementById("result").src = canvas.toDataURL("image/png", 0.5); }) .catch((e) => { alert(e); }); } -
Django slug with id in url
How can made a url with slug and id, like: https://example.com/product/beauty-slug/1 The Product model can accept repeated title product, and insted use unique slug i prefer use the slug with id models.py class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product_title = models.CharField(max_length=255, default='product_title') slug = models.SlugField(max_length=250,unique=True,null=True) def __str__(self): return self.product_title def get_absolute_url(self): return reverse('product_change', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.product_title) return super().save(*args, **kwargs) And how use it in a template product_list.html <a href="{% url 'product_view' product.slug %}">see product</a> urls.py ... path('product/<slug:slug>', ProductView.as_view(), name='product_view'), ... Thats works, but i know i gona have identical products title, so i think with id is better to my case, becouse if needed costumer can reference the order to seller with id number... -
how to have different anchor tag in the same for loop
** {% for i in objectss %} <div class="col-lg-4 col-md-6 col-12" data-aos="fade-up" data-aos-delay="400"> <div class="class-thumb"> <a href="accounts/let/"><img src="{{i.image.url}}" class="img-fluid" alt="Class"></a> <div class="class-info"> <h3 class="mb-1">{{i.name}}</h3> <span><strong>Trained by</strong> - Bella</span> <span class="class-price">₹{{i.price}}</span> <p class="mt-3">{{i.desc}}</p> </div> </div> </div> {% endfor %} **``` {% for i in objectss %} <div class="class-info"> <h3 class="mb-1">{{i.name}}</h3> <span><strong>Trained by</strong> - Bella</span> <span class="class-price">₹{{i.price}}</span> <p class="mt-3">{{i.desc}}</p> </div> </div> </div> {% endfor %}``` In this code for loop helping to display 6 typer of excercises on my html page. I want to add anchor tags for user so that if the user click on the singing image he get redirected to singing excercise page and same for other excercises. -
Closed connection: Django channels with async websockets
I'm trying to run this command, but it keeps closing the websocket connection: #!/usr/bin/env python from django.core.management.base import BaseCommand from channels.layers import get_channel_layer from asgiref.sync import async_to_sync class Command(BaseCommand): help = "Send message" def handle(self, **options): channel_layer = get_channel_layer() msg = { 'type': 'hello', 'content': 'hello' } async_to_sync(channel_layer.group_send)('chat', msg) print('done') I followed all the steps and examples (like this guide: https://channels.readthedocs.io/en/latest/topics/channel_layers.html#using-outside-of-consumers), the rest of the websocket code is working (using redis) and I can send/receive messages from a javascript frontend page. Here's the output I get from the command: Creating tcp connection to ('redis', 6379) Closed 1 connection(s) done I don't see any Redis errors, it's just a fresh docker container. -
Python get screenshot from active page's element
i want to take screenshot of django active page's elements. I research about selenium and playwright but they opening the pages on new browser. The page on which I want to take the screenshot has dynamic information and it is constantly changing, so it is not appropriate to take a screenshot by opening it on a new page. Each user will enter different information on the opened page and take a screenshot of the relevant element. -
Having Error page Not found Using Django Id based URLs in detail Page
i m having this type of error my hyperlink is look lke this my view functon look like that url patterns look lik that -
Video Conferencing Implementation in website
I have idea to implement video conferencing in my helath care website project & I don't know how to implement it. So it will be great favor to help -
Django websocket: Can't send message to channel outside consumer
I'm trying to get this example to work: https://channels.readthedocs.io/en/latest/topics/channel_layers.html#using-outside-of-consumers I have a Django application that starts a connection over websocket, and a command that sends a message, like this: from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): await self.channel_layer.group_add("chat", self.channel_name) await self.accept() print(f'[{self.channel_name}] - You are connected') async def disconnect(self, close_code): await self.channel_layer.group_discard( "chat", self.channel_name ) #!/usr/bin/env python from django.core.management.base import BaseCommand from channels.layers import get_channel_layer from asgiref.sync import async_to_sync class Command(BaseCommand): help = "Send message" def handle(self, **options): channel_layer = get_channel_layer() msg = {"message": 1} async_to_sync(channel_layer.group_send)('chat', msg) When I connect from a webapp, I get this log: [specific..inmemory!XodgAfVQQhKL] - You are connected Running the command does nothing..what am I missing? -
Only accept 15 seconds video file
I have django app I want to know how can I take a 15 second video file Force to take 15 seconds I am using react as frontend with django-rest-framework any idea ? -
Django DRF - API shows json format instead of interface
I recently updated to Django 4.0 and DRF 3.13.1, and now my API shows in json format by default, whereas before it was showing the interface. I would like to see an interface like so: But this is what I now get. Is there a way to change this back to the interface? Sorry if this is a silly question. -
Can I call a function in both create and update in ModelSerializer
Can i call same function in both create and update without overriding it? Hi im fairly new at this and trying to implement my code using the DRY principle. So im calling a function say for create_update_password in ModelSerializer's while creating or changing the password for this i have to override create and update in ModelSerializer and create_update_password in both of them. Im not doing any extra functionality in any of them them apart from calling this function. So is there any way that i can invoke this function in create and update without overrding it. Ill really appericiate it if anyone can give any suggestion. Below is the code Example Thanks You def create_update_password(self, instance, validated_data): password = validated_data["password"] instance.set_password(password) instance.save() class UserModelSerializer(ModelSerializer): def create(self, validated_data): instance = super(UserModelSerializer, self).create(validated_data) self.create_update_password(instance, validated_data) return instance def update(self, instance, validated_data): instance = super(UserModelSerializer, self).update(instance, validated_data) self.create_update_password(instance, validated_data) return instance -
Set specific valdiation rule in UpdateView
I set an UpdateView class to update data of user's markers. I have a Marker model with a field category. I want to have one and only "Where I live" category marker in all the user's markers. Is there a way to create a function in the UpdateView class to invalidate the form if there too many "Where I live" markers. class UpdateMarkerView(UpdateView): model = Marker fields = ["name", "description", "category"] template_name = "map/detail.html" success_url = "/" class Marker(models.Model): WIL = "WIL" WIWG = "WIWG" WIW = "WIW" IDK = "IDK" CATEGORY_MARKER = [(WIL,"Where I live"), (WIWG, "Where I want to go"),(WIW,"Where I went"),(IDK,"I don't know")] user = models.ForeignKey(User,blank=True, null=True,on_delete = models.SET_NULL) name = models.fields.CharField(max_length=100) description = models.fields.CharField(max_length=100) lat = models.fields.DecimalField(default=False, max_digits=5, decimal_places=3) lon = models.fields.DecimalField(default=False, max_digits=5, decimal_places=3) category = models.CharField(max_length=50, choices = CATEGORY_MARKER, default = IDK) I've already done it with a basic function but I can't find a way to it with a generic view if it's possible.