Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'str' object has no attribute 'name' Django rest api video post error
Here is my django rest api app for uploading videos,my models.py file is below, from django.db import models from django.contrib.auth.models import User from likevideos.models import Likevideo class Video(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255,blank=True) video_file = models.FileField(upload_to='videos/') description = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-created_at'] def __str__(self): return f"Video by {self.id}: {self.title}" @property def like_count(self): return self.likevideos.count() @property def comment_count(self): return self.videocomments.count() Here is my views.py file, from rest_framework import generics, permissions, filters from friends_chats.permissions import IsOwnerOrReadOnly from rest_framework.response import Response from .models import Video from .serializers import VideoSerializer class VideoListCreateView(generics.ListCreateAPIView): permission_classes = [permissions.IsAuthenticated, IsOwnerOrReadOnly] queryset = Video.objects.all() serializer_class = VideoSerializer filter_backends = [ filters.OrderingFilter, filters.SearchFilter, ] search_fields = [ 'owner__username', 'title', ] ordering_fields = [ 'like_count', 'comment_count', 'likevideos__created_at', ] def perform_create(self, serializer): serializer.save(owner=self.request.user) class VideoDetailView(generics.RetrieveUpdateDestroyAPIView): permission_classes = [IsOwnerOrReadOnly] queryset = Video.objects.all() serializer_class = VideoSerializer Here is my serializer, from rest_framework import serializers from django.core.validators import FileExtensionValidator from django.core.exceptions import ValidationError as DjangoValidationError from .models import Video from .models import Likevideo class VideoSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') is_owner = serializers.SerializerMethodField() likevideo_id = serializers.SerializerMethodField() like_count = serializers.ReadOnlyField() comment_count = serializers.ReadOnlyField() class Meta: model = Video fields = ['id', 'owner', 'title', 'video_file', 'description', 'created_at', 'updated_at', 'is_owner','likevideo_id','like_count','comment_count'] … -
How to override form field in Django function based view?
I like to use a form in a function based view but I like to override the kategoria select field to show only the objects that related to the user. models.py class Blog_poszt(models.Model): def __str__(self): return str(self.user) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blog_szerzo") datetime = models.DateTimeField(auto_now_add=True, auto_now=False) cim = models.CharField(max_length=300) cim_slug = models.CharField(max_length=300, null=True, blank=True) szoveg = models.CharField(max_length=10000, null=True, blank=True) kategoria = models.ForeignKey('Blog_kategoriak', on_delete=models.CASCADE, null=True, blank=True) kep = models.FileField(upload_to="blog/", null=True, blank=True) class Blog_kategoriak(models.Model): def __str__(self): return str(self.user) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="kategoria_szerzo") datetime = models.DateTimeField(auto_now_add=True, auto_now=False) kategoria = models.CharField(max_length=200) forms.py class UjBlogposztForm(forms.ModelForm): class Meta: model = Blog_poszt fields = '__all__' exclude = ('user',) views.py def blog_poszt(request): form = UjBlogposztForm(request.POST, request.FILES) if request.method == 'POST': if form.is_valid: form.instance.user = request.user form.save() context = { 'form': form, } html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-dark">Mentés</button> </form> -
I'm creating a website with the Django framework and I have a problem
path('accounts/login/', auth_view.LoginView.as_view(template_name='app/login.html', authentication_form=LoginForm), name='login'), path('logout/', auth_view.LogoutView.as_view(next_page='login'), name='logout'), when i want to use logout function i have set in my urls.py as above and also i have linked it well in my base.html like this href="{% 'logout' url %}" but after I tried the logout page it didn't work please help me please -
Django authenticate() always returns None
I am building a web project with Django to facilitate distribution in case of an earthquake. The user needs to be a member as a Mukhtar or a Helper. The registration system works successfully. But the login part is constantly returning None value even though my login information is absolutely correct. models.py: from django.db import models from django.contrib.auth.models import AbstractUser from base64 import b32encode from hashlib import sha1 from random import random # Create random id def pkgen(): rude = ('lol',) bad_pk = True while bad_pk: pk = b32encode(sha1(str(random())).digest()).lower()[:24] bad_pk = False for rw in rude: if pk.find(rw) >= 0: bad_pk = True return pk # Create your models here. class User(AbstractUser): muhtar = models.BooleanField(null=False,default=False) username = models.CharField(max_length=28, null=False, unique=False) email = models.EmailField(null=False, unique=True) tc = models.CharField(max_length=11, null=False, unique=True) address = models.TextField(null=False) need_help = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'tc' #Uyarı! Bu benzersiz olmasını ister REQUIRED_FIELDS = ['username'] def __str__(self): return f"{self.username}" class sos(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) sos_key = models.CharField(max_length=24, primary_key=True, default=pkgen, unique=True) address = models.TextField(null=False, unique=False) def __str__(self): return f"{self.user}" views.py: from django.shortcuts import render, redirect from .models import User from django.contrib.auth import authenticate, login, logout # Create your views here. def index(request): return render(request, "harita.html") def … -
UnboundLocalError: local variable 'client' referenced before assignment in Celery task
I am working on a Django project with Celery and Channels for handling MQTT connections. I have a Celery task (mqtt_client_task) that connects to an MQTT broker, and I am encountering the following error: File "/home/<user>/../../iot/tasks.py", line 30, in mqtt_client_task logger.error("Failed to connect, return code %d", rc) UnboundLocalError: local variable 'client' referenced before assignment Here's a simplified version of the relevant code: tasks.py: # iot/task.py from celery import shared_task from paho.mqtt import client as mqtt_client_module from asgiref import sync from channels.layers import get_channel_layer from django.conf import settings import logging from django.core.exceptions import ObjectDoesNotExist from django.db import close_old_connections logger = logging.getLogger(__name__) @shared_task(bind=True) def mqtt_client_task(self, device_client_id): from iot.models import Device try: device = Device.objects.get(client_id=device_client_id) topic = device.topic except ObjectDoesNotExist as e: logger.error(f"Device not found: {device_client_id}") return def on_connect(client, userdata, flags, rc): nonlocal mqtt_client_instance if rc == 0: logger.info("Connected to MQTT Broker!") else: logger.error("Failed to connect, return code %d", rc) client.subscribe(topic) def on_message(client, userdata, msg): logger.info(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic") channel_layer = get_channel_layer() sync.async_to_sync(channel_layer.group_send)( f"{device.id}", {"type": "device.message", "message": msg.payload.decode()} ) mqtt_client_instance = mqtt_client_module.Client(device_client_id) mqtt_client_instance.on_connect = on_connect mqtt_client_instance.on_message = on_message try: mqtt_client_instance.connect( settings.MQTT_HOST, settings.MQTT_PORT, settings.MQTT_KEEPALIVE ) mqtt_client_instance.loop_start() except Exception as e: logger.error(f"Failed to connect to MQTT Broker: {e}") return finally: close_old_connections() Consumer.py # iot/channels/consumers.py … -
Do I need to always have a server running to make every command after starting an app?
I'am reading a book Python Crash Course 2nd Edition 3rd project, creating a django web app. It's said that to start an app I need to have the server running in other terminal tab. In the first tab: python manage.py runserver And in the second tab: python manage.py startapp learning_logs And after these manipulations I need to further do those: defining a model, activating a model, and making migration, etc. Do I need to have a server running to make other commands after starting an app? Or do I only need it running to start an app? So for example, do I need to have server running when further making a migration? python manage.py makemigrations learning_logs -
Django Rest Framework Async Error: "'async_generator' object is not iterable"
I am working on a Django Rest Framework project with asynchronous views. I have an endpoint for streaming responses, here's my code: from adrf.views import APIView as View class ChatAPI(View): permission_classes = [IsAuthenticated] async def process_dataframe(self, file_urls): data_frames = [] for file_url in file_urls: if file_url.endswith('.csv'): df = pd.read_csv(file_url) data_frames.append(df) elif file_url.endswith(('.xls', '.xlsx')): xls = pd.ExcelFile(file_url) sheet_names = xls.sheet_names for sheet_name in sheet_names: df = pd.read_excel(file_url, sheet_name=sheet_name) data_frames.append(df) return data_frames async def get_cached_data(self, cache_key): return cache.get(cache_key) async def check_file_extension(self, file_ext, csv_agent_type): print(f"Checking file extension: {file_ext}") return file_ext in csv_agent_type async def check_all_file_extensions(self, file_extensions, csv_agent_type): tasks = [self.check_file_extension( file_ext, csv_agent_type) for file_ext in file_extensions] print(tasks, "tasks") results = await asyncio.gather(*tasks) print(f"Results: {results}") return all(results) async def post(self, request, thread_id, user_id): try: a = time.time() print("Start===========") csv_agent_type = ['csv', 'xls', 'xlsx'] file_ids = request.GET.get('file_ids', []) message = request.data.get('message') chat_history = "" streamed_text = "" image_url = None # Use sync_to_async here generate_graph = await ais_graph_required(message) print(generate_graph, "....") print(thread_id, '==========thread_id') # Use sync_to_async here thread = await sync_to_async(Thread.objects.get)(id=thread_id) file_ids = await sync_to_async(lambda: list( thread.files.all().values_list('id', flat=True)))() file_types = await sync_to_async(lambda: list( User_Files_New.objects.filter(id__in=file_ids).values_list('file_name', flat=True)))() # Use sync_to_async here file_extensions = [file_name.split( ".")[-1] for file_name in file_types] cache_key = f"kibee_agent_cache_{user_id}_{thread_id}" print(cache_key) cached_data = await self.get_cached_data(cache_key) print("got … -
Module not found error with Django Channels
I'm completely new to using channels, but have tried two separate installations, and setups to just get a basic version of channels running and am encountering a small issue. I'm assuming I'm probably just missing a small thing, but I cannot figure it out. The error is at handshake error I'll also show the current file structure, as well as the files that I've actually made modifications to. asgi.py settings.py settings.py consumers.py consumers.py routing.py Originally, in settings.py having ASGI_APPLICATION set as mysite.asgi.application was resulting in an error so I changed that to mysite.settings and it seemed to work correctly when starting. However, on handshake now this issue occurs, so I feel like that could potentially contribute to it. I've tried on different projects and both encounter this issue. -
"Why is the table in my PostgreSQL database hosted in Azure being dropped automatically?"
I have backend in Django and my postgresql database hosted in azure. There is one table named "devicedata" got dropped from database automatically two times yesterday. All the other tables are working fine. What might be the reason ?. Is it postgres related or azure ? I have no idea. Please help me out. I had to delete all the tables and migrate to create all the table in Postgres including devicedata table. -
django-how to upload image using ImageField in a model form?
My form doesn't save the uploaded image in the path given, my code: models.py: class MyClass(models.Model): user = models.OneToOneField(SomeClass, on_delete=models.CASCADE) address_line_1 = models.CharField(blank=True, max_length=100) address_line_2 = models.CharField(blank=True, max_length=100) profile_picture = models.ImageField(blank=True, upload_to='static/zzz/xxx/') forms.py class edit_profile_form(forms.Form): profile_picture = forms.ImageField(label='Avatar',widget=forms.FileInput( attrs={ 'class': 'form-control input_data', 'placeholder': 'Upload',})) views.py def validate_edit_profile(request): template = loader.get_template('account/edit_.html') user_form = edit_profile_form(request.POST,request.FILES) userprofile = EcomCustomerProfile.objects.get(user_id=request.user.id) #if user submit if request.POST: if user_form.is_valid(): # get the data first_name = user_form.cleaned_data['first_name'] last_name = user_form.cleaned_data['last_name'] phone = user_form.cleaned_data['phone'] profile_picture = user_form.cleaned_data['profile_picture'] #change db get_user = EcomCustomer.objects.get(id = request.user.id) get_user.first_name = first_name get_user.last_name = last_name get_user.phone = phone get_user.profile_picture = profile_picture user_form.save() get_user.save() return HttpResponse(template.render({'userprofile':userprofile}, request)) I'm using two forms: one for text, the other for uploading the image. But it doesn't upload anything. What's the problem ? -
Can you explain me how to deploy a django website
I need a good explanation in step by step in how to deploy my django website online. I tried github at first but thn i understood that github doesn't work that way and then I tried PythonAnywhere but I don't know the proper way to make a deployment so I need a help in that. -
How should I serve my API? (authentication without password)
My question on itself isn't a problem in coding, instead I'm having doubts in the design of the user authentication of my API. Sorry if this isn't a question fit for stack overflow I'm developing an API in Django that serves HTML templates. It's going to be served to pages, each one has a set of users. I was planning in following the design described here: Why and when to use API keys So basically, each page will have its own API key, and in order for the users to use the API, the page will request a temporary token for the user. My question is, how could I generate the temporary tokens? Is there a library that deal with this? I had no luck searching. -
Django doesn't send email
I encountered an issue where Django is not sending emails to the specified email address. I would greatly appreciate your assistance. views.py def register(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() user.is_active = False user.save() current_site = get_current_site(request) subject = 'Account verification email' message = render_to_string('account/registration/email-verification.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': user_tokenizer_generate.make_token(user), }) print(message) user.email_user(subject=subject, message=message) return redirect('email-verification-sent') context = {'form':form} return render(request, 'account/registration/register.html', context=context) def email_verification(request, uidb64, token): unique_id = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=unique_id) if user and user_tokenizer_generate.check_token(user, token): user.is_active = True user.save() return redirect('email-verification-success') else: return redirect('email-verification-failed') token.py from django.contrib.auth.tokens import PasswordResetTokenGenerator class UserVerificationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): user_id = str(user.pk) ts = str(timestamp) is_active = str(user.is_active) return f"{user_id}{ts}{is_active}" user_tokenizer_generate = UserVerificationTokenGenerator() settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_USE_TLS = 'True' EMAIL_HOST_USER = 'XXX@gmail.com' EMAIL_HOST_PASSWORD = 'XXX' EMAIL_HOST_USER and EMAIL_HOST_PASSWORD are correct I have already tried using SSL instead of TLS, disabling two-factor authentication, and removing the line 'EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' -
Django rest how to show hierarchical data in api response
I am getting the category id for GET request but I want to show text in hierarchical structure like child1 -> child -> child3 my expected response will be look like this { 'category': 'child1 -> child -> child3' } now getting response like this { 'category': 1 } somethings look like that my model where it show category name on hierarchical order my category_model class Product_category(models.Model): domain = models.CharField(max_length=250) parent_category = models.ForeignKey('self',on_delete=models.CASCADE,null=True, blank=True) category_name = models.CharField(max_length=200,null=True,blank=True,) category_icon = models.ImageField(upload_to=dynamic_icon_upload_path,blank=True,null=True) def get_hierarchical_name(self): if self.parent_category: return f"{self.parent_category.get_hierarchical_name()}->{self.category_name}" else: return f"{self.category_name}" def __str__(self): return self.get_hierarchical_name() my product model class Product(models.Model): title = models.CharField(max_length=200,blank=True,null=True) category = models.ForeignKey(Product_category,blank=True,null=True,on_delete=models.CASCADE) my serilizer class ParentProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['category',...others product fields] see the screenshot where right now I am getting id instated for hierarchical text -
Django import problem, cant import myapp but i have installed it in setings
I'm working on a Django project and encountering an ImportError when trying to import a function from my app into the urls.py file. Despite the function being defined and the app added to INSTALLED_APPS, Django cannot seem to locate the function. Project Structure: myproject/ manage.py dictionarapicol/ init.py settings.py urls.py asgi.py wsgi.py statics/ find.js myapp/ migrations/ __init__.py templates/ base.htm index.html __init__.py text_processing.py admin.py apps.py models.py tests.py views.py urls.py myapp/urls.py: from django.urls import path from myapp import views from .text_processing import process_text urlpatterns = [ path('', views.home, name='index'), path('contact/', views.contact, name='contact'), path('stiri_apicole/', views.login, name='stiri_apicole'), path('text_processing/', process_text, name='text_processing'), ] text_processing.py from django.http import JsonResponse import json from nltk.stem.snowball import SnowballStemmer import stanza import spacy_stanza from rowordnet import RoWordNet # Load dictionary data with open('static\dictionary.json', 'r', encoding='utf-8') as file: dictionary_data = json.load(file) # Initialize NLTK, spaCy, Stanza, andin stall RoWordNet stemmer = SnowballStemmer("romanian") nlp = spacy_stanza.load_pipeline('ro') import rowordnet as rwn wn = RoWordNet() def process_text(request): text = request.GET.get('text', '') stemmed_text = stemmer.stem(text) doc = nlp(text) lemmatized_text = ' '.join([token.lemma_ for token in doc]) synset_ids = wn.synsets(literal=text) synsets = [wn.synset(synset_id).definition for synset_id in synset_ids] return JsonResponse({ 'stemmed_text': stemmed_text, 'lemmatized_text': lemmatized_text, 'RoWordNet_synsets': synsets }) views.py from django.shortcuts import render # Create your views here. def home(request): … -
How to add global ranking annotation to subsequent Django queries?
I have a Django model that looks like this: class LeaderboardScore(models.Model): score = models.FloatField() player_account = models.ForeignKey(PlayerAccount, on_delete=models.CASCADE) timestamp = models.DateTimeField() This represents top scores in a game. The scores are ranked by score descending and timestamp ascending, so if two scores are the same, the earliest score is ranked higher. Every time I do a query on the leaderboards, I'd like to include the global ranking of each instance in the query result. I can do that successfully when I'm querying all the scores like so: lq = LeaderboardScore.objects.filter(leaderboard__id=1).annotate( rank=Window( expression=DenseRank(), order_by=[F('score').desc(), F('timestamp').asc()] ) ) This will correctly at a rank field with the ranking. But if I take the above query and filter it by player_account like so: # rank will be 1, but should be the global ranking lq.filter(player_account__id=123)[0].rank then the ranking resets so that the first item in the query has the rank of 1, even though its global rank should be different. How do I preserve the global ranking? -
¿How can I download a file on django clicking on a widget?
I have a django project consist in different forms with different fields. Some of them are filefield where I upload files to media based on this class.I just want to make a widget to download the files, so when I am editing in change form if a file has been submit I can click on a button to download. Everytime I click on the button I made I received this error on console: "Not allowed to load local resource:" followed by my local root something like file:///C:/proyectos/etc My code is too extensive but I will try to show you most of them: Models.py (this class is to upload filefields) class CustomStorage(FileSystemStorage): # Almacenamiento nuevo en media def __init__(self, *args, **kwargs): super().__init__(location=os.path.join(settings.BASE_DIR, 'media','companies'), *args, **kwargs) def submission_directory_path(instance, filename): # Obtener el nombre comercial de la compañía y el ID del cliente company_name = slugify(instance.client.company.comercial_name) client_data = f"{instance.client.id}_{slugify(instance.client.name)}_{instance.type_submission.name}" # Construir la ruta del directorio directory_path = os.path.join(company_name, client_data) # Devolver la ruta completa del archivo return os.path.join(directory_path, filename) Urls.py urlpatterns = [ path('admin/', admin.site.urls), #ENDPOINTS path('client-details/<uuid:client_id>/', views.get_contact_details, name='client-details'), path('panel/submission/<uuid:submission_id>/change/cancel', views.cancel_submission, name='cancel_submission'), path('panel/submission/<uuid:submission_id>/change/no-apply', views.no_apply_submission, name='no_apply_submission'), # Ir a pantalla de activación de cuenta path('<str:name>/<str:uidb64>/<str:token>/', views.account_activation, name='account_activation'), path('panel/submission/<uuid:submission_id>/download/<str:file_path>/', views.download_file, name='download_file'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) … -
How to remove images from MEDIA_ROOT by using "Clear" in Admin panel for ImageField in Django?
I am trying to find the way to remove images from MEDIA_ROOT when I'am using "Clear" in Admin panel. Image that shows the checkbox I want to use When I choice "Clear" option, it removes link to image from database but the image is still in MEDIA_ROOT. It there a way to change its behavior? I tried to look Django documentation and googling but I didn't find anything. -
How can I run a kafka consumer in a django project so that messages will passed to django project
I am running my kafka consumer (from the confluent_kafka library) in a separate django management command. (I did this because I couldn't find a way of running a kafka consumer within the runserver process in django without blocking up the runserver process. If there is a better way of doing this I would love to hear suggestions) My projects requirements are: djnago rest api project will receive kafka message for designated topic project will create an instance of model1. creation of model1 will propagate further actions/logic such as creating/updating other models + sending further kafka messages. My issue comes when designing logic to meet my requirements. Requirement 3 can be met using django signals and there is already code that implements these further actions/logic. My problem comes requirement 2 and a bit of 1. My consumer lives in a separate process from my server process so I need to a way of communicating the messages consumed to my server process. What would be the best way of doing this? Using a cache will require another process to read this cache for updates and that leaves me in the same situation as before. The fact that django code runs synchronously makes … -
Django can login but can't logout - 405 Method Not Allowed
When I try to login using http://127.0.0.1:8000/accounts/login/ it works fine and redirected and creates a sessionid, but when I try to logout using http://127.0.0.1:8000/accounts/logout/ it shows http error 405 and not deleting the sessionid Request URL: http://127.0.0.1:8000/accounts/logout/ Request Method: GET Status Code: 405 Method Not Allowed settings.py INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'app.apps.AppConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_URL = 'static/' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'upload' LOGIN_REDIRECT_URL = '/' urls.py urlpatterns = [ path('',include('app.urls')), path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) login.html <form method="POST" action="{% url 'login' %}" class="form"> {% csrf_token %} <center> <div class="logo f-logo"> <i class="fa-brands fa-blogger"></i> </div> <div class="inputs"> <div> <div class="search-bar s-active input"> {{form.username}} <div class="animated-search"> <i class="uil uil-envelope-alt"></i> </div> </div> <div class="search-bar s-active input"> {{form.password}} <div class="animated-search"> <i class="uil uil-key-skeleton"></i> </div> </div> </div> <button class="btn btn-primary rounded" type="submit">Login<span class="material-icons">arrow_right_alt</span></button> <p>Not have an account?<a href="signup.html">Sign up</a></p> </div> </center> </form> logged_out.html {% extends 'base.html' %} {% block title %} Blog | Logout {% endblock title %} {% block content %} <div class="container"> <center> <div class="typo"> <p>You have been successfully logged out. <a href="{% url 'login' %}">Login again</a> </p> </div> </center> </div> {% … -
How to Export Book Data for a Specific Genre in CSV or JSON Format
views.py class ExportBooksAPIView(APIView): permission_classes = [IsAuthenticated] def get_queryset(self, genre_id): try: genre = Genre.objects.get(id=genre_id) books = genre.books.all() return books except Genre.DoesNotExist: return None def get(self, request): genre_id = request.GET.get('genre_id') if not genre_id: return Response("Genre ID not specified in the request.", status=status.HTTP_400_BAD_REQUEST) books = self.get_queryset(genre_id) if not books: return Response(f"Genre with ID '{genre_id}' not found.", status=status.HTTP_404_NOT_FOUND) serializer = BookSerializer(books, many=True) csv_data = self.serialize_to_csv(serializer.data) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = f'attachment; filename="data_books.csv"' response.write(csv_data) return response def serialize_to_csv(self, data): csv_buffer = io.StringIO() csv_writer = csv.writer(csv_buffer) header_row = ['Book Name', 'Author Name', 'Number of Pages'] csv_writer.writerow(header_row) for book in data: csv_writer.writerow([book.get('name', ''), book.get('author', {}).get('name', ''), book.get('pages', '')]) return csv_buffer.getvalue() core/urls.py py path('export-books/', ExportBooksAPIView.as_view(), name='export_books'), ] project/urls.py path('genre/',include('core.urls')), Postman export all the data for a specific genre in a structured format (e.g., CSV or JSON). But i am getting { "detail": "Not found." } i should get all the details of all the books that comes under specific genre -
Add Social Login to my current Django project
I have an email/password signup/login flow in my Django project. I want to add LinkedIn login flow to my project. I would like to use the current User DB table for LinkedIn login. What I want is when a user logs in using LinkedIn, I want to get the user information and save it to the current User DB table, login and redirect to the home page. Please help me! The important thing is that when a user logs in using LinkedIn, I want to customize the user data in the backend and store it in the current User DB table. -
Django with SPA?
First of all, greetings to everyone, I want to convert my project from MPA to SPA in Django, but I can't get the structure in my head. In the area you see in the photo, I want to redirect the base.html (or any field, for example login.html, register...) field to the app field in index.html during a user's first login to the site. html...) field in index.html during the user's first login, but I want to make it workable with the back and forth buttons in the web browser and manual input of the url. The .html pages are returned as a response as a string on the django side and I get the data with fetch. My problem here is that if the person manually enters the url on the login.html page, I redirect the login.html and the index.html is passed. If I first fetch the index.html with the load event and then fetch the login.html, I instantly display the non-css version and then it is fixed. Since the beforeunload event works without fetching the index.html, the DOM cannot find my app field because I did not redirect the index.html. If you have a constructive solution, I would appreciate … -
WSGI application 'CMS.wsgi.application' could not be loaded; Error importing module
enter image description here Above is my django project structure and i have two django apps. I am using session variable to store username when user is logged. but i am getting error while using session variable. raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: WSGI application 'CMS.wsgi.application' could not be loaded; Error importing module. wsgi.py ---> main project file import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'CMS.settings') application = get_wsgi_application() authentication/views.py def login(request): error_message = None if request.method == 'POST': username_value = request.POST.get('username') password_value = request.POST.get('password') try: user = SignUp.objects.get(username=username_value) # Check if the provided password matches the hashed password in the database if check_password(password_value, user.password): # Successful login response = HttpResponse("Login successful!") request.session['username'] = user.username return redirect('home') else: error_message = "Invalid username or password" except DoesNotExist: error_message = "User does not exist" return render(request, 'authentication/login.html', {'error_message': error_message}) settings.py from pathlib import Path from mongoengine import connect # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure--#u^llr^ji5f70u-vm-99-59(m4010v_$a%bga2-puf2-d%l*3' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', … -
django base.html with htmx
So question is i got my base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- styles --> </head> <body> {% include 'includes/sidebar.html' %} <div id="main"> {% block content %} {% endblock content %} </div> {% block js %} <!-- block where js is located --> {% endblock js%} </body> dashboard.html {% extends "base.html" %} {% load i18n %} {% block content %} <!--my content--> {% endblock content %} and my sidebar.html % load static %} {% load i18n %} {% block content %} <div id="sidebar" class="active"> <div class="sidebar-wrapper active"> <div class="sidebar-header"> <div class="d-flex justify-content-between"> <div class="toggler"> <a href="#" class="sidebar-hide d-xl-none d-block"><i class="bi bi-x bi-middle"></i></a> </div> </div> </div> <div class="sidebar-menu"> <ul class="menu"> <li class="sidebar-item has-sub"> <a href="#" class='sidebar-link'> <i class="bi bi-grid-fill"></i> <span>Dashboard</span> </a> <ul class="submenu"> <li class="submenu-item "> {% url "dashboard:dashboard" as dashboard %} <a href="{{ dashboard }}" hx-get="{{ dashboard}}" hx-target="#main" hx-push-url="true" hx-indicator = "#content-loader" hx-on="htmx:beforeRequest: event.detail.target.innerHTML = ''" class='submenu-link'> <i class="bi bi-grid-fill"></i> <span>{% trans 'Dashboard' %}</span> </a> </li> </ul> <!-- else code --> So question is when user redirect from login page to dashboard, if im not extends from base.html it not shown any sidebar and its logical, but with htmlx when im extends base.html template this render …