Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Current URL anchor link gets added to my temple from Django Form Model ImageField
I've created an UserProfile. Facing an issue regarding ImageField. I had everything working fine on front-end until I added the image to my user profile from admin to test it. What I'm getting is anchor link which is a current URL of my user profile instead of getting a picture. I want help!! models.py from django.db import models from django.contrib.auth.models import User from django.template.defaultfilters import slugify from PIL import Image # Create your models here. class Profile(models.Model): slug = models.SlugField(max_length=255, unique=True, null=True) user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField('profile picture', default='accounts/avatars/default_avatar.jpg', upload_to="accounts/avatars/") bio = models.TextField(max_length=500, null=True) def __str__(self): return self.user.username def save(self, *args, **kwargs): self.slug = slugify(self.user.get_username()) super().save(*args, **kwargs) img = Image.open(self.avatar.path) # Open image # resize image if img.height > 150 or img.width > 150: output_size = (150, 150) img.thumbnail(output_size) # Resize image img.save(self.avatar.path) # Save it again and override the larger image views.py @login_required def profile(request): if request.method == 'POST': p_form = UpdateProfileForm(request.POST, request.FILES, instance=request.user.profile) if p_form.is_valid(): p_form.save() messages.success(request, f'Your profile has been updated!') return redirect('home') # Redirect back to home page else: p_form = UpdateProfileForm(instance=request.user.profile) print(p_form.fields) context = { 'p_form': p_form } return render(request, 'accounts/profile.html', context) profile.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="profile-pic-wrapper"> <div class="pic-holder"> … -
The current path, =/login/, didn’t match any of these. Django
def loginPage(request): page = 'login' username = request.POST.get('username') password = request.POST.get('password') try: user = User.objects.get(username=username) except: messages.error(request, 'user dose not exist') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') context = {'page':page} return render(request, 'base/login_register.html', context) Here is the django code snippet of mine in the views.py file but it gives me an error saying, The current path, =/login/, didn’t match any of these. Django As i can see i have entered the correct path but it's not working Here is my urls.py file urlpatterns = [ path('login/', views.loginPage, name="login"), path('logout/', views.logoutUser, name="logout"), path('register/', views.registerPage, name="register"), path('room/<str:pk>/', views.room, name="room"), path('create-room/', views.createRoom, name="create-room"), path('update-room/<str:pk>/', views.updateRoom, name="update-room"), path('delete-room/<str:pk>/', views.deleteRoom, name="delete-room"), path('', views.home, name="home"), ] I want to know the reason for the given error. -
Unable to Retrieve ForeignKey Objects in QuerySet
I’m just learning Django and i must say it is a very interesting framework. I'm facing an issue in my Django project where I'm unable to retrieve objects related to a ForeignKey field in a QuerySet. # models.py from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(Author, on_delete=models.CASCADE) Now, I'm trying to retrieve all books by a specific author using a QuerySet: # views.py from django.shortcuts import render from .models import Author, Book def books_by_author(request, author_id): author = Author.objects.get(pk=author_id) books = Book.objects.filter(author=author) return render(request, 'books_by_author.html', {'books': books, 'author': author}) My template <!-- books_by_author.html --> <h1>{{ author.name }}'s Books</h1> <ul> {% for book in books %} <li>{{ book.title }}</li> {% endfor %} </ul> However, the books are not being displayed as expected. What might be causing this issue, and how can I correctly retrieve and display books related to a specific author in my template? -
How to get move() operation to work in Django Treebeard
I'm having trouble getting the move() operation to work in Django Treebeard. Here's my model: class TestNode(MP_Node): name = models.CharField(max_length=200) node_order_by = ['name'] And a test: class TestNodeTestCase(TestCase): def test_move_test_node(self): get = lambda node_id: TestNode.objects.get(pk=node_id) # create ROOT -> parent -> child tree root = TestNode.add_root(name='ROOT') parent = get(root.id).add_child(name='parent') child = get(parent.id).add_child(name='child') # just to be on the safe side, requery all nodes root = get(root.id) parent = get(parent.id) child = get(child.id) # tree looks good: # [{'data': {'name': 'ROOT'}, 'id': 1, 'children': [{'data': {'name': 'parent'}, 'id': 2, 'children': [{'data': {'name': 'child'}, 'id': 3}]}]}] print(TestNode.dump_bulk()) # now move the child from the parent to ROOT child.move(root, 'sorted-child') child.save() # If I try dumping the tree here, I get this exception: # KeyError: '00010001' # print(TestNode.dump_bulk()) # requery all nodes root = get(root.id) parent = get(parent.id) child = get(child.id) # child's new parent should be ROOT self.assertEqual(child.get_parent().id, root.id) I get: myproj.models.TestNode.DoesNotExist: TestNode matching query does not exist I have read that most of the operations are performed in SQL, so I am obsessively reloading the model instances, but it's still not working. What am I doing wrong here? Thanks! -
Django Models Permission For Fields
let's say I've manually created three groups and three users through the admin site. Additionally, I have the following model: class Export(models.Model): export_group1 = models.BooleanField(default=False) export_group2 = models.BooleanField(default=False) export_group3 = models.BooleanField(default=False) How can I ensure that 'user1,' with the assigned permissions of 'group1,' only has access to the field 'export_group1'? Is it possible to implement this in the models.py file? -
Add scroll-y to a cell that overflows in jquer datatables and limit row height
I have a django web site that uses jquery datatables to display a table of 13 values. The first 12 values are a few words or numbers. The last column has many words. I would like to add a vertical scrollbar to the last column and limit the height of each row to 2 lines of text so the table is more compact. For example, on a widescreen monitor the table looks ok. But, if I make the browser window smaller, simulating a smaller screen, I get huge rows because of all the text in the last column. I am open to suggestions on how to other suggestions on how to make the table look better on smaller screens, including cell phones. The html for the table: {% for f in flights %} <div class="row mt-4"> <div class="col-12"> <div class="card mb-4"> <div class="card-header pb-0"> <p class="mb-1 pt-2 text-bold">{{ f.date }}</p> <h5 class="font-weight-bolder">{{ f.teacher_name }}</h5> </div> <div class="card-body px-0 pt-0 pb-2"> <div class="table-responsive p-0"> <table class="display" id="models" style="width:100%"> <thead> <tr class="text-center mb-0 text-lg font-weight-bold"> <th rowspan="2">Rocket Name</th> <th rowspan="2">Mission Specialists</th> <th rowspan="2">Flight Engineers</th> <th rowspan="2">Type</th> <th colspan="1">Lift-off Weight</th> <th colspan="2">Altitude</th> <th rowspan="2">Egg</th> <th rowspan="2">Shockcord</th> <th rowspan="2">Nose cone</th> <th rowspan="2">Coupler</th> <th rowspan="2">Parachute</th> … -
(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.