Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
You don't have permission for this user error when trying to update profile
Getting the error message "authorize": "You don't have permission for this user." when trying to update a user profile. I can update information from my default user class (ie.username, first_name, last_name etc), but only if I remove all reference to city, country and bio (anything related to information stored in my extended model and keep my update method nested under class Meta:. Here is my serializer: #updating user profile class UpdateUserSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=False) city = serializers.CharField(source='profile.city') country = serializers.CharField(source='profile.country') class Meta: model = User #, 'city', 'country', 'bio' fields = ['username', 'email', 'password', 'first_name', 'last_name', 'city', 'country'] extra_kwargs = {'username': {'required': False}, 'email': {'required': False}, 'password': {'required': False}, 'first_name': {'required': False}, 'last_name': {'required': False}, 'city': {'required': False}, 'country': {'required': False} } def validate_email(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(email=value).exists(): raise serializers.ValidationError({"email": "This email is already in use."}) return value def validate_username(self, value): user = self.context['request'].user if User.objects.exclude(pk=user.pk).filter(username=value).exists(): raise serializers.ValidationError({"username": "This username is already in use."}) return value def update(self, instance, validated_data): #re-writing updated profile info from request user = self.context['request'].user profile = instance.profile if user.pk != instance.pk: raise serializers.ValidationError({"authorize": "You don't have permission for this user."}) instance.first_name = validated_data['first_name'] instance.last_name = validated_data['last_name'] instance.email = validated_data['email'] instance.username = validated_data['username'] instance.save() … -
Django 3.2.9 Url Path İmportError
I have created a django project called "blogprojesi". I want to import the urls.py file inside the application I created with the name "inf" to the urls.py file inside this project, but I am getting the following error ImportError: cannot import name 'inf' from 'blogprojesi' (.....\blogprojesi\blogprojesi_init_.py) I guess somehow it doesn't see the inf app. I tried the Re_path thing but it didn't work. How can I solve this? **urls.py file inside the "blogprojesi"** from django.contrib import admin from django.urls import path,include from blogprojesi import inf from blogprojesi.inf import urls urlpatterns = [ path('admin/', admin.site.urls), path('',inf,include('inf.urls')), ] **Contents of urls.py file inside inf application** from django.urls import path from . import views urlpatterns = [ path("",views.index), path("index",views.index), path("blogs",views.blogs), path("blogs/<int:id>",views.blog_details), ] **Contents of views.py file inside inf application** from http.client import HTTPResponse from django.http.response import HttpResponse from django.shortcuts import render def index(request): return HttpResponse("Home Page") def blogs(request): return HttpResponse("blogs") def blog_details(request,id): return HttpResponse("blog detail: "+id) -
Disable pagination inspector on drf_yasg
Hi guys im using drf_yasg to create my swagger documentation but I have an issue with a PaginationInspector. In one of my views I declare a paginator and, in swagger, is shown as the default pagination for swagger. Something like this count* integer #This info is generated automatically by swagger next string($uri) #This info is generated automatically by swagger x-nullable: true #This info is generated automatically by swagger previous: string($uri) #This info is generated automatically by swagger x-nullable: trueç results: (THE BODY I ACTUALLY WANT TO SHOW) I would like that the swagger ignore that pagination but haven’t found any info related to it. i try using the decorator, initially I though it could be something like @swagger_auto_schema(paginator_inspectors=False) but it doesn't work and I can't find anything usefull on the docs. Thanks in advance oh and just in case this is my view: class CharacterView(ListChView): class OutputSerializer(serializers.Serializer): id = serializers.CharField(source="external_id") created_at = serializers.DateTimeField() pagination_class = CustomPagination -
How to complete the 19.3 from the book Python-Crash-Course.-Eric-Mattes
Trying to complete the 19.3 from the book Python-Crash-Course.-Eric-Mattes. The task is: 19-3. Refactoring: There are two places in views.py where we make sure the user associated with a topic matches the currently logged-in user. Put the code for this check in a function called check_topic_owner(), and call this function where appropriate. views.py ''' from django.shortcuts import render from django.http import HttpResponseRedirect, Http404 from django.core.urlresolvers import reverse from django.contrib.auth.decorators import login_required from .models import Topic, Entry from .forms import TopicForm, EntryForm def index(request): """The home page for Learning Log.""" return render(request, 'learning_logs/index.html') @login_required def topics(request): """Show all topics.""" topics = Topic.objects.filter(owner=request.user).order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) @login_required def topic(request, topic_id): """Show a single topic, and all its entries.""" topic = Topic.objects.get(id=topic_id) # Make sure the topic belongs to the current user. if topic.owner != request.user: raise Http404 entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) @login_required def new_topic(request): """Add a new topic.""" if request.method != 'POST': # No data submitted; create a blank form. form = TopicForm() else: # POST data submitted; process data. form = TopicForm(request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.owner = request.user new_topic.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form': form} … -
how to set loader in django app using python and javascript
I'm building a big project using django, and I want the best way to put the loader during operations for Example: code now this function need almost 2 min to finsh the function when this function run the page only loading how i can set a loader while the function run ? for frontend i use (html , css, js) backend ( django - python ) i want simple method In short, I want to set loader while the run functions in django :) -
Two ways to create timezone aware datetime objects (Django). Seven minutes difference?
Up to now I thought both ways to create a timezone aware datetime are equal. But they are not: import datetime from django.utils.timezone import make_aware, get_current_timezone make_aware(datetime.datetime(1999, 1, 1, 0, 0, 0), get_current_timezone()) datetime.datetime(1999, 1, 1, 0, 0, 0, tzinfo=get_current_timezone()) datetime.datetime(1999, 1, 1, 0, 0, tzinfo=<DstTzInfo 'Europe/Berlin' CET+1:00:00 STD>) datetime.datetime(1999, 1, 1, 0, 0, tzinfo=<DstTzInfo 'Europe/Berlin' LMT+0:53:00 STD>) In the Django Admin GUI second way creates this (German date format dd.mm.YYYY): 01.01.1999 00:07:00 Why are there 7 minutes difference if I use this: datetime.datetime(1999, 1, 1, 0, 0, 0, tzinfo=get_current_timezone()) -
Manifest.json not found Django React
I'm unable to get rid of manifest.json error. I don't want to remove it's link from HTML file. Also I tried every single answer out there on stackoverflow and other sites but nothing worked. Error Image Directory Structure Following are my settings for static files and html files - INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'frontend/build'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_URL = '/static/' STATICFILES_DIRS = [BASE_DIR / 'frontend' / 'build' / 'static'] Can you please tell me what's wrong here ? -
If I need to sort objects by a sum of 2 fields, what is the most efficient way to do this [Django]
I have a class called LogSheet that looks like this: class LogSheet(models.Model): calls_logged = models.IntegerField(default=0) texts_logged = models.IntegerField(default=0) What would be the best way to get a queryset that is sorted by the calls_logged + texts_logged. Is there a way to index this query? -
Django write Q filter based on the Form elements
I would like to write django filter for the following scenario. CASE : I have 4 checkboxes box1, box2, box3, box4 and a submit button on my HTML page. I have written model post with 6 fieldd where 4 fields corresponds to box1,2,3,4. Based on the user input (4 checkboxes) it should filter the post. However does this mean i have to write 16 scenarios 4x4. or is it possible to formulate it in a better way. post.objects.filter(Q(id=1),Q(sid=1),Q(pid=1),Q(kid=1)) # case 1 post.objects.filter(Q(id=1),Q(sid=1)) post.objects.filter(Q(id=1),Q(kid=1)) post.objects.filter(Q(id=1),Q(pid=1)) post.objects.filter(Q(kid=1),Q(sid=1)) . . . post.objects.filter(Q(kid=1)) Is there a better way to do it? -
Rename Filter Label Model Admin Django
Is it possible to change this label in the list filter from model admin without creating a custom filter? I'm using the same table for 2 different fields and user needs to filter the table using both fields (separately or combining them). Without the rename in the Admin view will have 2 filters with same name applying to different fields. Not the best ux. -
how to filter users in admin panel?
I have a task form in my app. Django is informing owners that someone has sent a task and they need to assign a particular person to this task (by choosing user in column owner) from the admin panel. There can be only 1 person assigned to each task. My problem is that people who are assigning tasks can see the list of all users and I want to filter users in this dropdown list only to users that are in a group named "owners". Question Is there any way to filter users that are displayed in the dropdown list? models.py class TaskRquest(models.Model): title = models.CharField(max_length=1000, blank=True, null=True, default='') body = models.TextField('Description') priority = models.BooleanField(default=False, blank=True, null=True) publish_date = models.DateTimeField('publish', default=timezone.now) owner = models.OneToOneField(User, blank=True, null=True, on_delete=models.DO_NOTHING) admin.py class TaskRquestAdmin(ImportExportModelAdmin): list_display = ('title', 'publish_date', 'priority', 'owner') admin.site.register(TaskRquest, TaskRquestAdmin) -
I want more optimizing Django ORM
I have this model: class Actor(models.Model): act_id = models.AutoField(primary_key=True) act_name = models.CharField(max_length=125) act_gender = models.CharField(max_length=1) class Casting(models.Model): actor = models.ForeignKey('Actor', on_delete=models.CASCADE) movie = models.ForeignKey('product.Movie', on_delete=models.CASCADE) part = models.CharField(max_length=25, null=True) class Movie(TimeStampModel): mov_id = models.AutoField(primary_key=True) mov_title = models.CharField(max_length=200) director = models.ForeignKey('participant.Director', on_delete=models.CASCADE) I want this result: <QuerySet [{'actor_id__act_name': 'Dwayne Johnson', 'actor_id__act_id': 24}, {'actor_id__act_name': 'met smith', 'actor_id__act_id': 25}, {'actor_id__act_name': 'Will Smith', 'actor_id__act_id'__act_name': 'Vin Diesel', 'actor_id__act_id': 27}, {'actor_id__act_name': 'Chris Pratt', 'actor_id__act_id': 28}, {'actor_id__act_name': 'Ryan Reynolds', 'actor_id__act_id': 29}]> I wrote this code: Casting.objects.filter(movie_id=1).select_related('actor').values('actor_id__act_name', 'actor_id__act_id') I want to write an optimized ORM. Please suggest a better code. -
Test celery task with django
I´m trying test a celery task in my django project using the same database as django test. In my setup I have databases = '__all__' @classmethod def setUpClass(cls): super().setUpClass() # Start up celery worker cls.celery_worker = start_worker(app, perform_ping_check=False) cls.celery_worker.__enter__() @classmethod def tearDownClass(cls): super().tearDownClass() # Close worker cls.celery_worker.__exit__(None, None, None) But i got psycopg2.InterfaceError: connection already closed when run cls.celery_worker.enter(). Somebody can help me? -
Using Class-Based Views with Function-Based Views together in Django
Is it possible to use Class-Based Views with Function-Based Views together in django project? If yes, Is that best practice ? Can I use them together in the same views.py -
Parent form not getting values from child form during child object initialization in Django
I created a basic form in django. class basicform(forms.Form): br = ((None,' '),('CSE','CSE'),('ECE','ECE'),('IT','IT')) se = ((None,' '),('M','Male'),('F','Female'),('O','Others')) secx = ((None,' '),('A','A'),('B','B'),('C','C'),('D','D')) roll_no = forms.CharField(required=False,label='Roll No:') name = forms.CharField(required=False,label='Name:') sex = forms.ChoiceField(required=False,choices=se,label='Gender:') branch = forms.ChoiceField(required=False,choices=br,label='Branch:') sec = forms.ChoiceField(required=False,choices=secx,label='Section:') i made another form class marks(basicform): s11 = forms.DecimalField(max_value=100,min_value=0) s12 = forms.DecimalField(max_value=100,min_value=0) s13 = forms.DecimalField(max_value=100,min_value=0) ...... def __init__(self,*args,**kwargs): super(marks,self).__init__(*args,**kwargs) self.fields['name'].disabled = True self.fields['roll_no'].disabled = True self.fields['sex'].disabled = True self.fields['branch'].disabled = True self.fields['sec'].disabled = True the issue is, i am taking post data from the base form, and i want that data to be assigned into the child (i.e. marks object) mark = marks(data = request.POST) this is what i'm trying to do. keep in mind the post data is from the base class(i.e. basicform), i'm under the assumption that the 'data' parameter would be passed onto the super class and therefore values would be assigned, but that is not the case. what am i doing wrong? def create(request): global form if request.method == 'POST': form = basicform(data = request.POST) if form.is_valid(): mark = marks(data = request.POST) mark.full_clean() print(form.cleaned_data) print(mark.cleaned_data) this is an excerpt from my view, here the print statements are for debugging and as i mentioned before, 'form' variable has the values … -
Django - Admin Area - I can't delete a user from users (User matching query does not exist.)
I created a Users app. In models i create a Profile and signals. In admin area i can create a new user end is created a Profile as well. When i delete the new user form Profile is also deleted from Users and is ok. But if i try to delete the new user from Users area i got error message: "DoesNotExist at /admin/auth/user/3/delete/ - User matching query does not exist". I dont know why ? Any suggestion ? I run and apply all the migrations and also i delete and create another database but is not solve this issue. models.py from django.db import models from django.contrib.auth.models import User from PIL import Image from ckeditor_uploader.fields import RichTextUploadingField # Create your models here. class Profil(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) username = models.CharField(max_length=200, blank=True, null=True) nume = models.CharField(max_length=200, blank=True, null=True) avatar = models.ImageField ( upload_to ='utilizatori/', default='utilizatori/avatar_profilearning.jpg', verbose_name='Avatar (320px * 320px)') departament = models.CharField(max_length=200, blank=True, null=True) functie = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(max_length=500, blank=True, null=True) descriere = RichTextUploadingField(external_plugin_resources=[( 'emojione', '/static/src/plugins/ckeditor_plugins/emojione/' , 'plugin.js', )], config_name='default') creat = models.DateTimeField(auto_now_add=True) #pentru a redimensiona rezolutia avatarului incarcat def save(self, *args, **kawrgs): super().save(*args, **kawrgs) img = Image.open(self.avatar.path) if img.height > 320 or img.width > … -
Azure IoT device loosing connection to transparent edge gateway device
I have an issue with a IoT device looses the connection to a transparent Azure IoT Edge gateway. I don't know where to start searching, therefore I'm a bit lost here. IoT Device I used the sample telemetry application (Python) and customized it to our needs. It connects to the Edge Device with MQTT over WS. Initially, it works great until the disconnect happens. SDK version is 2.11.0 IoT Edge I have setup an Azure IoT Edge device as transparent gateway. It is running the latest versions (1.2), installed on a Azure Linux VM. Problem When the script has been running for some time (e.g. 30 minutes) a connectivity issue appears. Exception caught in background thread. Unable to handle. ReconnectStage: DisconnectEvent received while in unexpected state - CONNECTING, Connected: False ['azure.iot.device.common.pipeline.pipeline_exceptions.OperationTimeout: Transport timeout on connection operation\n'] Traceback (most recent call last): File "C:\Users\foo\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\iot\device\iothub\aio\async_clients.py", line 33, in handle_result return await callback.completion() File "C:\Users\foo\AppData\Local\Programs\Python\Python310\lib\site-packages\azure\iot\device\common\async_adapter.py", line 91, in completion return await self.future azure.iot.device.common.transport_exceptions.ConnectionDroppedError: transport disconnected The above exception was the direct cause of the following exception: Traceback (most recent call last): File "c:\Development\machine-poc\python\telemetrysender.py", line 165, in <module> main() File "c:\Development\machine-poc\python\telemetrysender.py", line 76, in main send_telemetry_from_device(device_client, payload, i) File "c:\Development\machine-poc\python\telemetrysender.py", line 86, in send_telemetry_from_device … -
django:Model get all User except one user with his user id
Is there any method of django model.object to get all the users from User model except one user with his id? -
Django - Can I use one UpdateView to update fields on separate pages?
Let's say I have a Student model, with name and age fields, and I have a page with a DetailView class showing these fields. Let's say that rather than having one "update" button that will take me to a form to update all fields of my model at once, I want a separate button for each field that takes me to a separate page with a form to update it. I know how I could do this with a separate HTML file and separate UpdateView class for each field, but it seems like there should be a cleaner way. In the first HTML file I have two buttons: <a href="{% url 'update_name' pk=student.pk%}">Update name</a> <a href="{% url 'update_age' pk=student.pk%}">Update age</a> In the second I have the form: <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> Urls: urlpatterns = [ path('<int:pk', views.StudentDetailView.as_view(), name="detail"), path('update_name/<int:pk>', views.StudentUpdateView.as_view(), name="update_name"), path('update_age/<int:pk>', views.StudentUpdateView.as_view(), name="update_age"), ] Views: class StudentUpdateView(UpdateView): model = models.Student template_name = 'update_student.html' I suppose I'm looking for some sort of if statement that I can put in my view, like: if condition: fields = ("name",) elif condition2: fields = ("age",) Hopefully this makes sense! Thank you for any help :) -
'no app installed with this label' error when creating an empty migration
WOrking on a django project, I had to split an app in two apps and move models from one app to the other. Now i want to move the data from the old table to the new one using the migrations. However, when i want to create an empty migration with "manage.py makemigrations --empty myapp" i have the error ==> 'no app installed with this label'. My new app is in the installed apps in settings. This is where the error occurs, when reading the settings. Has anyone a clue to help me solve my problem? -
Django: View and View-Test working against each other
right now I'm trying to test one of my really simple views - which is working totally fine - and receiving an error: Traceback (most recent call last): File "C:\Users\someone\Documents\django_tests\app\tests\test_views.py", line 42, in test_person_post ValueError: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x00000262BBE2CF10>>": "Person.created_from" must be a "CustomUser" instance. I've changed the default auth.user.model with AbstractUser and changed it into mail/password-, instead of username/password-combination. models.py: class Person(models.Model): GENDERS = ( ('-', '-'), ('Diverse', 'Diverse'), ('Female', 'Female'), ('Male', 'Male'), ) first_name = models.CharField(max_length=50, null=False, blank=False) last_name = models.CharField(max_length=50, null=False, blank=False) gender = models.CharField(max_length=10, null=False, blank=False, choices=GENDERS, default=GENDERS[0][1]) born = models.DateField(null=False, blank=False) adult = models.BooleanField(default=False) created_from = models.ForeignKey(USER, null=False, blank=False, on_delete=models.CASCADE) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now=True) class Meta: ordering = ['last_name', 'first_name'] constraints = [ models.UniqueConstraint(fields=['last_name', 'first_name'], name="unique person constraint"), ] verbose_name = "Person" verbose_name_plural = "Persons" def get_absolute_url(self): return f"api/persons/{self.id}/" def __str__(self) -> str: return f"{self.first_name} {self.last_name}" forms.py: class PersonForm(ModelForm): class Meta: model = Person exclude = [ 'id', 'adult', 'created_from', 'created_date', 'updated_date', ] views.py: def index(request): form = PersonForm() if request.method == 'POST': form = PersonForm(request.POST) if form.is_valid(): person = form.save(commit=False) person.created_from = request.user person.save() return redirect('index') context = {'form': form} return render(request, 'app/index.html', context) test_views.py: USER = get_user_model() class … -
Convert string to int before quering django ORM
I have a model class Entry(models.Model): maca = models.CharField(max_length=100, blank=True, null=True) This field will accept only numbers (cannot set char field to integer field for business reasons) Now I have to get all Entries that have maca greater than 90 What I'm trying to do is this: Entry.objects.filter(maca__gte=90) But gte isn't working because the maca is string How can I convert maca to int before filtering? or something like this? Thanks -
Add multiple real-time plots on the same page with Chart.js (Django)
i'm trying to add multiple real-time plots on the same page (Django framework) with Chart.js using websockets. When i try to add separate socket on the 2nd plot, the 1st freezes. Here is my code, thanks a lot. I'm sure there is a better way to write code, but I'm relatively new to js. <script> let socket =new WebSocket('ws://localhost:8000/ws/polData/'); socket.onopen =function(e){ alert('Connection established'); }; socket.onmessage = function(e){ console.log(e.data); var recData=JSON.parse(e.data); dataObjNew=dataObj['data']['datasets'][0]['data']; dataObjNew.shift(); dataObjNew.push(recData.value); dataObj['data']['datasets'][0]['data']=dataObjNew; window.myLine.update(); }; socket.onclose = function(e){ alert('Connection CLosed'); }; </script> <script> var dataObj={ type: 'line', data: { labels: [1,2,3,4,5,6], datasets: [{ label: 'Real time data', borderColor: "#1d7af3", pointBorderColor: "#FFF", pointBackgroundColor: "#1d7af3", pointBorderWidth: 2, pointHoverRadius: 4, pointHoverBorderWidth: 1, pointRadius: 4, backgroundColor: 'transparent', fill: true, borderWidth: 2, data: [12, 19, 3, 5, 2, 3], }] }, options: { responsive: true, maintainAspectRatio: false, legend: { position: 'bottom', labels : { padding: 10, fontColor: '#1d7af3', } }, tooltips: { bodySpacing: 4, mode:"nearest", intersect: 0, position:"nearest", xPadding:10, yPadding:10, caretPadding:10 }, layout:{ padding:{left:15,right:15,top:15,bottom:15} }, scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } } var ctx = document.getElementById('lineChart').getContext('2d'); window.myLine = new Chart(ctx,dataObj ); </script> <script> let socket =new WebSocket('ws://localhost:8000/ws/polData2/'); socket.onopen =function(e){ alert('Connection established'); }; socket.onmessage = function(e){ console.log(e.data); var recData=JSON.parse(e.data); … -
How to duplicate input field?
I want to create a button to add more file input. I mean, there is a file input on the page, when the user clicks the add more button, then it should create a new and different file input field. How can I do that? -
Difference Django DB models using the ForeignKey to object with or without "to" statement?
I am new to Django and trying to understand someone else code. Where I am struggling with is the models.py and when to use a direct assignment of another object or when to use the "to" statement. What is the difference between those statement? model = models.ForeignKey('Car', on_delete=models.CASCADE, blank=True, null=True) model = models.ForeignKey(to='Car', on_delete=models.CASCADE, blank=True, null=True)