Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
(Django, Ajax, FormMixin, Forms) 500 (Internal Server Error) Error submitting form
To send and receive a response I use Ajax, Django and the Based View class. I want to implement form submission via Ajax so that the page does not reload after submitting the form. To receive the form to the server I use FormMixin. I get the following error in the console 500 (Internal Server Error): views.py: import os import json from urllib import request from django.conf import settings from django.views.generic import TemplateView, ListView, DetailView from django.views.generic.edit import FormMixin from django.shortcuts import redirect from django.http import JsonResponse from mobile_template.views import MobileTemplateView from .models import Layouts from .forms import RequestPriceForm class LayoutsDetail(MobileTemplateView, FormMixin, DetailView): model = Layouts template_name = 'main/layouts_detail.html' form_class = RequestPriceForm # def get_context_data(self, **kwargs): # context = super().get_context_data(**kwargs) #context['form'] = RequestPriceForm() #try: #pet = json.load(request.urlopen('https://pets.nlk.agency', timeout=1)) #context['pet'] = pet['pet'] #context['token'] = pet['token'] #except: #context['token'] = None #context['pet'] = None #return context def get_success_url(self): return reverse('layouts_detail', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super(LayoutsDetail, self).get_context_data(**kwargs) context['form'] = RequestPriceForm() try: pet = json.load(request.urlopen('https://pets.nlk.agency', timeout=1)) context['pet'] = pet['pet'] context['token'] = pet['token'] except: context['token'] = None context['pet'] = None return context def post(self, request, *args, **kwargs): form = RequestPriceForm(request.POST) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_invalid(self, form): response = super(LayoutsDetail, … -
Django Is it possible to display images from media subfolders?
I have the project in which admin(editor) is uploading images to database and they will display in articles and articles minatures (form of a list). I managed to configure displaying images from the media folder but it is not working in the way i would it like to be. I would like to upload images in the specific subfolders of "Media" folder. e.g: blog/media/reviews_images blog/media/reviews_minatures_images I know that upload to the specific folders is possible but that is not the point of this question. I am courious how can i configure MEDIA ROOT to display images from different subfolders of it. Now I can specify one of this folders as MEDIA ROOT and the images from this folder are displaying correctly but from the other arent displaying at all. Is it possible to configure that? my code: models.py fs_reviews_images = FileSystemStorage(location="blog/media/reviews_images") class ReviewsImages(models.Model): image = models.ImageField(storage=fs_reviews_images) description = models.CharField(max_length=50) fs_reviews_minature_images = FileSystemStorage(location="blog/media/reviews_miniatures_images") class ReviewsMiniaturesImages(models.Model): miniature_image = models.ImageField(storage=fs_reviews_minature_images) description = models.CharField(max_length=50) game_title = models.CharField(max_length=50) def __str__(self): return f"{self.game_title} {self.description}" urls.py urlpatterns = [ path("admin/", admin.site.urls), path("", views.HomeView.as_view(), name="home"), path("reviews", views.ReviewsListView.as_view(), name="reviews"), path("reviews/article/<pk>", views.ReviewsDetailView.as_view(), name="reviews-detail") ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py MEDIA_ROOT = os.path.join(BASE_DIR, "blog/media/reviews_miniatures_images") MEDIA_URL = '/media/' template <img src="{{ MEDIA_URL }}{{ … -
APIView Query Not Returning Any Results
I am having one of those days where the things I think are going to be easy on this project are just not turning out that way. I feel like I must be overlooking something very simple here in my frustration... I have an APIView that passes in the a UUID to identify the "chapter" of the game story, checks to see if the current logged in user has an entry saying they completed the challenge, then if so returns the next Hunt Clue (different from the chapter challenge) or zero for me to handle in the UI. For some reason, it is not returning any results in the query. However, when I output the raw sql query (queryset.query) the query returns the results expected just fine. Any help greatly appreciated. View class GetHuntClue(APIView): def get(self, request, **kwargs): serializer_context = { 'request': request, } chapter_uuid = self.kwargs['chapter_uuid'] curr_user = self.request.user #check to make sure it's answered then provide the appropriate hunt clue. log_type = GameActivityType.objects.filter(activity_type_name="Correct Challenge Answer").first() already_ans = GameActivity.objects.filter(user=curr_user).filter(activity_chapter=chapter_uuid).filter(activity_type=log_type).count() if (already_ans): queryset = HuntClue.objects.filter(hunt_chapter=chapter_uuid) print(queryset.query) serializer = HuntClueSerializer(queryset, context=serializer_context) return Response(serializer.data) else: return HttpResponse(already_ans, content_type="text/plain") Serializer class HuntClueSerializer(serializers.ModelSerializer): class Meta: model = HuntClue #fields = '__all__' fields = ("id", … -
How does post_save take the data after saving?
django signal post_save I am curious. I asked chatgpt. I read a bit of the docs. @receiver(post_save, sender=Comment) def post_save_comment(sender, instance, **kwargs): instance.pk .. I can get pk. characteeeeeersssssssssssss -
Form input value returns None in ajax,django
$(document).ready(function() { $('#sonuc1').on('keyup', function() { var sonuc1 = $('#sonuc1').val(); var sonuc2 ='' var csrf_value = $('input[name="csrfmiddlewaretoken"]').val(); if (sonuc1 === 'NO'){ $('#sonuc2').show(); sonuc2 = $('#sonuc2').val(); } // Send AJAX request to the Django view $.ajax({ type: 'POST', url: '/pkl/rpa/', // Replace with the actual URL of your Django view data: { 'sonuc1': sonuc1, 'sonuc2':sonuc2, 'csrfmiddlewaretoken': csrf_value }, success: function(response) { // Handle the response from the server if needed console.log('Server Response:', response); }, error: function(error) { console.error('Error:', error); } }); }); }); what i am trying to do is if sonuc1 equals no show sonuc2 input element on form and get both values and send to django using ajax def rpa_save(request): if request.method == 'POST': sonuc1 = request.POST.get('sonuc1') sonuc2 = request.POST.get('sonuc2') if sonuc1 == 'NO': print(sonuc1) print(sonuc2) return JsonResponse({'status': 'success'}) # Handle other HTTP methods or return an error response return JsonResponse({'status': 'error', 'message': 'Invalid request method'}) why sonuc2 returns None type when i submit or i try to get values before submitting ? -
Display JSON data with Django/ Python and Bootstrap
I want to display data from a countries API (Json format) into a bootstrap 5 card inside a Django project. The Json file contains dictionarries and lists. I can access data to use a for loop. For example x.capital.0 displays the capital for all the countries. But the currencies is the problem because it is a nested dictionarry. I could use x.currencies.USD.name but then I have to specify the second key (USD) for every country so the I have to use 100 lines of code the do this. Is there a way to skip the second key? I tryed x.currencies.itmes(), x.currencies.values(), x.currencies[1] and much more. Could you please help to solve this problem. Many thanks in advance. Github: https://github.com/Roelof132/countries-app/blob/main/space/templates/home.html API: 'https://restcountries.com/v3.1/all' For the API also see the views.py file. -
Django save chunked files leading to invalid file errors
In my create post endpoint I call this function to upload a file (currently for debugging purposes I instantly run assemble_attachment, but when all bugs are fixed, it will run as an automated task) def _save_chunk(chunk: bytes, chunk_index, attachment_type: str, attachment_name: str, attachment_extension: str): if attachment_type == "VIDEO": destination = config.media_source + f'temporary/{attachment_name}_{chunk_index}.webm' with open(destination, 'wb') as file: file.write(chunk) return if attachment_type == "IMAGE": destination = config.media_source + f'temporary/{attachment_name}_{chunk_index}.webp' with open(destination, 'wb') as file: file.write(chunk) return if attachment_type == "AUDIO": destination = config.media_source + f'temporary/{attachment_name}_{chunk_index}.{attachment_extension}' with open(destination, 'wb') as file: file.write(chunk) return def upload_attachment(attachment: UploadedFile, user_permissions: permissions.Permissions) -> tuple: # more code chunk_index = 1 for chunk in attachment.chunks(): _save_chunk(chunk, chunk_index, post_type, attachment_name, attachment_extension) chunk_index += 1 print(f'Chunks saved in {time.time() - start_time} seconds.') post_attachment = models.PostAttachment.objects.create( attachment_type=post_type, name=attachment_name, extension=attachment_extension ) assemble_attachments._assemble_attachment(post_attachment) # more code For this example, I am showing the flow for saving an image, but the others aren't unstable. The issue is that some files will give an error, while others will work flawlessly. def _assemble_image(post_attachment: models.PostAttachment): destination = os.path.join(config.media_source, 'attachments', f'{post_attachment.name}.webp') image_chunks = [] for file in os.listdir(config.media_source + 'temporary/'): if file.startswith(post_attachment.name): chunk_path = os.path.join(config.media_source, 'temporary', file) try: with open(chunk_path, 'rb') as chunk_file: data = chunk_file.read() … -
"GET /static/vendor/bootstrap/css/bootstrap.min.css HTTP/1.1" 404 -
Hello guys I have a problem when i run my app.py the css and images won't work. I already partition the static file from the template. Can you guys help me with this one. Thank you!! <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@100;200;300;400;500;600;700;800;900&display=swap" rel="stylesheet"> <title>Villa Agency - Real Estate HTML5 Template</title> <link href="/static/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="/static/assets/css/fontawesome.css"> <link rel="stylesheet" href="/static/assets/css/templatemo-villa-agency.css"> <link rel="stylesheet" href="/static/assets/css/owl.css"> <link rel="stylesheet" href="https://unpkg.com/swiper@7/swiper-bundle.min.css"> I already pip install bootstrap-v5 and also include the INSTALLED_APPS = ( # ... "bootstrap5", # ... ) but it won't work either -
How do I make the channels for each chats using Pusher Channel
So basically I am making a social media web using Django, and I also build a chat message on my web as well, so I looked into YouTube and followed a tutorial to make a real-time chat message, and I also use the Pusher WebSocket to hold the message to be sent, but I met a problem is that when I message with the one I click on, the message is also displayed to the other user account, but it does not actually exist because when the other user reload the page, the message from me to the user I chat with disappear. The success part is that the message is displayed forever in my chat with the one I message with even if I reload the page. I spent almost a week to figure it out but any ideas I think about aren't working. So these are my code for the real-time message THIS IS MY VIEWS.PY FILE @login_required(login_url='login') def chat_room(request): uid = request.user.id user = Profiles.objects.get(id = uid) follows = user.follows.all() context = {'user':user, 'follows':follows} return render(request,"chat_room.html",context) @login_required(login_url='login') def chat_details(request,id): uid = request.user.id user = Profiles.objects.get(id = uid) follows = user.follows.get(id=id) form = ChatMessageForm() chats = ChatMessage.objects.all() receive_chats … -
How to send multiple time series objects (created in Django view) to Dash Application for plot?
I have a Django application aiming to track my stock portfolio daily value (Time Series 1) and daily return (Time Series 2). These 2 Time Series are computed in Django based on custom models and methods. On my homepage, I want to display these Time Series in a Dash app with 2 buttons: "Returns" and "Prices". Depending on the button pressed, only one of the 2 time series will be plotted. I am using the django-plotly-dash package. dash_app.py import dash from dash import dcc, html from django_plotly_dash import DjangoDash app = DjangoDash('Dashboard') app.layout = html.Div(children=[ # Price / Return mode dcc.RadioItems( id="radio-chart-mode", options=["Prices", "Returns"], value="Returns", inline=True), # Buttons below for dates html.Div([ html.Button(id='btn-horizon-1m', children="1m"), html.Button(id='btn-horizon-3m', children="3m"), html.Button(id='btn-horizon-6m', children="6m"), html.Button(id='btn-horizon-ytd', children="YTD"), html.Button(id='btn-horizon-1y', children="1Y"), html.Button(id='btn-horizon-3y', children="3Y"), html.Button(id='btn-horizon-max', children="Max") ]), # The Time Series chart html.Div(dcc.Graph(id='graph-ts', figure={})), ]) # Price/Return callback @app.callback( dash.dependencies.Output('graph-ts', 'figure'), [dash.dependencies.Input('radio-chart-mode', 'value')], prevent_initial_call=False ) def update_the_graph(chart_mode: str): if (chart_mode == "Prices"): # Draw Prices Graph based on ts_prices pass elif chart_mode == "Returns": # Draw Return Graph based on ts_returns pass My issue is that I cannot pass the 2 time series object from my Django view to the Dash application. I have tried to take advantage of the … -
Issue in django in personalpage
i work on pet project (emergency notification system) this is my views from django.shortcuts import render, redirect from django.views.generic import TemplateView from django.contrib.messages.views import SuccessMessageMixin from django.views.generic.edit import CreateView from django.urls import reverse_lazy from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.contrib import messages #################################################### class Main(TemplateView): template_name = 'emnosys/main.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['css_file'] = 'styles.css' return context ################################################### def Registration(request): if request.method == "POST": username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] password2 = request.POST['password2'] myuser = User.objects.create_user(username, email, password1) myuser.save() return redirect('signin') return render(request, "emnosys/registration.html") ############################################### def Signin(request): if request.method == 'POST': username = request.POST['username'] password1 = request.POST['pass1'] user = authenticate(username=username, password=password1) if user is not None: login(request, user) return render(request, "emnosys/main.html") else: return redirect('signin') return render(request, "emnosys/signin.html") ################################################ def Signout(request): logout(request) return redirect('home') ###################################################### class PersonalPage(TemplateView): template_name = 'emnosys/personalpage.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['css_file'] = 'styles.css' return context this is my urls from django.urls import path from . import views from .views import Main urlpatterns = [ path('', Main.as_view(), name='home'), path('registration/', views.Registration, name='registration'), path('signin/', views.Signin, name='signin'), path('signout/', views.Signout, name='signout'), path('personalpage/', views.PersonalPage, name='personalpage'), ] this is my personal page html <!DOCTYPE … -
ICONS are not showing up In the toolbar section TinyMCE Django
The icons are not showing up in the toolbar section. TinyMCE=3.6.0 settings.py TINYMCE_JS_URL = os.path.join(STATIC_URL, "tinymce/tinymce.min.js") TINYMCE_JS_ROOT = os.path.join(STATIC_ROOT, "tinymce") TINYMCE_DEFAULT_CONFIG = { "height": "320px", "width": "800px", "selector": "textarea", "plugins": "advlist autolink lists link image charmap print preview anchor searchreplace visualblocks code " "fullscreen insertdatetime media table paste code help wordcount spellchecker", "toolbar": '''undo redo | bold italic underline strikethrough | fontselect fontsizeselect formatselect | alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist checklist | forecolor backcolor casechange permanentpen formatpainter removeformat | pagebreak | charmap emoticons | fullscreen preview save print | insertfile image media pageembed template link anchor codesample | a11ycheck ltr rtl | showcomments addcomment code''', "custom_undo_redo_levels": 10, "language": "en", # To force a specific language instead of the Django current language. } I am using TinyMCE in my Django application, but the icons in the toolbar are not showing up. I have checked that the icons are included in the toolbar configuration and that the necessary CSS and JavaScript files are loaded. I have also tried clearing my browser cache and reloading the page, but the issue persists. I expected the icons to appear in the toolbar as in the TinyMCE documentation. What could be … -
All Auth and Swagger
I'm trying to use Django All Auth and DRF YASG (Yet another swagger generator) to use Googles OAuth2. I was able to use Django Session Authentication to pop open the google auth portal and successfully log in the user, however I now need to use this functionality from an outside source, prompting me to need to use the swagger oath. This is my current setup. # Swagger SWAGGER_SETTINGS = { "DEFAULT_INFO": "django_project.urls.app_info", "USE_SESSION_AUTH": False, "SECURITY_DEFINITIONS": { "Your App API - Swagger": { "type": "oauth2", "authorizationUrl": "accounts/google/login", "tokenUrl": "accounts/google/login/callback", "flow": "accessCode", } }, "OAUTH2_REDIRECT_URL": "accounts/google/login", "OAUTH2_CONFIG": { "clientId": OAUTH_CLIENT, "clientSecret": OAUTH_SECRET, "appName": "PushApp", }, } # Oauth2 LOGIN_REDIRECT_URL = "/" LOGOUT_REDIRECT_URL = "/" ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_EMAIL_REQUIRED = True SOCIALACCOUNT_LOGIN_ON_GET = True ACCOUNT_LOGOUT_ON_GET = True AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ] SOCIALACCOUNT_PROVIDERS = { "google": { "EMAIL_AUTHENTICATION": True, "APP": { "client_id": OAUTH_CLIENT, "secret": OAUTH_SECRET, "key": "", }, "SCOPE": [ "profile", "email", ], "AUTH_PARAMS": { "access_type": "online", }, } } This setup successfully opens the google login portal, however, when it redirects back to the swagger page, I am not logged in. The problem must be in my redirect urls, being authorizationUrl, tokenUrl, or OAUTH2_REDIRECT_URL. However, I'm not sure what to set … -
AttributeError: '_io.BytesIO' object has no attribute 'endswith' when attempting to check audio and video codec from base64 video file in Django
I'm currently working on a Django project where I need to check the audio and video codec of a base64-encoded video file. To achieve this, I've implemented a function that decodes the base64 string into binary data and then attempts to load the video clip using MoviePy. However, I'm encountering an AttributeError: '_io.BytesIO' object has no attribute 'endswith' when trying to run the code. Here's the relevant part of the code: def get_video_codec_info(base64_data): # Decode base64 string into binary data _format, _file_str = base64_data.split(";base64,") binary_data = base64.b64decode(_file_str) # Load the video clip using MoviePy clip = VideoFileClip(BytesIO(binary_data)) # Get information about the video codec codec_info = { 'video_codec': clip.video_codec, 'audio_codec': clip.audio_codec, } return codec_info The error occurs at the line clip = VideoFileClip(BytesIO(binary_data)) and it seems related to the use of BytesIO. I've tried to find a solution, but I'm stuck at the moment. Any suggestions on how to resolve this issue or alternative approaches to check the audio and video codec of a base64-encoded video file in Django would be greatly appreciated. Thanks! -
sign-up:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error)
enter image description here `Title: Internal Server Error (500) on Django Sign-up Page - Need Assistance with is_ajax Attribute Issue Description: Hello community, I'm currently working on a Django project and have run into an Internal Server Error (500) on the sign-up page. After some investigation, it appears to be related to the is_ajax attribute in the views.py file. I've included the relevant code snippets and traceback below for your review.` views.py class SignUpView(AjaxFormMixin, FormView): ''' Generic FormView with our mixin for user sign-up with reCAPTCHA security ''' template_name = "users/sign_up.html" form_class = UserForm success_url = "/" # reCAPTURE key required in context def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["recaptcha_site_key"] = settings.RECAPTCHA_PUBLIC_KEY return context # overwrite the mixin logic to get, check and save reCAPTURE score def form_valid(self, form): response = super(AjaxFormMixin, self).form_valid(form) if self.request.is_ajax(): token = form.cleaned_data.get('token') captcha = reCAPTCHAValidation(token) if captcha["success"]: obj = form.save() obj.email = obj.username obj.save() up = obj.userprofile up.captcha_score = float(captcha["score"]) up.save() login(self.request, obj, backend='django.contrib.auth.backends.ModelBackend') # change result & message on success result = "Success" message = "Thank you for signing up" data = {'result': result, 'message': message} return JsonResponse(data) return response urls.py from django.urls import path from . import views app_name = "users" urlpatterns … -
Understanding and Fixing User Permissions Logic in Django
I know this might be a silly question but please don't laugh at me. I am struggling to understand this simple logic. I am not understating why this logic is not working where it means if request.user is not the owner of the object or the user is not an admin user. The first part of this logic works to prevent other users from overwriting the owner object but why second part not working where a user can be overwritten object if he is an admin user? if (request.user != comment.user) or (not request.user.is_superuser): why my above logic only working for if user != owner of the obj ? why admin user can't edit if he is an admin? but this logic works on both part if not (request.user.is_superuser or (request.user == blog.blog_author)): -
In the below code how def save() is working? [closed]
In This code explain the working of code block mentioned below from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class NewUserForm(UserCreationForm): CHOICES=( ('Doctor','D'), ('Patient','P'), ('Manager','M') ) email = forms.EmailField(required=False) username = forms.CharField(required=True) phone = forms.IntegerField(required=False) role = forms.CharField(widget=forms.Select(choices=CHOICES)) password1 = forms.CharField(required=True) password2 = forms.CharField(required=True) class Meta: model = User fields = ("email","username","phone","role","password1","password2") def save(self,commit=True): user = super(NewUserForm,self).save(commit=False) user.email = self.changed_data['email'] if commit: user.save() return user Please explain working of def save and class Meta , what is the use of .save(commit=False) here. -
Some static files are throwing 404 when deploying Django on vercel
I am deploying my Django project on vercel This is my vercel.json file { "version": 2, "builds": [ { "src": "event_management/wsgi.py", "use": "@vercel/python", "config": {"maxLambdaSize": "15mb", "runtime": "python3.9"} }, { "src": "build_files.sh", "use": "@vercel/static-build", "config": { "distDir": "staticfiles_build" } } ], "routes": [ { "src": "/static/(.*)", "dest": "/static/$1" }, { "src": "/(.*)", "dest": "event_management/wsgi.py" } ] } my settings.py STATIC_URL = 'static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles_build', 'static') everything works fine but when I open the admin panel one CSS file static/admin/css/base.css is throwing 404 error all the other static files are loading fine Here is the admin panel link. the base.css is even listed in Vercel static Assets You can also check the file is present on the directory listing here here is my github repo link the code is in main branch -
Choose the best backend for real-time wbapp
I have a gps tracking service tha is monitoring data (ex cars) from database on the openlyers map realtime. I want to use websocket. So what is the best for backend . Django channels or nodejs?? I want to use postgresql but django channels use redis. -
Python Plotly Line Chart not displaying Lines
I am trying to create an app that would display some charts based on chosen item for an average monthly data, like "6/2023", "7/2023". I have the code which is working and I can see output in my terminal, but the line graph won't work, just a blank page, and looks like it is not receiving my data. Please help class Item(models.Model): item = models.CharField(max_length=100) date = models.DateField(null=True) price = models.FloatField() def __str__(self): return self.item def line(request): items = Item.objects.values_list('item', flat=True).distinct() item = request.GET.get('item', 'Drink') data = Item.objects.filter(item=item).annotate( month=F('date__month'), year=F('date__year') ).values( 'month', 'year' ).annotate( avg_price=Avg('price') ).order_by( 'year', 'month' ) item_years = [f"{k['month']}/{k['year']}" for k in data] item_price = [f"{v['avg_price']}" for v in data] cds = ColumnDataSource(data=dict(item_years=item_years, item_price=item_price)) fig = figure(height=500, sizing_mode="stretch_width", title=f"{item} GDP") fig.title.align = 'center' fig.title.text_font_size = '1.5em' fig.yaxis[0].formatter = NumeralTickFormatter(format="$0.0a") fig.circle(source=cds, x='item_years', y='item_price', size=12) fig.line(source=cds, x='item_years', y='item_price', line_width=2) tooltips = [ ('Year', '@item_years'), ('Price', '@item_price') ] fig.add_tools(HoverTool(tooltips=tooltips)) script, div = components(fig) context = { 'items': items, 'item': item, 'script': script, 'div': div, } if request.htmx: return render(request, 'analysis/partials/gdp-bar.html', context) return render(request, 'analysis/line.html', context) <div class="row"> <div id="linechart" class="col-10"> {% include 'analysis/partials/gdp-bar.html' %} </div> <div class="col-2"> <label>Product</label> <select id="select-year" class="custom-select" name="item" autocomplete="off" hx-get="{% url 'linechart' %}" hx-target="#linechart"> {% for … -
Django why my post.count_views increments by 2?
Good evening, everyone, I'm a beginner at Django I have blog page details that has count views and category for the blog post and blog post tags and other staff my post model is: class Post(models.Model): title = models.CharField(max_length=250) content = RichTextUploadingField() post_date = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=200, unique=True) image = models.ImageField(null=True, blank=True, upload_to="images/") tagss = models.ManyToManyField(Tags, blank=True, related_name='post') Categorys = models.ManyToManyField(Category, blank=True, related_name='post') views_count = models.IntegerField(default=0, null=True, blank=True) def __str__(self): return self.title and my view is: def post_page(request, slug): post = Post.objects.get(slug = slug) post.views_count = post.views_count + 1 post.save() print("views:", post.views_count ) cats = Category.objects.all() tags = Tags.objects.all() # change 2 to how many random items you want random_items = list(Post.objects.all().order_by('?')[:2]) related_posts = list( Post.objects.filter( Q(tagss__name__in=[tag.name for tag in post.tagss.all()]) | Q(Categorys__name__in=[Category.name for Category in post.Categorys.all()]) ).distinct() ) recent_posts = Post.objects.all().order_by('-id')[:4] context = {'post': post, 'cats': cats, 'tags': tags, 'recent_posts': recent_posts, 'random_blog': random_items, 'related_posts': related_posts} return render(request, 'blog/Blog_details.html', context) my problem is when I refresh the post page the views increase by 2 I need when the user refresh the page increase by 1 Thanks everyone -
Session is set to None when calling an rest_framework class based endpoint
In my webpage the user will login with spotify in order to use the spotify api and display things like top songs, top artists etc. After implementing the authorization flow of spotify api, I created and endpoint that should check if the current session_id is in my database with an already assigned access token / refresh token and login the user (and generate new access token if required). The problem is inside the endpoint function, the session is None. Checking session function (here self.session.session_key is None): class IsAuthenticated(APIView): def get(self, request, format=None): # self.request.session.save() # if not request.session.session_key: # request.session.save() is_authenticated = is_spotify_authenticated(self.request.session.session_key) return Response({'is_authenticated': is_authenticated}, status=status.HTTP_200_OK) Where I make the request from (and I have the correct session): def home(request): response = get('http://127.0.0.1:8000/api/is-authenticated').json() # print(response) # print(f"{request.session.session_key=}") request.session["is_authenticated"] = response.get("is_authenticated") return render(request, "home.html") I've tried as you can see from the commented code to call .save() but it just creates a new session, it does not use the initial one -
mypy django models typehint
I integrated mypy into my project and would like to type my django models, how would I enable the following conversions? ForeignKey to the actual model, charField and textField to str, DecimalField to Decimal... class mymodel(models.Model): address: str = models.CharField(max_length=100) description: str = models.TextField() organisation: Organisation = models.ForeignKey( "organisations.Organisation", on_delete=models.CASCADE, related_name="properties", editable=False, ) My current setup.cfg file looks like this: [mypy] plugins = mypy_drf_plugin.main, mypy_django_plugin.main, pydantic.mypy exclude = /migrations/|template python_version = 3.11 no_implicit_optional = True strict_optional = True [mypy.plugins.django-stubs] django_settings_module = "backend.settings" -
Django rest serializer problem with serializing many-to-many field
I cannot serialize menu object, which contains foreign key to DishOrder object which contains a foreign key to Dish object. class Dish(models.Model): name = models.CharField(max_length=20, blank=False, null=False, unique=True) ... def __str__(self): return self.name class Menu(models.Model): name = models.CharField(max_length=50, unique=True) ... @property def cost(self): return self.dishes.aggregate(total_cost=Sum('dish__price'))['total_cost'] or 0.00 def __str__(self): return f"Меню '{self.name}'" class DishOrder(models.Model): dish = models.ForeignKey(Dish, on_delete=models.SET_NULL, blank=True, null=True) menu = models.ForeignKey(Menu, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.PositiveIntegerField() def __str__(self): return self.dish.name Here are my serializers: class DishSerializer(serializers.ModelSerializer): category = serializers.CharField(source='category.category', read_only=True) price = serializers.FloatField() class Meta: model = Dish fields = '__all__' class DishOrderSerializer(serializers.ModelSerializer): dish = DishSerializer() class Meta: model = DishOrder fields = ['dish', 'quantity'] class MenuSerializer(serializers.ModelSerializer): dishes = DishOrderSerializer(many=True) class Meta: model = Menu fields = '__all__' Error after calling MenuSerializer(all_menus) AttributeError: Got AttributeError when attempting to get a value for field `dish` on serializer `DishOrderSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Dish` instance. Original exception text was: 'Dish' object has no attribute 'dish'. ChatGPT says: the problem may occur because of dish naming -
NoReverseMatch Django - Attribute printing elsewhere in file?
I am getting a 'No reverse match' error in my Django DeleteView template. I have done some research, and this is supposedly caused when an attribute for a url redirect is blank. The error looks like the following, however the success button redirect works as expected, it is only erroring on my 'cancel' option. In this case, the url thats generating this error looks like the following: <a class="mt-3 mb-3 btn btn-secondary" id="cancel-btn" href="{% url 'post-detail' object.id %}">Cancel</a> This would mean that, 'object.id' is blank/null... However, I have added this attribute into a paragraph tag within the same template, and am seeing the correct value print (in this case, 3). {% block content %} <div> <form method="POST"> {% csrf_token %} <!--required security token--> <fieldset class="form-group"> <legend class="border-bottom mb-4">Delete Event</legend> <p>Are you sure you want to delete the post "{{object.id}}"?</p> </fieldset> <div class="form-group text-center"> <button class="btn btn-danger m-3" type="submit">Yes, Delete</button> <a class="mt-3 mb-3 btn btn-secondary" id="cancel-btn" href="{% url 'post-detail' object.id %}">Cancel</a> </div> </form> </div> {% endblock content %} Perhaps I have incorrectly typed my code, but I can't seem to figure out how the value could possibly get erased and is unable to be referenced for the cancel button href? My …