Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Session, Login and Signup
This is my view module def home(request): return render(request, 'rescues_site/home_page.html') # @login_required def user_home(request): if request.method == 'POST': username = request.session.get('username') context = { 'username': username } return render(request, 'rescues_site/home_page.html', context) def login(request): if request.method == 'GET': return render(request, 'registration/login.html') if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username = username, password = password) if user is not None and user.is_active and user.is_authenticated: login(request, user) request.session['username'] = user.username return redirect('user_home') else: return render(request, 'registration/login.html') @transaction.atomic def sign_up(request): if request.method == 'GET': return render(request, 'registration/sign_up.html') if request.method == 'POST': error = [] first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') address = request.POST.get('address') suburb = request.POST.get('suburb') postcode = request.POST.get('postcode') email = request.POST.get('email') phone_number = request.POST.get('phone_number', None) password = make_password(request.POST.get('password')) try: user = CustomUser.objects.create(username = email, first_name = first_name, last_name = last_name, address = address, suburb = suburb, postcode = postcode, phone_number = phone_number, password = password) request.session['username'] = user.username return redirect('user_home') I tried to login the user and redirect the user to the home page with their cresidentials but what I have is a POST request in the terminal and it take me nowhere. I'm still new to Django and Python. Thank you for your time! -
CSRF Error event after adding CORS_TRUSTED_ORIGINS Django
I am trying to implement feature for changing password but when I make a put request from react frontend to django backend I am getting CSRF error. I am not getting such an error for other put/post requests. Following are the code details: settings.py REST_FRAMEWORK = { # 'DEFAULT_PERMISSION_CLASSES': [ # 'rest_framework.permissions.IsAuthenticated', # ], # 'DEFAULT_AUTHENTICATION_CLASSES': [ # 'rest_framework_simplejwt.authentication.JWTAuthentication', # ], 'DEFAULT_PAGINATION_CLASS': 'main.paginations.CustomPagination', 'PAGE_SIZE': 12 } CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1:8000", "http://127.0.0.1:3000", "http://localhost:3000", ] CORS_TRUSTED_ORIGINS = [ 'http://localhost:3000', ] views.py class ChangePasswordView(generics.UpdateAPIView): queryset = User.objects.all() serializer_class = serializers.ChangePasswordSerializer serializers.py class ChangePasswordSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=True) password2 = serializers.CharField(write_only=True, required=True) old_password = serializers.CharField(write_only=True, required=True) class Meta: model = models.User fields = [ 'old_password', 'password', 'password2' ] def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError({'password': 'Password fields did not match!'}) return attrs def validate_old_password(self, value): user = self.context['request'].user if not user.check_password(value): raise serializers.ValidationError({'old_password': 'Old password provided is incorrect!'}) return value def update(self, instance, validated_data): user = self.context['request'].user print(user) if user.pk != instance.pk: raise serializers.ValidationError({"authorize": "You don't have permission to change password!",}) instance.set_password(validated_data['password']) instance.save() return instance urls.py ... path('change_password/<int:pk>/', views.ChangePasswordView.as_view(), name='auth_change_password'), ... Frontend: const link = `${BASE_URL}${CHANGE_PASSWORD_URL}${customer_id}`; const formData = new FormData(); formData.append('old_password', oldPwdRef.current.value); formData.append('password', newPwdRef.current.value); formData.append('password2', confirmNewPwdRef.current.value); axios.put(link, formData, … -
Calling a variable from python function in HTML page. Coding done in Python, HTML, and Django [duplicate]
I created a basic website in Django, with Python and HTML. Now when I click a button, I want to see a python variable contents on the website. I have a HTML file, and a python views file(I have more files but I think those are the main ones I need to change). I want to print the contents of a python variable onto a HTML website. -
Django Meta.constraints are not working in my models
I'm trying to define a unique constraint for two primary keys in my model, because they are referenced by other models. And ent_ruc cant be unique. Must be unique together with ent_id. class Enterprise(models.Model): ent_id = models.CharField( db_column='ENT_ID', primary_key=True, max_length=16, default=timestamp_id_16) ent_ruc = models.CharField( db_column='ENT_RUC', max_length=16) ent_name = models.CharField(db_column='ENT_NAME', max_length=256) ent_address = models.CharField(db_column='ENT_ADDRESS', max_length=512) ent_type = models.CharField(db_column='ENT_TYPE', max_length=2) class Meta: db_table = 'ENTERPRISE' constraints = [ models.UniqueConstraint( fields=['ent_ruc', 'ent_id'], name='unique_enterprise') ] But when I run the server I get the error: 'Enterprise.ent_ruc' must be unique because it is referenced by a foreign key. HINT: Add unique=True to this field or add a UniqueConstraint (without condition) in the model Meta.constraints. Why Meta.constraints are not working ? -
How to Make This Django's ImageField Work?
models.py `class SpecialOffer(models.Model): productImage = models.ImageField(upload_to="", null=True, blank=True) productName = models.CharField('Product Name', max_length=20) def __str__(self): return self.productName` views.py `def homepage(request): specialoffers = SpecialOffer.objects.all() context = { 'specialoffers' : specialoffers, } return render(request, "index.html", context)` index.html {% for product_name in specialoffers %} <img src="{{ product_name.productImage.url }}" alt="" /> {% endfor %} and the error is that the image i'm uploading through admin sections, is not rendering through my HTML templates. what's wrong with my code? I tried changing this {{ product_name.productImage.url }} to {{ product_name.productImage }} but is still not working. I also tried setting up the MEDIA_URL, and MEDIA_ROOT. -
getting model object using .get(slug=slug) return an error: Invitation matching query does not exist
I am creating a notification system using django, I'm using django signal to create Notification model when the Invitation model is created, but when I created the Invitation model, and click on the link that are in notification template it says: Invitation matching query does not exist. This is a booking application, we want to send that link to the person who created the Invitation model via his email, so that he can see his information, but the link does not gives the person information when I click it in the notification template it says: DoesNotExist at /invitation_information/OlaRooms-123297186425/ Invitation matching query does not exist. views.py def invitation_information(request, slug): invitation = Invitation.objects.get(slug=slug) return render(request, 'invitations.html', {'invitation':invitation}) urls.py path('invitation_information/<slug:slug>/', views.invitation_information, name='invitation_information'), notification template <div class="container"> <div class="row"> {% for notification in notifications %} {% if not notification.is_read %} <div class="col-md-3"> <div class="card"> <div class="card-body"> <a href="{{ notification.link }}"> {{ notification.message }} </a> </div> </div> </div> {% endif %} {% endfor %} </div> </div> signals: @receiver(post_save, sender=Invitation) def notification_signals(sender, instance, created, **kwargs): message = f"{instance.first_name} {instance.last_name} booked our {instance.room_type.room_type} room for {instance.number_of_day} day" link = reverse('Invitation_Information', args=[str(instance.room_type.slug)]) room_id_number = generate_random_number() notification = Notification.objects.create( user=instance.room_type.user, message=message, link=link, room_id_number=room_id_number ) notification.save() My Models: class Room(models.Model): … -
Optimizing Django Admin Search by 'external_id' for Large Datasetsop
I'm facing performance issues when searching for records by the 'external_id' field in the Django Admin on a large dataset. The 'external_id' is a unique identifier for each record in my model. I've already added a HashIndex for this field, but it's still slow. What can I do to optimize the search performance in this specific scenario? Are there any other indexing techniques or Django-specific optimizations that can help speed up the search operation? I appreciate any insights or suggestions to improve the performance of searching by 'external_id' in the Django Admin, especially on large datasets. Thank you! from django.contrib.postgres.indexes import HashIndex from django.db import models class SocialIds(models.Model): """Model for social network identifiers of a user.""" profile = models.ForeignKey( 'accounts.Profile', related_name='socials', on_delete=models.deletion.CASCADE, verbose_name='User Profile', ) service_name = models.CharField( max_length=30, verbose_name='Social Network Name', ) external_id = models.CharField( max_length=100, verbose_name='External Identifier', ) class Meta: verbose_name = 'Social Network Identifier' verbose_name_plural = 'Social Network Identifiers' constraints = [ models.UniqueConstraint( fields=[ 'service_name', 'external_id', ], name='unique_social_service_name_external_id_ids', ), ] indexes = [ HashIndex( fields=['external_id'], name='social_ids_external_idx', ), ] def __str__(self): return str(self.profile) @admin.register(SocialIds) class SocialIDsAdmin(admin.ModelAdmin): list_display = ('profile', 'service_name') list_filter = ('service_name',) raw_id_fields = ('profile',) search_fields = ['profile__nickname', 'external_id'] fields = ('profile', 'service_name') I'd like to obtain … -
Django Error: 'cannot pickle '_io.BufferedReader' object' when Using Cache with Context Data
I'm encountering a challenging issue in my Django project related to caching and context data. When trying to cache the context data in a view, I'm receiving the error message: "cannot pickle '_io.BufferedReader' object." The error seems to occur in my view that displays detailed information about a book, and I'm attempting to cache certain parts of the context, such as average ratings, recommended books, and the last books. There is my detail book view and model: #views.py class DetailBookView(DetailView): template_name = "books/book-detail.html" queryset = Book.objects.all().select_related("genre") cache_timeout = 60 def get_context_data(self, **kwargs): obj = self.get_object() context = super().get_context_data(**kwargs) cache_key = f"book_detail_{obj.id}" cached_data = cache.get(cache_key) if cached_data is not None: context.update(cached_data) # average rating book context["avg"] = BookRelations.objects.get_rating(book=obj) # generate 3 random book context["recommended"] = Book.objects.get_recommended(obj.genre) # last 3 books context["last_books"] = self.get_queryset().values("title") else: cache.set(cache_key, context, self.cache_timeout) return context #models.py (Books) class BookManager(models.Manager): def get_recommended(self, genre): recommend_books = list(Book.objects.filter(genre=genre).select_related("owner")) if len(recommend_books) < 3: recommend_books += list(self.get_queryset())[:4] return random.sample(recommend_books, 3) class Book(models.Model): title = models.CharField(max_length=250) slug = models.SlugField(default="") description = models.TextField(blank=True, null=True) rating = models.DecimalField( validators=[MaxValueValidator(5)], max_digits=3, decimal_places=2 ) created_at = models.DateTimeField(auto_now_add=True) last_update = models.DateTimeField(auto_now=True) image = models.ImageField( upload_to="book_img/", validators=[FileExtensionValidator(["jpg", "JPEG"])], null=True, blank=True, ) genre = models.ForeignKey(Genre, on_delete=models.PROTECT, null=True) author = models.ForeignKey(Author, … -
How to display multiple related objects in Django
I have two models that look like this: class EventDrink(models.Model): name = models.CharField(max_length=255) drink_active = models.BooleanField() def __str__(self): return self.name class EventIngredient(models.Model): drink = models.ManyToManyField(EventDrink) name = models.CharField(max_length=255) url = models.URLField() def __str__(self): return self.name I now want to display all drinks with drink_active set to True to display in my view. I also want to display the ingredients related to that drink. I know I can filter on the drinks in my view like this: drinks = EventDrink.objects.filter(drink_active=1) But how do I now display the ingredients related to each drink? -
The contents in my cards are not the same size eventhough they have the same code
So I made this booking page with bootstrap, and I have made the Upcoming Bookings section first, after that I just copied and past it to the Past Booking section, and just change the variable inside the templating language curly brackets. In theory, since its 99.99% the same code, it should be the same right? But for some reason the details in the Past Booking card is slightly smaller than the Upcoming booking, and this makes it looks unsymmetrical and its driving my OCD crazy. I cannot figure it out! If anyone could that would be very helpful! Screenshot my_bookings.html {% extends 'base.html' %} {% load static %} {% block content %} <div class="container-fluid"> <div class="jumbotron"> <div class="welcome-my-bookings mt-5 text-center"> <h1>My Bookings</h1> </div> </div> <div class="row mt-4 booking-title"> <h3>Upcoming Bookings</h3> <hr> </div> <div class="col-12 card mb-4 left top"> <div class="card-body"> {% if future_bookings %} {% for booking in future_bookings %} <div class="booking-details booking-card my-4"> <div class="row justify-content-center align-items-center flex-lg-row"> <div class="col-auto booking-img-container"> <a href="{% url 'lesson_detail' booking.lesson.slug %}" class="lesson-link"> <div class="col-auto"> {% if "placeholder" in booking.lesson.featured_image.url %} <img class="booking-img d-none d-md-inline-block" src="https://res.cloudinary.com/dukqu7lia/image/upload/v1696354385/placeholder.jpg"> {% else %} <img src="{{ booking.lesson.lesson.featured_image.url }}" class="booking-img d-none d-md-block"> {% endif %} </div> </a> </div> <div class="col-auto … -
Centering div and its elements in Django project
I'm diving into Django for my first project, and I'm stuck with centering stuff on my site. What I'm trying to do is create a div that holds all the content on the site except for the navigation bar. I want this div to sit right in the middle of the screen and take up 50% of the width. And, of course, all the stuff inside that div should be centered too. I've tried a few things, but it's not quite working. Take a look at what I've got: Here is the template: <html> <style> body { margin: 0; padding: 0; } img[src="/media/images/crate_bar.png"] { margin: 0; padding: 0; display: block; width: 100%; height: auto; box-sizing: border-box; } img[src="/media/images/logo.png"] { position: absolute; display: block; width: auto; height: auto; left: 50%; transform: translateX(-50%); top: 0; } #logo { display: flex; justify-content: center; align-items: center; text-align: center; } #main_container { display: flex; justify-content: center; align-items: center; } #second_container { display: flex; justify-content: center; align-items: center; width: 50%; } </style> <div id="logo"> <img src="/media/images/crate_bar.png"> <a href="{% url 'mainapp:home_view' %}"><img src="/media/images/logo.png" alt="logo"></a> </div> <h1> {% if user.is_superuser %} <a href="{% url 'mainapp:new_article' %}"><button type=" button">New article</button></a> {% endif %} {% block content %} <div id="main_container"> … -
Create dynamic URL using primary key in django
I'm developing a website, it creates url for every article using slug (entered manually by the admin who is posting the article) However I'm trying to change it to be dynamically generated using pk. Note that there is no content uploaded in the website so it won't affected by this change. Here is the current code and my main problem is that I don't know how to change it to pk. and when I try the available solutions I don't know where it should be passed through HTML pages. #view.py def DetailView(request, slug): template_name = 'post_detail.html' post = get_object_or_404(Post, slug=slug) return render(request, template_name, {'post': post}) #models.py class Post(models.Model): title = models.CharField(max_length=500) image = models.ImageField(null=True, blank=True, upload_to='media/') content = RichTextField(blank = True, null = True) post_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False) created_on = models.DateTimeField(auto_now_add=True) modified_on = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=200, allow_unicode=True, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') status = models.IntegerField(choices=STATUS, default=0) category = models.CharField(max_length=500, choices= categories_list, default='0') #To order posts based on created dates decsend class Meta: ordering = ['-created_on'] def __str__(self): return self.title #urls.py path('<slug:slug>/', views.DetailView, name='post_detail'), and here is how it's being passed to the html <p><a href="{% url 'post_detail' post.slug %}">{{post.content|safe |slice:":10" }}</a></p> Thanks in advance -
Django Query input results of one queryset to find an object that doesn't appear in another model
Good afternoon, I am trying to write an DRF endpoint that returns the next unused hint. I have two models: class GameActivity(models.Model): activity_datetime = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='activity_user') activity_type = models.ForeignKey(GameActivityType, on_delete=models.CASCADE, null=True, blank=True,related_name='game_activity_type') activity_hint = models.ForeignKey(Hint, on_delete=models.CASCADE, null=True, blank=True) And class Hint(models.Model): hint_title = models.CharField(max_length=50) hint_detail = models.CharField(max_length=300) hint_level = models.IntegerField() chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE, null=True, blank=True, related_name="chapter_hint") pts_cost = models.IntegerField() What I am trying to do is return the next hint for the passed in Chapter ID that is NOT in the GameActivity model. pseudo-code return Hint where (Count (GameActivity where activity_hint=Hint AND Hint.Chapter == Chapter.ID) = 0) order by hint_level ASC LIMIT 1 I cannot figure out how to chain two queries together, the first being input to the second. Queryset = SELECT * from Hint WHERE chapter.id = CHAPTER_ID Pass in the queryset into GameActivity and return the one Hint with the lowest hint_level that doesn't have a GameActivity entry. Thanks for any help, I feel like I am not thinking about the problem correctly. BCBB -
Authentication failed: Include valid openId scopes like profile, email
I am building an app with Django and social-auth-app-django. I followed this tutorial. I created an app on LinkedIn for Developers, got the client_id and secret_key. I also made sure that the product Sign In with LinkedIn using OpenID Connect is added to my app. In settings.py, I added all the OAUTH2 parameters: SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY = '...' # Client ID SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET = '...' # Client Secret SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = ['r_basicprofile', 'r_emailaddress'] SOCIAL_AUTH_LINKEDIN_OAUTH2_FIELD_SELECTORS = ['email', 'formatted-name', 'public-profile-url', 'picture-url'] SOCIAL_AUTH_LINKEDIN_OAUTH2_EXTRA_DATA = [ ('id', 'id'), ('formattedName', 'name'), ('emailAddress', 'email_address'), ('pictureUrl', 'picture_url'), ('publicProfileUrl', 'profile_url'), ] However, I kept getting Authentication failed: Scope "r_basicprofile" is not authorized for your application. I changed SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE: SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = ['openid'] Now I get Authentication failed: Include valid openId scopes like profile, email. Based on the official LinkedIn documentation, I also tried SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = ['openid', 'profile', 'email'] But I got Authentication failed: Scope "r_liteprofile" is not authorized for your application. again. Has anyone an example of a settings.py configuration that works? -
why webSocket connection failed?
I've been trying to cerate a chat app using Django with webSocket,in console I got this, error WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/room/' failed: room/:20 I'm not using Redis for implementing Django channels, İt is just a simple chat app runs on local server host views.py def room(request, room_name): return render(request, "chatroom.html", {"room_name": room_name}) routing.py websocket_urlpatterns = [ re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatRoomConsumer.as_asgi()), ] consumer.py class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope["url_route"]["kwarges"]["room_name"] self.room_group_name = "chat_%s" % self.room_name await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() # to know which group we should send to await self.channel_layer.group_send( self.room_group_name, { "type": "tester_message", "tester": "hello world", }, ) async def tester_message(self, event): tester = event["tester"] await self.send(text_data=json.dumps({"tester": tester})) async def disconnect(self, close_code): await self.channel_layer.group_discard(self.room_group_name, self.channel_name) chatroom.html <div id="user-hello"> </div> <!-- convert an object into a JSON object --> {{room_name|json_script:"room-name"}} <script> // convert a JSON object in text format to js object that can be used const roomName=JSON.parse(document.getElementById('room-name').textContent); //create websocket connection script const chatSocket=new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/' ); //receive a massege chatSocket.onmessage=function(e){ const data=JSON.parse(e.data) console.log(data); document.querySelector('#user-hello').innerHTML=(data.tester) } </script> settings.py INSTALLED_APPS = [ "channels", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "chat", ] DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" ASGI_APPLICATION = "core.routing.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer", … -
Uncaught DOMException: Failed to execute 'querySelector' on 'Element': 'td:nth-child(...)' is not a valid selector
Hi guys I am building a django app, and i am struggling with js function to sort a html table ( values in the desired column ) by clicking the column name. Below I provide a html template and another html file which extends this template, and of course the js file itself. Any help is appreciated, thank you in advance! TEMPLATE: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Report Result</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link type="text/css" href="{% static 'css/report.css' %}" rel="stylesheet" /> </head> <body> <h1>{{ info }}</h1> <p style="font-size: 30px;">The report was generated successfully. You can download the xlsx file using the button below:</p> <p style="font-size: 20px;">To sort values by column, click the name of the desired column</p> <table id="data-table"> <thead> <tr> {% for col in column_names %} <th data-col="{{ col }}">{{ col }}</th> {% endfor %} </tr> </thead> <tbody>{% block content %}{% endblock %}</tbody> </table> <script src="{% static 'js/sorting.js' %}"></script> </body> </html> HTML FILE THAT EXTENDS THE PREVIUOS ONE: {% extends 'base_report.html' %} {% block content %} {% for row_data in data_to_render %} <tr> {% for cell_data in row_data %} <td> {% if cell_data.link %} <a href="{{ cell_data.value }}"> {{ cell_data.value }} </a> {% … -
modify models instances and sent to another model in django
I have 2 models in django Model A and Model B in model A exist 2 fields start_hour = models.TimeField() end_hour = models.TimeField() and I want to send this instance to a function and return a list with a slot time of 1 hour. for an example: start_hour = '10:00' end_hour = '15:00' output : [ ( '10:00 – 11:00'), ( '11:12 – 12:00'), ( '12:00 – 13:00'), ( '13:00 – 14:00'), ( '14:00 – 15:00'), ] i wrote function and works well my question is : i want in model B show list of time slot to select not show start time and end time Model_A = models.ForeignKey(Model_A, on_delete=models.CASCADE) I wrote this code, but it shows the start time and end time! -
OAuth2 Authentification Django and MSexchange
I am building a Django App where users have to be able to send emails with their specific exchange mail address. I think I need OAuth2 for that. However MS support and all other resources I found state that I need to register my app in Azure AD. But I don't have an Azure AD. I do have access to the Microsoft 365 admin center. Do I have to register my App there or generate a specific token? -
How to fix django mfa for firefox and safari (Registeration Failed as NotAllowedError: CredentialContainer request is not allowed)
I use the mfa library (https://pypi.org/project/mfa/) within my django project. In Chrome, the user can register a second factor (fido) easily, but in firefox, i get the following error: Registeration Failed as NotAllowedError: CredentialContainer request is not allowed., try again or Go to Security Home Im googeling this since hours but cant find a solution, i already checked CSP Settings. Any help is really appreciated! -
Passing Parent PK to ModelForm in Class Based Create and Update View
I'm updating function based views to class based views and having issues re-establishing the link between campaign and books. My Book Model has a foreign key link to Campaigns. campaign = models.ForeignKey(Campaign, on_delete=models.DO_NOTHING) I have a ModelForm where I set the campaign_id and would like to get this from the CreateView. class BookForm(forms.ModelForm): def __init__(self, *args, **kwargs): author = kwargs.pop('author', None) campaign_id = kwargs.pop('campaign_id', None) super(BookForm, self).__init__(*args, **kwargs) if campaign_id: self.fields['campaign_id'].initial = campaign_id campaign_id = forms.CharField(widget=forms.HiddenInput()) I followed this using dispatch and get_form_kwargs and my CreateView looks like class BookCreateView(generic.CreateView): model = Book template_name = 'PromoManager/book_form.html' form_class = BookForm success_url = '/profile' campaign_id = None # Retrieves the campaign_id from url def dispatch(self, request, *args, **kwargs): self.campaign_id = kwargs.get("pk") return super().dispatch(request, *args, **kwargs) ## Sends building id to the form def get_form_kwargs(self, *args, **kwargs): kwargs = super().get_form_kwargs(*args, **kwargs) kwargs["campaign_id"] = self.campaign_id return kwargs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['campaign'] = Campaign.objects.get(pk=self.campaign_id) context['title_label'] = "Create" return context def form_valid(self, form): instance = form.save(commit=False) instance.author = self.request.user instance.campaign = Campaign.objects.get(id=form.cleaned_data['campaign_id']) instance.save() form.save_m2m() return super().form_valid(form) But it breaks the UpdateView which relies on the same form as the PK passed on the update view URL is the book pk. My UpdateView looks … -
Odd results when running similar queries in Postgres
I am having this issue where my database is causing the CPU usage of our db server to hit 100% on a particular query. The query has two different where clauses and does not work, but when I delete either of the where clauses, the query returns quickly. The query i am trying to run is the following. This query references two tables in the database, asset_asset and asset_assetclassification. asset_asset has 1.8 million rows and asset_assetclassification has 7k rows. select count(1) from asset_asset INNER JOIN "asset_assetclassification" ON ("asset_asset"."classification_id" = "asset_assetclassification"."id") WHERE ("asset_assetclassification"."company_id" = 1 AND "asset_asset"."deleted_at" IS NULL); Here is a screenshot of the query plan for this query. And if i run this select count(1) from asset_asset INNER JOIN "asset_assetclassification" ON ("asset_asset"."classification_id" = "asset_assetclassification"."id") WHERE ("asset_assetclassification"."company_id" = 1); and here is a screenshot of the query plan for this query or this select count(1) from asset_asset INNER JOIN "asset_assetclassification" ON ("asset_asset"."classification_id" = "asset_assetclassification"."id") WHERE ("asset_asset"."deleted_at" IS NULL); the query works perfectly fine. Note: the original query was generated by Django. Any ideas about whats going on here? Thanks in advance! -
Send progressive data from django view to ajax
I have a django webapp. And I'm using jquery to send a POST. With that POST, I get multiple informations from the backend. But The page need to wait until all the informations are ready and then prin all of them. I would want, as an exemple, when the first one is finished, to be displayed, and then, when the second one is done, to be displayed and so on. That's my view: def home(request): context = {} if request.method == 'POST': is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' if is_ajax: context = {} # Update the expression if it's valid try: print('---------------------------------') print('POST[math-input]: {0}'.format(request.POST['math-input'])) print('POST[time]: {0}'.format(request.POST['time'])) data = request.POST['math-input'] core.max_time = int(request.POST['time']) print('---------------------------------') context = dispatch_expression(data) except Exception as exc: # exc_type, exc_obj, exc_tb = sys.exc_info() # fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] # print(exc_type, fname, exc_tb.tb_lineno) # print("Exception: {0}".format(exc)) traceback.print_exc() context = {'result': 'Expresie invalidă!'} return JsonResponse(context, status=200) template = loader.get_template('home.html') return HttpResponse(template.render(context, request)) Basically, dispatch_expression(data) is doing all the algorithms. I can modify that function to work with yields, without any problem, but I have no idea how to send each step when it's done. I heard about async, but any example on the internet didn't help me. I tried StreamingHttpResponse, but … -
Updates made via admin to m2m Django field are not persisted in the database
I`m new to Django and completely stuck with this one. This pet project is a website for online school. The default flow would be: user signups and has the role Student by default, then if this user is a school teacher admin updates the role to Teacher. I have the following User model which has role field, I plan to use it to display correct content for the user on the website, since I dont want to use groups and permissions for this purpose, at least not yet. But I want to have groups in sync with User roles and use groups to manage permissions inside admin. class User(AbstractUser): username = None email = models.EmailField(max_length=255, unique=True, verbose_name="email address") first_name = models.CharField(_("first name"), max_length=150) last_name = models.CharField(_("last name"), max_length=150) updated_at = models.DateTimeField(_("last updated to user"), auto_now=True) email_verified = models.BooleanField(default=False) role = models.PositiveSmallIntegerField( choices=UserRolesChoices.choices, default=UserRolesChoices.STUDENT ) date_of_birth = models.DateTimeField(_("date of birth"), null=True, blank=True) profile_picture = models.ImageField(_("profile picture"), null=True, blank=True, upload_to=profile_pic_directory_path, storage=OverwriteStorage) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] def __str__(self): return self.email @property def is_staff(self): return (self.role in (UserRoles.TEACHER, UserRoles.ADMIN)) or self.is_superuser @property def is_teacher(self): return self.role == UserRoles.TEACHER def save(self, *args, **kwargs): is_new_user = not self.pk changed_fields = … -
RecursionError: maximum recursion depth exceeded while calling a Python object when updating choice field
model: StatusChoices = ( ("TODO", "todo"), ("DOING", "doing"), ("DONE", "done"), ) class Task(models.Model): status = models.CharField( choices=StatusChoices, default=StatusChoices[0], max_length=5, ) request body: { "id": 15, "content": "Updated Task Content", "creationDate": "2020-10-23", "user": 2 , "status": "DONE" } serialiser: class TaskUpdateSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ("status") view class TaskUpdateAPIView(APIView): def patch(self, request, pk): try: task = Task.objects.get(pk=pk) except Task.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = TaskUpdateSerializer(task, data=request.data, partial=True) if serializer.is_valid(): task.status = request.data.get("status", task.status) task.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) url: urlpatterns = [ path("task/update/<int:pk>", TaskUpdateAPIView.as_view(), name='update-task' ), ] New error: RecursionError: maximum recursion depth exceeded while calling a Python object What am I missing? -
Override error representation on import model page django
I'm working with a django application and don't wanted to show users the stack trace when there is any error occurred in production. For example, I've added validation to validate import action under before_import method, and when there is any issue in the validation it shows error message along with stack trace. Please refer screenshot below: Instead I wanted to just show the error message only. This is mainly for the security purpose as on production it will disclose my server directory structure to it's users. I tried couple of things, to override import.html under my templates directory, but it didn't worked. to override exception using LOGGING in settings.py It is great, if I can show list of errors for all affected rows in a CSV/XLSX file.