Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Iterating over Raw Query is slow
I have a query which uses a window function. I am using a raw query to filter over that new field, since django doesn't allow filtering over that window function (at least in the version I am using). So it would look something like this (simplified): # Returns 440k lines user_files = Files.objects.filter(file__deleted=False).filter(user__terminated__gte=today).annotate( row_number=Window(expression=RowNumber(), partition_by=[F("user")], order_by=[F("creation_date").desc()])) I am basically trying to get the last not deleted file from each user which is not terminated. Afterwards I use following raw query to get what I want: # returns 9k lines sql, params = user_files.query.sql_with_params() latest_user_files = Files.objects.raw(f'select * from ({sql}) sq where row_number = 1', params) if I run these queries in the database, they run quite quickly (300ms). But once I try to iterate over them or even just print them it takes a very long time to execute. Anywhere from 100 to 200 seconds even though the query itself just takes a little bit less than half a second. Is there anything I am missing? Is the extra field row_number in the raw query an issue? Thank you for any hint/answers. (Using Django 3.2 and Python 3.9) -
Django ManyToMany trhough summary calculation
Giving next models: class Question(models.Model): question = models.TextField() output_params = models.ManyToManyField(OutputParam, through='OutputParamWeight') class OutputParam(TimeStampModel): form = models.ForeignKey(Form, on_delete=models.CASCADE, related_name='output_params') name = models.CharField(max_length=255) class OutputParamWeight(models.Model): output_param = models.ForeignKey(OutputParam, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) weight = models.IntegerField() class Answer(TimeStampModel): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') value = models.IntegerField() Every question affects N output params in a form multiplying x1, x2, x3 the associates answer value. For example: Question 1 -> Output param 1 x1 Output param 2 x3 Output param 3 x2 Question 2 -> Output param 1 x2 Output param 3 x3 Answer 1 -> Question 1 Value 2 Answer 2 -> Question 2 Value 3 So, what I'm trying to do now is summarize the form result as follows: Output param 1: 6 (answer1.value * question1.output_param1.weight + answer1.value * question2.output_param1.weight) Output param 2: 15 Which queries should I perform to get the final result in an optimized way? -
ImportError (circular import) in Django
everyone! I need to delete my django app. After I do this, in another app I get ImportError. Apps don't have any connections at all. But if in the first app in models I restore one line with import, everything goes well. My structure app_one/models.py --- need to delete app_two/models.py app_two/service.py app_three/tasks.py When I try to delete everything from app_one/models.py -> ImportError occured. But when I restore one line from app_three.tasks import some_task everything is ok I checked everything - there are no real circular imports in theese three apps If someone faced issue like this, I will appreciate your help I tried to move this import to app_two/apps.py AppsConfig.ready, also I tried to move this import higher to another app which initialized before app_two. Nothing helped -
OpenCV VideoCapture Error in Docker Container (Returns None When Read)
Here is my DockerFile: FROM python:3.10.4 LABEL maintainer="Louis Jefferson Zhang <louis.ljz08@gmail.com>" # Set environment variables ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Build Dependencies for Opencv, Dlib and Psycopg2 RUN apt-get update && apt-get install -y \ build-essential \ cmake \ libopencv-dev \ libdlib-dev \ libpq-dev \ && rm -rf /var/lib/apt/lists/* # Installation RUN pip install opencv-python dlib psycopg2 # MAIN WORKDIR /code COPY requirements.txt . RUN pip install -r requirements.txt COPY ./fr_as . Here is my Docker Compose: version: "3.9" services: web: build: . command: python /code/fr_as/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db devices: - /dev/video0:/dev/video0 privileged: true db: image: postgres:15 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - "POSTGRES_HOST_AUTH_METHOD=trust" volumes: postgres_data: I built the container using this command: docker-compose up -d --build And an error appeared when running the code below: cap = cv2.VideoCapture(0) _, img = cap.read() Here is the error message: OpenCV(4.7.0) /io/opencv/modules/imgproc/src/resize.cpp:4062: error: (-215:Assertion failed) !ssize.empty() in function 'resize' Looking at the Variable Watch Window, The Values for these variables are: _ = False img = None -
How to filter the latest amended laws in django admin site?
below is the description of models: I have a Law model Each law many Versions Each version has many Translations Each translation has many annotations I want to get the latest amended laws in the django admin site. So, I created a proxy model of Law. and in the the admin file of law I have this: @admin.register(LatestAmendedLaws) class LatestAmendedLawsAdmin(admin.ModelAdmin): list_display = ("id", "rs_number", "created") def get_queryset(self, request): latest_translation_datetime = Translation.objects.latest("created").created return ( super() .get_queryset(request) .filter(created__gte=latest_translation_datetime) ) this script doesn't return the correct latest amended laws. because it filters based on the created field of law. but it should be based on the latest created/updated date of translations that are associated with the law. -
django getlist() function
I have a tags generator for my blog site and every time I enter tags it generates a hidden html input, and it appends whenever I insert a tag like this example below. <input type="hiiden" name="tags" value="<value of inserted tags>"> <input type="hiiden" name="tags" value="<value of inserted tags>"> <input type="hiiden" name="tags" value="<value of inserted tags>"> In my Django view I get all the tags from the form through request.POST.getlist("tags") and save it on database so the inserted tags is like this on database ['value1','value2','value3'] When I fetch the tags in the Django template through for loop to extract the strings from the arrayfield the output shows like this: [ ' v a l u e 1 ' , ' v a l u e 2 ' , ' v a l u e 3 ' ] // one by one character output the code works fine but the problem is it outputs character by character in the array including the brackets and the apostrophe and the commas. What i want to achieve is only the strings which are present in the array field anyone knows what can be the solution for this? any suggestion and help is appreciated. -
django orm group by taking value from order by
query_set = query_set.values('event','cat_type').annotate(cat_count=Count('id')).order_by("event__slug", "cat_type") when I execute the sql query it returns, ... GROUP BY event_id,cat_type,event.slug,cat_type. My question is why it considers the value written in ordey_by as Group by condition?? -
Django - Object of type User is not JSON serializable
I am facing an issue with POSTing data (which has a User object) to a ModelViewSet. Error: "Object of type User is not JSON serializable" data_params = { "log_user_id": user, "device_name": "sampledevice", "log_user_email": "svc.netadc@ads.aexp.com", "feature_name": 'Subnet Automation', } print(data_params, "data_params") response = requests.post("<url>/netadc3/arista/ImplementationLogsAristaViewSet/implementationlogsarista/", auth=(<username>, <password>), headers={"content-type": "application/json"}, data=json.dumps(data_params), verify=False) serializers.py: class ImplementationLogsAristaSerializer(serializers.HyperlinkedModelSerializer): log_user_id = UserSerializer(read_only=True) class Meta: model = ImplementationLogsArista fields = ('log_id','device_name', 'log_user_id','log_user_email','feature_name') Not sure how to successfully POST the data with User into the ModelViewSet. views.py: class ImplementationLogsAristaViewSet(viewsets.ModelViewSet): queryset = ImplementationLogsArista.objects.all().order_by('log_capture_date') serializer_class = ImplementationLogsAristaSerializer permission_classes = (IsAuthenticated,) pagination_class = None -
Optimize Django ORM query to get object if a specific related object does not exist
I have the following table structures: class Library: id = models.CharField(...) bookcase = models.ForeignKey( Bookcase, related_name="libraries" ) location = models.ChoiceField(...) # Other attributes... class Bookcase: # some attributes type = models.ChoiceField(..) class Book: bookcase = models.ForeignKey( Bookcase, related_name="books" ) title=models.CharField(...) status=models.ChoiceField(...) # borrowed | missing | available Say if I want to get all Library objects that does not have a book with title "Foo" that is NOT missing, how can I optimize this query? I have the following: libraries = Library.objects.select_related('bookcase').filter(location='NY', bookcase__type='wooden') libraries_without_book = [] for library in libraries: has_non_missing_book = Book.objects.filter( bookcase=library.bookcase, title="Foo", ).exclude(status='missing').exists() if not has_non_missing_book: libraries_without_book.append(library.id) Unfortunately, this performs an extra query for every Library object that matches the initial filtering condition. Is there a more optimized method I can use here that makes use of prefetch_related in some way? -
Nesting Django QuerySets
Is there a way to create a queryset that operates on a nested queryset? The simplest example I can think of to explain what I'm trying to accomplish is by demonstration. I would like to write code something like MeterReadings.objects.filter(radio=1).objects.filter(meter=1) resulting in SQL looking like SELECT * FROM ( SELECT * FROM MeterReading WHERE radio=1 ) WHERE meter=1; More specifically I have a model representing readings from sensors class Sensor(models.Model): sensor=models.PositiveIntegerField() timestamp=models.DatetimeField() reading=models.IntegerField() With this I am creating a queryset that annotates every sensor with the elapsed time since the previous reading in seconds readings = ( SensorReading.objects.filter(**filters) .annotate( previous_read=Window( expression=window.Lead("timestamp"), partition_by=[F("sensor"),], order_by=["timestamp",], frame=RowRange(start=-1, end=0), ) ) .annotate(delta=Abs(Extract(F("timestamp") - F("previous_read"), "epoch"))) ) I now want to aggregate those per sensor to see the minimum and maximum elapsed time between readings from every sensor. I initially tried readings.values("sensor").annotate(max=Max('delta'),min=Min('delta'))[0] however, this fails because window values cannot be used inside the aggregate. Are there any methods or libraries to solve this without needing to resort to raw SQL? Or have I just overlooked a simpler solution to the problem? -
How to setup django with lighttpd?
I have a live website that is running under lighttpd. I now have a sub-domain that I want to run under django. I do not want to move to Apache as I don't currently have the resources to support two production web servers. The django part is actually working well with the django builtin development server so now I just need to port it into production. It seems that all documentation to setup django with lighttpd is over 10 years old and uses fastcgi that from what I can see was deprecated and removed from django. The new docs point to use wscgi - scgi under lighttpd. But even that is being hard to get any documentation. Do I need to run uwsgi and use that to serve the pages to mod_scgi? Or should I use gunicorn? I am sort of at a loss on what to do. Suggestions welcome! -
Django: How to Filter Model with "where" clause to display in list admin related objects
I have 2 models that depend on each other. One is the "FeatureFilm" model and the other is the "CompanyInvolved" model. In the "FeatureFilm" table I want to store movies and in the "CompanyInvolved" table I want to store the many companies that have contributed to a movie. The "CompanyInvolved" model is attached to the "FeatureFilm" table with a foreignkey. I want to display a column from the CompanyInvolved table in the list view of the FeatureFilm Admin Panel. I have already done that with my code. The only thing I didn't get yet is a filter that filters the CompanyInvolved table on the field "company_role". I want to show only the values that have the company_role = "Production". Can someone please help? many greetings here is my depending code: model.py class ProjectBaseModel(models.Model): title = models.CharField("Titel", max_length=100, blank=False, unique=True) leading_postproduction_id = models.ForeignKey( Company, verbose_name="Federführende Postproduktion", on_delete=models.SET_NULL, blank=True, null=True, ) class FeatureFilm(ProjectBaseModel): class Meta: verbose_name = "Kinofilm" class CompanyInvolved(models.Model): feature_id = models.ForeignKey( FeatureFilm, on_delete=models.CASCADE, null=True, blank=True, ) tv_movie_id = models.ForeignKey( TvMovie, on_delete=models.CASCADE, null=True, blank=True ) company_roll = models.CharField( choices=company_roll, max_length=15, blank=True, help_text="Produktion, Co-Produktion, Kinoverleiher, Sender, Weltvertrieb", ) company_involved = models.ForeignKey( Company, on_delete=models.SET_NULL, null=True, blank=True, ) def __str__(self): return "#" + str(self.pk) … -
TypeError at /crear-cliente/ in Django
Hello there, I'm trying to do a form that can store the customers records, but recently it's throw me this error TypeError at /crear-cliente/ object of type 'int' has no len() C:\Users\G-FIVE\Desktop\practicas y proyectos\mini_erp\MiniErp\customers\views.py, line 43, in register_customer address = address ) customer.save() """ form = FormCustomer(request.POST) if form.is_valid(): … data_form = form.cleaned_data first_name = data_form['first_name'] last_name = data_form['last_name'] cedula = data_form['cedula'] phone_number = data_form['phone_number'] I did the form using the Django classes, I'll show you the code of the form, the view and the model Form code: from django import forms from django.core import validators # Clase para el formulario de registro de clientes class FormCustomer(forms.Form): # Input para el first_name first_name = forms.CharField( label='Nombre', required=True, widget=forms.TextInput( attrs={ 'placeholder':'Ej: John', 'class': 'form-control form-control-user mb-3', 'id': 'first_name' } ), validators= [ validators.MinLengthValidator(3, 'El nombre está incompleto') ] ) # Input para el last_name last_name = forms.CharField( label='Apellido', required=True, widget=forms.TextInput( attrs={ 'placeholder':'Ej: Doe', 'class': 'form-control form-control-user mb-3', 'id': 'last_name' } ), validators= [ validators.MinLengthValidator(3, 'El nombre está incompleto') ] ) # Input para la cédula cedula = forms.IntegerField( label='Cédula', required=True, widget=forms.NumberInput( attrs={ 'placeholder':'xx xxx xxx', 'class': 'form-control form-control-user mb-3', 'id': 'cedula' } ), validators= [ validators.MinLengthValidator(7, 'Faltan números'), validators.MaxLengthValidator(8, 'Has introducido … -
How to make Celery + Django + Pytest work together
Trying to test an endpoint that has a celery task. Celery tasks don't seem to run in the test. django==4.1.5 celery==5.2.7 pytest==7.2.1 pytest-django==4.5.2 An endpoint: def do_some_stuff(blah: Blah) -> Blah: res = cool_task.apply_async(kwargs={ 'cool_id': int(pk), 'config': config, 'name': RESUBMIT.value, }, link=update_status.si( cool_id=int(pk), new_status="why is this so hard", ) ) [...] A test: @pytest.mark.django_db def test_my_thing(django_client: Client) -> None: [...] response = django_client.post(f"/api/myendpoint/{mything.id}/do_some_stuff/") It hits the endpoint. Gets a 202 back as expected. But celery doesn't seem to be picking up the task in the test. The update_status method updates the db, and I'm not seeing that happen. I've tried creating a celery app in the test, creating a worker in the test, changing the test to use the main DB instead of the test db, setting the override_settings to "BROKER_BANDEND='memory'". I'd like a full working example. It seems kind of basic but it's eluding me. I don't understand what combination of fixtures and overrides I need for this to work. Seems to work when I actually call the application. -
Making external http calls using requests package within Daphne
I have a Django project that runs by Daphne, one of my views needs to submit a http request externally using the requests package, unfortunately that package is not async compatible, so if the http call is blocked, the whole Daphne app hangs. def view(request): # this call will get timed out data = requests.get('https://blocked') ... return Response(...) I did some quick search and couldn't find any quick answers. One possibility is to serve these views via Uwsgi, apart from this approach, are there any other quick wins? Maybe use aiohttp? -
How to render code based on checkbox value in Django?
I want to conditionally render part of form that's responsible for billing address. If user has checkbox checked, don't render it, if unchecked - render. I tried following: <div class="big-padding"> <input type="checkbox" id="billing-same-as-shipping" name="billing-same-as-shipping" checked> <label for="billing-same-as-shipping">Billing address same as shipping address</label> </div> {% if checked in 'billing-same-as-shipping' %} <h3>Billing Address</h3> <div class="big-padding"> <div class="row "> {% include "views/parts/billing-address.html" %} </div> </div> {% endif %} No matter what I try, I can't seem to make conditional rendering work. -
Getting error: 'No 'Access-Control-Allow-Origin' header is present on the requested resource.' for logout route in Django/React app
I have an app using React/Django, with Auth0 for authentication. I've followed this tutorial to fix any CORS errors, and all my routes are not running into any issues, except for my logout route. I'm creating a logout button, which will flush the user's session on Django and redirect to the Auth0 logout page as well. urls.py urlpatterns = [ ... path('logout/, views.logout, name = 'logout') ] views.py from django.contrib.auth import logout as django_logout def logout(request): django_logout(request) domain = settings.AUTH0_DOMAIN client_id = settings.AUTH0_CLIENT_ID return_to = '127.0.0.1:8000' return redirect(f'https://{domain}/v2/logout?client_id={client_id}&returnTo={returnTo}') App.jsx const App = () => { ... const logout = async () => { await fetch('http://127.0.0.1:8000/logout/') } return ( <div> ... <button onClick={logout}>Logout</button> <div> ) } When the user logs out, I'm getting a CORS error despite importing and configuring django-cors-headers and not getting this error for any other route. Specifically, the error is No 'Access-Control-Allow-Origin' header is present on the requested resource. -
How to map Django TextChoices text to a choice?
Suppose I have this code, inspired from the Django docs about enumeration types: class YearInSchool(models.TextChoices): FRESHMAN = 'FR', 'Freshman' SOPHOMORE = 'SO', 'Sophomore' JUNIOR = 'JR', 'Junior' SENIOR = 'SR', 'Senior' GRADUATE = 'GR', 'Graduate' Now suppose I have the string "Sophomore". How do I get from that to YearInSchool.SOPHOMORE? The only thing I can think of is a loop: the_str = "Sophomore" val = None for val1, label in YearInSchool.choices: if label == the_str: val = YearInSchool(val1) break assert YearInSchool.SOPHOMORE == val That seems awkward. Is there a better way? -
Django form scrubs blank spaces spaces
I have a model with a text field: models.py class Techtip(models.Model): title = models.CharField(max_length=150) year = models.PositiveIntegerField() year2 = models.PositiveIntegerField() make = models.CharField(max_length=30) model = models.CharField(max_length=30) description = models.TextField(max_length=10000) user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True) date_revised = models.DateTimeField(null=True) additional_field = models.TextField(max_length=5000, null=True, blank=True) additional_field2 = models.TextField(max_length=5000, null=True, blank=True) image1 = models.ImageField(upload_to=user_directory_path, null=True, blank=True) image2 = models.ImageField(upload_to=user_directory_path, null=True, blank=True) image3 = models.ImageField(upload_to=user_directory_path, null=True, blank=True) def __str__(self): return self.title If a create a Techtip and give it a description of: "Hello, This is line one of the disctription. This is line two. and this is line 3." When using {{techtip.deescription}} in the template I receive this: "Hello, This is line one of the disctription. This is line two. and this is line 3." However, if you bring up a form to edit the description, the spaces are there. It is also displayed correctly in the admin panel. Here is the form: forms.py class TechtipFormModel(forms.ModelForm): """This form creates and edits techtips.""" class Meta: model = Techtip fields = '__all__' exclude = ('user', 'date_revised', 'additional_field', 'additional_field2', 'image1', 'image2', 'image3') def __init__(self, *args, **kwargs): super(TechtipFormModel, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'id-TechtipForm' self.helper.form_method = 'post' self.helper.add_input(Submit('submit', 'Submit')) self.fields['description'].strip = False Here are … -
DataTables with Django Rest Framework New/Edit/Delete Buttons not working
I am trying to incorporate DataTables Editor into a Django REST API I made. While I am able to get the datatable to display, the create/edit/delete buttons to do not work. I want to focus on just the edit function for now and hopefully the answer can be applied to the create/delete functions as well. Every time I select the edit button and chose an entry to edit I am returned PUT http://127.0.0.1:8000/dashboard/api/investigator/1 403 (Forbidden) I am able to edit the entry but the request is not processed which makes me believe it is either my datatables being setup wrong or the REST API not connecting with datatables. Can anyone provide input if I setup the datatable wrong? urls.py from django.urls import path, include from . import views from rest_framework import routers from .views import StudyList, StudyDetail, InvestigatorView app_name = 'dashboard' router = routers.DefaultRouter() router.register('study', views.StudyView) router.register('investigator', views.InvestigatorView) router.register('lead', views.LeadView) router.register('institution', views.InstitutionView) router.register('site', views.SiteView) investigator_list = InvestigatorView.as_view({ 'get': 'list', 'post': 'create' }) investigator_detail = InvestigatorView.as_view({ 'get': 'retrieve', 'PUT': 'update', 'patch': 'partial_update', 'delete': 'destroy' }) urlpatterns = [ path('', views.datatables, name='datatable'), path('investigator/', views.datatables_investigator, name='datatables_investigator'), path('api/', include(router.urls)), path('api/investigator/', investigator_list, name='InvestigatorList'), path('api/investigator/<int:pk>', investigator_detail, name='InvestigatorDetail'), path('api/study/', StudyList.as_view(), name='StudyList'), path('api/study/<int:pk>/', StudyDetail.as_view(), name='StudyDetail') ] datatables_investigator.html {% … -
get and show cookies for backend user model -- django
I want cookies to be displayed in the Admin User Model, the customer's data is located in the cookie section and when the customer login, Django requests a cookie from the user authentication account. My Cookie name is 'device', I can use it for guest user but i don't know how to send it to backend and django ask me for it. Error : Field 'id' expected a number but got ''. My Custom User Model: class Account(AbstractBaseUser): phone_number = models.CharField(unique=True, max_length=11, validators=[MinLengthValidator(11)]) device = models.CharField(max_length=200, blank=True) USERNAME_FIELD = 'phone_number' models.py: class Customer(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) # Get COOKIE For guest user -- I set a cookie as device device = models.CharField(max_length=200, blank=True) views.py: Error comes from here def Add_To_Cart(request, pk): if request.user.is_authenticated: """" Error comes from here, i have no idea how to call cookie to user authentication backend.""" customer = request.user.device <<-- item = get_object_or_404(Post, pk=pk) order_item, created = OrderPost.objects.get_or_create( item=item, user=customer, ordered = False ) order_qs = Order.objects.filter(user=customer, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order post is in the order if order.items.filter(item__pk=item.pk).exists(): order_item.qunatity += 1 order_item.save() messages.info(request, "this item just added to your cart") return redirect('article-detail', pk=pk) else: order.items.add(order_item) messages.info(request, … -
Graphen-Django possible to filter a set?
newly working with GraphQl and wondering is it possible to filter a set in a query? I'm still new to database design as well so could be an issue there. So I run the below query, managerGwPicks has a field player with is a player object containig their name etc. This player object contains a set of all the weeks they have played which is a separate table in my database. So as can be seen in the above image when I display the set it shows all the game week data whereas ideally I would like it filtered by the gameweek:21 parameter passed to the managerGwPicks query. I'm not sure it should be possible as there is no direct link between the managerGwPicks and playergwstats tables but I'd like to be sure that my thinking is correct. My solution for my front end would be to have two queries, one similar to what I have getting the player informartion and a second query using the player id and gameweek to query playergwstats to get the player stats for the individual week. Does this sound like a reasonable approach? Thanks -
Django conditional post save signal not working
I have a model for user profiles that has a post save signal that auto creates a user profile whenever a new user is created. I don't want the post save signal to create a user profile when a new superuser is created. So far I have not been able to get this to work. Any ideas about how to fix this? the model: from django.db import models from tinymce import models as tinymce_models from accounts.models import CustomUser from phone_field import PhoneField from constrainedfilefield.fields import ConstrainedFileField import os from io import BytesIO from django.core.files.uploadedfile import InMemoryUploadedFile import sys from PIL import Image from django.db.models.signals import post_save import PIL class UserProfile(models.Model): user = models.OneToOneField(CustomUser, null=True, on_delete=models.CASCADE) preferred_name = models.CharField(null=True, blank=True, max_length= 75) pronouns = models.CharField(null=True, blank=True, max_length= 40) phone = PhoneField(blank=True, help_text='Contact phone number') job_title = models.CharField(null=True, blank=True, max_length= 75) birthdate = models.DateField(null=True, blank=True) bio = tinymce_models.HTMLField(null=True, blank=True) profile_image = ConstrainedFileField( null=True, blank=True, upload_to='projects/employee_profiles', content_types=['image/png', 'image/jpg', 'image/jpeg', 'image/gif'], max_upload_size=2097152, ) def save(self, *args, **kwargs): super(UserProfile, self).save(*args, **kwargs) if self.profile_image: if os.path.exists(self.profile_image.path): image = Image.open(self.profile_image) outputIoStream = BytesIO() basewidth = 100 wpercent = basewidth / image.size[0] hsize = int(image.size[1] * wpercent) imageTemproaryResized = image.resize((basewidth, hsize)) imageTemproaryResized.save(outputIoStream, format='PNG') outputIoStream.seek(0) self.profile_image = InMemoryUploadedFile(outputIoStream, 'ConstrainedFileField', … -
Django: how to move the "page not found" exception and context from function to class-based view?
I'm converting a simple function to a class-based view. I had found a good resource with examples that helped me in the past to better understand the whole topic (can be found here), but I couldn't find a good example of how to handle exceptions related to a page in a class-based view when the page is not found (for example, someone makes a typo in URL). I'm also not sure how to handle additional context that I want also transfer to class-based view. I would appreciate some help, and suggestions based on this simple example below. My goal is to import the main View with `from django.views import View' and place all logic in this class instead of this function. def meetup_details(request, meetup_slug): try: selected_meetup = Meetup.objects.get(slug=meetup_slug) return render(request, 'meetups/meetup-details.html', { 'meetup_found': True, 'meetup_title': selected_meetup.title, 'meetup_description': selected_meetup.description }) except Exception as exc: return render(request, 'meetups/meetup-details.html', { 'meetup_found': False }) -
In Django, how to annotate inside a M2M field?
I have these models: class Convocacao(models.Model): cursos = models.ManyToManyField(Curso) class RegistroConvocacao(models.Model): aluno = models.ForeignKey(Aluno) convocacao = models.ForeignKey(Convocacao) tipo = models.IntegerField(choices=TiposConvocacao) class Aluno(models.Model): curso = models.ForeignKey(Curso) Then I get a Convocacao object: obj = get_object_or_404(Convocacao, pk=pk) Now, I want to use annotate inside obj.cursos, to sum the tipo of RegistroConvocacao. Something like: cursos = obj.cursos.all() cursos = cursos.annotate( total_ingressantes=obj.registroconvocacao_set.filter( aluno__curso__in=obj.cursos, tipo_convocacao=RegistroConvocacao.TIPO_CONVOCACAO_INGRESSANTE ).count() ) But it gives error: TypeError: 'ManyRelatedManager' object is not iterable I want to do something like: for curso in obj.cursos.all(): total = curso.total_ingressantes ...