Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
correct websocket structure for django chat app
I am building the chat functionality on my app with django-channels and redis, and I am new to websocket. after collecting enough infomation, here's my sketch of the application. basically there are two types of chat: team chat user chat they are all integrited into one chat friends view. for team chat, such a team with pk=8, the user connects to let route = `ws://${window.location.host}/ws/team/${team.pk}/` to send and receive messages. and if the user is not in the team, the connection will be rejected. this means if you joined to team8, team12, team13... you be connected to ws8, ws12, ws13... for user app, establish ws connection between two user: for example, ws1 is used for user1 to receive message, which if user2 want to send message to user1, user2 must connect to the socket. this means if you have n contacts, it will be n ws connections. the chat consumer only applies in chat view, and I have a notification app uses ws and is implemented throughout the application. user1 connect to note1 to receive system infomation. this means if n user is online, n note socket connections will be established. soon I noticed the performance and number limit issue, … -
Django M2M through table delete and save methods
I have a many to many relation between two tables and relation is saved in a through table: class Book(models.Model): likes = models.ManyToManyField(User, through=BookLike) class User(models.Model): ... class BookLike(models.Model): user = models.ForeignKey(User) book = models.ForeignKey(Book) When a user likes or dislikes a book I want to carry out some actions like increasing/decreasing the like count of book for example. I tried overwriting save and delete functions of BookLike but they are not called when I call book_instance.likes.remove(user) and book_instance.likes.add(user). How can I achieve this? -
How to save the number of child paragraph in Django Model?
im beginner in django. Here im trying to save number like as MS word headings 1,2,3 levels. This model would save each paragraph items with numbers For example if there is no uplevel, numbers should be 1, 2, 3 else 1.1, 1.2 or 1.1.1, 1.1.2 But i can't do this. Please help to me. models class Document (models.Model): drafttype=models.ForeignKey(DraftType, on_delete=models.CASCADE,verbose_name='GroupItem') draft=models.CharField(max_length=500) number=models.CharField(max_length=500) uplevel=models.ForeignKey('self', on_delete=models.CASCADE, related_name='+') def __str__(self): return self.title def get_absolute_url(self): return reverse('doc-detail', args=[str(self.id)]) def get_update_url(self): return '/doc/update/{}'.format(self.id) def get_delete_url(self): return '/doc/del/{}'.format(self.id) def save(self): if self.uplevel: counter=Document.objects.filter(uplevel=self.uplevel) # increasing by 1 , should be 1.1, or 1.1.1 self.number=counter.number+'.'+counter.count() else: # getting last number and next one should be 2 or 3 counter=Document.objects.all().order_by('number').last() self.number=counter.number+1 Im tried separated model as like below. But i think this is not solution Models class Buleg (Authors): norm=models.ForeignKey(Norm, on_delete=models.CASCADE, verbose_name='Төсөл') text = models.TextField(verbose_name='Бүлэг') class Heseg (Authors): norm=models.ForeignKey(Buleg, on_delete=models.CASCADE, verbose_name='Бүлэг') text = models.TextField(verbose_name='Хэсэг') class Zaalt (Authors): norm=models.ForeignKey(Heseg, on_delete=models.CASCADE, verbose_name='Хэсэг') text = models.TextField(verbose_name='Заалт') -
How to change page content when changing in db Django
I am trying create notifications system in my site. Button with notifications situated on the ever page, this is make by using context processor. But I want that AJAX work, when update my model Notifications Now, I am make AJAX request which work ever 5 seconds, this request checking DB and change content on the page. How this make? If need, I can attach my code. -
NoReverseMatch at / Reverse for 'home' not found. 'home' is not a valid view function or pattern name
I'm working on my Django blog. I was working on a registration form, everything it was working until I tested it and redirection was not working properly. Trying to fix errors, I got this message django.urls.exceptions.NoReverseMatch: Reverse for 'home' not found. 'home' is not a valid view function or pattern name. blog/urls.py from . import views from django.urls import path app_name = 'my_blog' urlpatterns = [ path('', views.home, name='home'), path('post/<slug:slug>/', views.post_detail, name='post_detail'), path('category/<slug:slug>/', views.category_detail, name='category_detail'), path('register/', views.register_request, name='register'), path('login/', views.login_request, name='login'), ] views.py def register_request(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() login(request, user) messages.success(request, "Registration successful." ) return redirect("my_blog:homepage") messages.error(request, "Unsuccessful registration. Invalid information.") form = NewUserForm() return render (request=request, template_name="register.html", context={"register_form":form}) def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}.") return redirect("my_blog:homepage") else: messages.error(request,"Invalid username or password.") else: messages.error(request,"Invalid username or password.") form = AuthenticationForm() return render(request=request, template_name="login.html", context={"login_form":form}) In base.html I used "{% url 'home' %}", and now this is error when I try to reload page, I have no idea why this is … -
How are adapters used in django-allauth?
Hi everyone this is my first post on StackOverflow. I'm building a web application using Django and I would like to: Only allow people that have a Google account to sign up / log in Only people with a specific email domain can access the web app and their UserModel will be saved to the database. I started with coding a middleware, and it worked, I managed to log out those that tried to log in with a Google account associated with a not allowed email BUT they were saved in the database User model. I then found out about Adapters (for django-allauth) and I saw I could use them to achieve my goals but in the documentation, they are only cited once. I then started looking at the GitHub repo and found some more info but I'm still not able to implement this myself. Can anyone help me? Btw this is my code so far: Disclaimer: This code does not work, it's not even called when I try to test it. ( I tried to log in with a wrong Google account to see it it gets triggered but nothing appened) main_app/adapters.py from allauth.socialaccount.adapter import DefaultSocialAccountAdapter from allauth.account.adapter import … -
Django NoReverseMatch at /account/register/
I am new in Django, trying to get an activation email but can't figure out what's the problem. Reverse for 'activate' with keyword arguments '{'uidb64': 'MTU', 'token': 'bhp5py-6f0679ec02bc2863df780ea30d2984da'}' not found. 1 pattern(s) tried: ['account/activate/(?P[-a-zA-Z0-9_]+)/(?P[-a-zA-Z0-9_]+)\Z'] views.py def account_register(request): if request.method == 'POST': registraionForm = RegistraionForm(request.POST) if registraionForm.is_valid(): user = registraionForm.save(commit=False) user.email = registraionForm.cleaned_data['email'] user.set_password(registraionForm.cleaned_data['password']) user.is_active = False user.save() # setup email current_site = get_current_site(request) subject = 'Activate your account' message = render_to_string('account/registration/account_activation_email.html',{ 'user': user, 'domain':current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) user.email_user(subject=subject, message=message) return HttpResponse('Successful') else: registraionForm = RegistraionForm() return render(request, 'account/registration/register.html', {'form':registraionForm}) def account_activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = UserBase.objects.get(pk=uid) except: pass if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return redirect('account:dashboard') else: return render(request, 'account/registraion/activation_invalid.html') urls.py from django.urls import path from . import views app_name = 'account' urlpatterns = [ path('register/', views.account_register, name='register'), path('activate/<slug:uid64>/<slug:token>', views.account_activate, name='activate'), path('dashboard/', views.account_dashboard, name='dashboard'), ] token.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( text_type(user.pk) + text_type(timestamp) + text_type(user.is_active) ) account_activation_token = AccountActivationTokenGenerator() html {% autoescape off %} Hi {{ user.user_name }}, Your account has successfully created. Please click below link to activate your account http://{{ domain }}{% url … -
Page not found at /register/... Raised by: my_blog.views.post_detail... Django
I'm working on Django blog, and I'm working on register form. I got error Page not found at /register/ like you can see on image. But it say that error was raised by post_detail - Raised by: my_blog.views.post_detail This is register.html {% extends "base.html" %} {% load static %} {% block content %} {% load crispy_forms_tags %} <!--Register--> <div class="container py-5"> <h1>Register</h1> <form method="POST"> {% csrf_token %} {{ register_form|crispy }} <button class="btn btn-primary" type="submit">Register</button> </form> <p class="text-center">If you already have an account, <a href="/login">login</a> instead.</p> </div> {% endblock %} Views.py def register_request(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() login(request, user) messages.success(request, "Registration successful." ) return redirect("main:homepage") messages.error(request, "Unsuccessful registration. Invalid information.") form = NewUserForm() return render (request=request, template_name="register.html", context={"register_form":form}) def post_detail(request, slug): latest_posts = Post.objects.filter(created_at__lte=timezone.now()).order_by('created_at')[:9] post = get_object_or_404(Post, slug=slug) context = {'post': post, 'latest_posts': latest_posts} return render(request, 'post_detail.html', context) blog/urls.py from . import views from django.urls import path urlpatterns = [ path('', views.home, name='home'), path('<slug:slug>/', views.post_detail, name='post_detail'), path('category/<slug:slug>/', views.category_detail, name='category_detail'), path('register/', views.register_request, name='register'), ] forms.py class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() … -
I'm getting a 403 Forbidden response when using axios instance in react to access my api endpoint in Django rest framework
I am working on a blog project, following a certain tutorial, using django 4.1.4, DRF-3.14, React 18.2, and using drf-social-oauth2 1.2.1 module for social logins When I use postman or that DRF API Interface to make request to the api everything is working fine, I can do all the request when authenticated but when I use exios instance I keep getting the 403 Forbidden error. Here is axios file: import axios from 'axios'; const baseURL = 'http://127.0.0.1:8000/api/'; const token = localStorage.getItem('access_token') console.log(token); const axiosInstance = axios.create({ baseURL: baseURL, timeout: 5000, headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'multipart/form-data', accept: 'application/json', }, }); axiosInstance.interceptors.response.use( (response) => { return response; }, async function (error) { const originalRequest = error.config; if (typeof error.response === 'undefined') { alert( 'A server/network error occurred. ' + 'Looks like CORS might be the problem. ' + 'Sorry about this - we will get it fixed shortly.' ); return Promise.reject(error); } if ( error.response.status === 401 && originalRequest.url === baseURL + 'token/refresh/' ) { window.location.href = '/login/'; return Promise.reject(error); } if ( error.response.data.code === 'token_not_valid' && error.response.status === 401 && error.response.statusText === 'Unauthorized' ) { const refreshToken = localStorage.getItem('refresh_token'); if (refreshToken) { const tokenParts = JSON.parse(atob(refreshToken.split('.')[1])); // exp date … -
Django DRF - Only allow access to view if user is at a specific physical location
I'm working on a game (react front-end, DRF back-end) that requires users to visit physical locations to win digital prizes. I want to make sure the participants physically visit the locations and don't just make a request from their home to the prize endpoint using curl or postman. What is the best strategy for this? Haven't tried anything yet; not sure where to start. -
Why is my Django rest framework api returning an empty list?
Hello I am working on an Django Rest Framework api and one of the views is returning an empty list. here's my view: @api_view(['GET']) def post_search(request): form = SearchForm() query = None results = [] if request.method == 'GET': if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] results = Paper.objects.annotate( search=SearchVector('abstract', 'title'),).filter(search=query) serializer = PaperSerializer(results, many=True) return Response(serializer.data) here is the form: class SearchForm(forms.Form): query = forms.CharField() and here are my urls: path('search/', views.post_search, name='post_search'), So on the shell I ran: Paper.objects.annotate(search=SearchVector('abstract', 'title'),).filter(search='Type') and I got the results I wanted but when do this: import requests url = 'http://127.0.0.1:8000/api/search/?search=Type' re = requests.get(url) re.json # -> [] # or import json json.loads(re) # ->raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not Response Any help will be appreciated; thanks -
How do I "flatten" a nested serializer in DRF?
We have a nested serializer that we would like to "flatten". But I'm not having much luck finding how to achieve this in the docs. Here is the current output. { "user_inventory": "UOHvaxFa11R5Z0bPYuihP0RKocn2", "quantity": 1, "player": { "card_id": "c69c0808328fdc3e3f3ee8b9b7d4a7f8", "game": "MLB The Show 22", "name": "Jesus Tinoco", "all_positions": [ "CP" ] } } Here is what I'd like: { "user_inventory": "UOHvaxFa11R5Z0bPYuihP0RKocn2", "quantity": 1, "card_id": "c69c0808328fdc3e3f3ee8b9b7d4a7f8", "game": "MLB The Show 22", "name": "Jesus Tinoco", "all_positions": [ "CP" ] } Here is how the serializers are setup: class PlayerProfileSerializer(serializers.ModelSerializer): class Meta: model = PlayerProfile fields = ( 'card_id', 'game', 'name', 'all_positions', ) class UserInventoryItemSerializer(serializers.ModelSerializer): player = PlayerProfileSerializer() class Meta: model = UserInventoryItem fields = ( 'user_inventory', 'quantity', 'player', ) Here is the view: class OwnedInventoryView(viewsets.ModelViewSet): serializer_class = UserInventoryItemSerializer filterset_class = UserInventoryItemFilter def get_queryset(self): order_by = self.request.query_params.get('order_by', '') if order_by: order_by_name = order_by.split(' ')[1] order_by_sign = order_by.split(' ')[0] order_by_sign = '' if order_by_sign == 'asc' else '-' return UserInventoryItem.objects.filter(user_inventory=self.kwargs['user_inventory_pk']).order_by(order_by_sign + order_by_name) return UserInventoryItem.objects.filter(user_inventory=self.kwargs['user_inventory_pk']) -
Python - Django - Form fields not showing on HTML page
I am learning Django and am trying to set up a simple form HTML with form fields which I can send via POST method. However, if I load HTML page the fields are not visible The HTML page is create.html {% extends 'main/base.html' %} {% block title %} Create a task {% endblock %} {% block content %} <h1>Create a task</h1> <form method="post"> {% csrf_token %} {{ form.title }} {{ form.task }} <button type="submit" class="btn btn-success">Add</button> <span>{{ error }}</span> </form> {% endblock %} <input type="text" placeholder="Enter name" class="form-control"><br> <textarea placeholder="Enter description" class="form-control"></textarea><br> My forms.py file is as follows: from .models import Task from django.forms import ModelForm, TextInput, Textarea class TaskForm(ModelForm): class Meta: model = Task fields = ["title", "task"] widgets = { "title": TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter name' }), "task": Textarea(attrs={ 'class': 'form-control', 'placeholder': 'Enter description' }), } and views.py is as this: from django.shortcuts import render, redirect from .models import Task from .forms import TaskForm def index(request): tasks = Task.objects.order_by('id') return render(request, 'main/index.html', {'title': 'Main page of this website', 'tasks': tasks}) def about(request): return render(request, "main/about.html") def create(request): error = '' if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() redirect('home') else: error = 'The form has … -
django.db.utils.IntegrityError: null value in column "id" violates not-null constraint superuser
I'm writing a site on django. And I ran into a problem, when I want to add a superuser, the following error occurs: django.db.utils.IntegrityError: null value in column "id" violates not-null constraint DETAIL: Failing row contains (pbkdf2_sha256$390000$gajFrJerChyUlrAwZWzfkS$gmZ4GQTavfwqlV5jaPl+..., null, t, admin_dima, , , t, t, 2023-01-07 22:12:28. 743122+00, null, , dima1@gmail.com, , ). I think it has something to do with the fact that I'm using a model that inherits from AbstractUser Here is my model: class JobseekerRegisterInfo(AbstractUser): id = models.IntegerField(primary_key=True) phone_number = PhoneNumberField() email = models.EmailField(unique=True) full_name = models.CharField(max_length=120) hashed_password = models.CharField(max_length=200) def __str__(self): return self.full_name And I commented for a while in the settings.py file and the main urls.py file the link to the admin page, and before that, how to create a superuser, I uncommented it again -
DatabaseError when trying to print all flatpages in Django template
I have a Django app that I have just added flatpages to. The issue I am running into is printing out the list of all flatpages that I have created. The reason I want to do this is so that I can print them out in a header navigation template so that they will appear automatically as I create/remove them. Else I would manually have to update the html file to add a new link. I have this added in my views.py urlpatterns += [ re_path(r'^(?P<url>.*/)$', views.flatpage), ] Right now I am using the flatpages default template as my test file. Error: DatabaseError at /aaa/ No exception message supplied Request Method: GET Request URL: http://214.191.20.123/aaa/ Django Version: 3.2 Exception Type: DatabaseError Exception Location: /home/django/parser/venv/lib/python3.8/site-packages/djongo/cursor.py, line 59, in execute Python Executable: /home/django/parser/venv/bin/python Python Version: 3.8.10 Python Path: ['/home/django/parser', '/home/django/parser/venv/bin', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/django/parser/venv/lib/python3.8/site-packages'] Server time: Sat, 07 Jan 2023 22:01:23 +0000 Error: Environment: Request Method: GET Request URL: http://214.191.20.123/aaa/ Django Version: 3.2 Python Version: 3.8.10 Installed Applications: ['adobeparser', 'cbs_parser', 'segment_parser', 'parsers', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages'] Installed 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', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware'] Template error: In template /home/django/parser/parsers/templates/flatpages/default.html, error at line 25 (Could not … -
django-admin startproject error (version conflict?)
When I run "django-admin startproject myproject" I get the following error: Traceback (most recent call last): File "/System/Volumes/Data/Library/Frameworks/Python.framework/Versions/3.11/bin/django-admin", line 5, in from django.core.management import execute_from_command_line File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/init.py", line 17, in from django.conf import settings File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/conf/init.py", line 14, in from pathlib import Path File "/opt/anaconda3/lib/python3.9/site-packages/pathlib.py", line 10, in from collections import Sequence ImportError: cannot import name 'Sequence' from 'collections' (/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/collections/init.py) I'm assuming the problem is due to problems involving multiple locations and versions. Does that seem to be the correct assumption? Suggestions for how to fix this? -
Django-Stripe how to get the product data in the checkout session
I am still new to django and I am working on a django website whereby users can purchase goods and pay through Stripe. I have been following a tutorial and the tutorial has managed to make a payment but the problem is that the figures they are using are hard coded. My issue currently is how to get the values of what I am selling from the database. Here is my views.py: def bookService(request, gig_id): gig = Gig.objects.get(gig_id = gig_id) context = {'gig':gig} return render(request, 'payments/book.html', context) @csrf_exempt def create_checkout_session(request): #Updated- creating Order object order=Order(email=" ",paid="False",amount=0,description=" ", buyer=request.user.profile) order.save() session = stripe.checkout.Session.create( client_reference_id=request.user.id if request.user.is_authenticated else None, payment_method_types=['card'], line_items=[{ 'price_data': { 'currency': 'usd', 'product_data': { 'name': 'Intro to Django Course', }, 'unit_amount': 10000, }, 'quantity': 1, }], #Update - passing order ID in checkout to update the order object in webhook metadata={ "order_id":order.id }, mode='payment', success_url=YOUR_DOMAIN + '/success.html', cancel_url=YOUR_DOMAIN + '/cancel.html', ) return JsonResponse({'id': session.id}) Here is the URLs file urlpatterns = [ path('seller/<str:gig_id>/', views.bookService, name='home'), path('create-checkout-session/', views.create_checkout_session, name='checkout'), path('success.html/', views.success,name='success'), path('cancel.html/', views.cancel,name='cancel'), ] And here is the template whereby I am viewing the details and also whereby the button that redirects users to pay is located: <script type="text/javascript"> // … -
How can I Render Data To Main Template In Other Extended View From Main Template?
First of all, hello everyone. I apologize to everyone for my bad English, I will try my best. I am making a video site, in this site there are three main views, they are single-video-view, index-view and main-view. All other views extends from main-view (%extends 'base/main.html' %). There is a sidebar that should appear on all pages. In this sidebar, the categories of pre-loaded videos should be listed. My urls.py: urlpatterns = [ path('',views.index,name="index"), path('main/',views.main,name="main"), path('video/<slug:slug>/',views.video,name="video"), #path('test/',views.category,name="setcategory"), path('apivideo/',views.apivideo,name="apivideo"), ] If I visit main.html directly working fine Single video view, categories not listing Index view, categories not listing View.py: def index(request): # q = request.GET.get('q') # if request.GET.get('q') != None: if 'q' in request.GET and request.GET['q']: page = request.GET.get('page', 1) q = request.GET['q'] videos = Video.objects.filter( Q(video_title__icontains=q) | Q(video_tags__icontains=q)) paginator = Paginator(videos, 24) videos = paginator.page(page) return render(request, 'base/index.html', {'videos': videos, 'q': q}) else: main(request) videos = Video.objects.all().order_by("-id") paginator = Paginator(videos, 24) page_number = request.GET.get('page') videos = paginator.get_page(page_number) return render(request, 'base/index.html', {'videos': videos}) def main(request): setcategory = [] category = Video.objects.values_list('video_tags', flat=True) for i in range(0, len(category)): for x in range(0, len(category[i])): categorycount = Video.objects.filter(Q(video_title__icontains=str( category[i][x]).lower()) | Q(video_tags__icontains=str(category[i][x]).lower())).count() if (categorycount >= 10): print("if: " + str(categorycount)) setcategory.append(str(category[i][x]).lower()) else: print("else: " + … -
I can't run the command : python manage.py runserver
I can't run the command 'python manage.py reunserver' on my terminal. I dont know why, here is what the terminal shows me : enter image description here Can please someone help me ? I tried to execute the django dev server but it didn't worked. Normally, it show something like this : enter image description here -
Why are we inheriting here in django?
This is my first post here. I am a beginner in django and I am almost done reading through django for beginners by William S. Vincent. In chapter 8, he goes over the custom user model and creates the following code for the forms needed: from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = UserCreationForm.Meta.fields + ("age",) class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = UserChangeForm.Meta.fields My question is why are we using class Meta here and why is the first class Meta inheriting from "UserCreationForm", but the second class Meta doesn't. Thanks! -
sort feed by engagement count django
I would like to sort my feed containing image posts by the engagement (number_of_dislikes + number_of_likes), so that the most popular post is on top. But I'm pretty unsure of how to do it. Please have a look at what I have so far and help me out. There are two main problems: one, I have the engagement-post in the html displayed in the same way as the like or dislike, which only reveals the number on click. I tried to change that by just displaying the engagement_count but it only showed the numbers of the posts I´ve clicked on before when the button was still there. How do I display an always counting number of engagement? secondly, i need to sort the feed by that count... thanks a lot. index.html (homepage) {% for post in posts %} <div class="bg-white shadow rounded-md -mx-2 lg:mx-0"> <!-- post header--> <div class="flex justify-between items-center px-4 py-3"> <div class="flex flex-1 items-center space-x-4"> <a href="#"> <div class="bg-gradient-to-tr from-yellow-600 to-pink-600 p-0.5 rounded-full"> <img src="{% static 'assets/images/avatars/user.png' %}" class="bg-gray-200 border border-white rounded-full w-8 h-8"> </div> </a> <span class="block capitalize font-semibold "><a href="/profile/{{ post.id }}">@{{ post.id }} </a></span> </div> <div> <a href="#"> <!-- <i class="icon-feather-more-horizontal text-2xl hover:bg-gray-200 rounded-full … -
Redirect user in django after form submission using JavaScript
Using JS to add some interactivity to the form and now would like to redirect the user to a different url and be able to do it dynamically. Using plain JS as of now, need ideas. Adding sample code below. book.addEventListener('submit', (e) => { e.preventDefault(); const submitButton = document.getElementById('book'); submitButton.disabled = true; submitButton.innerHTML = 'Booking...'; setTimeout(() => { submitButton.innerHTML = `<i class="fa-solid fa-check" style="color: white; text-align: center;"></i>`; }, 1000); // return user to profile page }); Not really sure what to try as I am new to using JavaScript. -
In Django's auth contrib module, how do I validate a token submitted from a reset password form?
I'm using Django 3.1 with its auth contrib module. I have an API-only application, in which I initiate a password reset using the following Django view class ResetPasswordView(SuccessMessageMixin, PasswordResetView): reset_password_template_name = 'templates/users/password_reset.html' email_template_name = 'users/password_reset_email.html' subject_template_name = 'users/password_reset_subject' success_message = "We've emailed you instructions for setting your password, " \ "if an account exists with the email you entered. You should receive them shortly." \ " If you don't receive an email, " \ "please make sure you've entered the address you registered with, and check your spam folder." success_url = reverse_lazy('users-home') @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): request.csrf_processing_done = True return super().dispatch(request, *args, **kwargs) def post(self, request, *args, **kwargs): email = json.loads(request.body).get('username') try: if User.objects.get(email=email).is_active: form = PasswordResetForm({'email': email}) print("form valid? %s" % form.is_valid()) if form.is_valid(): request = HttpRequest() request.META['SERVER_NAME'] = socket.gethostbyname('localhost') #'127.0.0.1' request.META['SERVER_PORT'] = 8000 # calling save() sends the email # check the form in the source code for the signature and defaults form.save(request=request, use_https=False, from_email="laredotornado@yahoo.com", email_template_name='../templates/users/password_reset_email.html') print("email: %s " % email) return super(ResetPasswordView, self).post(request, *args, **kwargs) except Exception as e: print("\n\nerror ...\n\n") print(e) # this for if the email is not in the db of the system return super(ResetPasswordView, self).post(request, *args, **kwargs) This generates an email … -
How to remove the folder structure generated when building multiple html entry points using Vite.js?
My current vite.config.js looks sorta of like this: export default defineConfig({ plugins: [react()], build: { assetsDir: './', rollupOptions: { input: { main: fileURLToPath(new URL('./src/html/main.html', import.meta.url)), mobile: fileURLToPath(new URL('./src/html/mobile.html', import.meta.url)), config: fileURLToPath(new URL('./src/html/config.html', import.meta.url)), }, output: { dir: 'dist', }, }, }, }); So my project's current folder structure for organization reasons is: src/ |- components |- hooks |- pages `- Config `- index.tsx `- Main `- index.tsx `- Mobile `- index.tsx |- html/ | `- config.html | `- main.html | `- mobile.html My build(dist) folder structure is: dist |- [...bunch of js files] | src/ |- html/ | `- config.html | `- main.html | `- mobile.html My ideal final folder structure goal would be: dist |- [...bunch of js files] |- config.html |- main.html |- mobile.html I know I can just re-structure the project folder structure by putting the HTML files outside the src folder, in the root folder. But I'm aiming at being organized. I know this is possible using Webpack and I couldn't figure out how to do it on Vite.js with HTML files. Any direction or help would be awesome. -
How to same place on page when redirecting to previous page
I was wondering if there is a way in django for when you click back to go to the previous page via a link or in my case an anchored link with in an img, for it to also end up in the same place as you click originally, in my case the image that is clicked in the first place. Page I click image to redirect: </head> <body> <header>{% include 'navbardesktop.html' %}</header> <div class="image-container"> <div class="image-post"> <a href="{% url 'gallery' %}" ><img class="photo-img" src="{{photo.image.url}}" /></a> <h2 class="photo-title">{{photo.image_title}}</h2> <p class="contact"> Interested in purchasing this as a print? Contact me for more information regarding price and sizes. </p> <a href="{% url 'contact' %}" class="btn btn-secondary" type="button" >Contact</a > <a href="{% url 'gallery' %}" class="btn btn-secondary" type="button" >Gallery</a > </div> </div> </body> </html> Page I want to redirect to: <body> <header>{% include 'navbardesktop.html' %}</header> <div class="container-gallery"> <div class="col-md-12" id="gallerygrid1"> <div class="row"> {% for photo in images %} <div class="col-md-4" id="gallerygrid2"> <a href="{% url 'viewimage' photo.slug %}" ><img class="gallery-thumbnail" src="{{photo.image.url}}" style="" /></a> </div> {% empty %} <h3>No Projects...</h3> {% endfor %} </div> </div> </div> </body> </html>