Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Auth email in Django
I am making my first app, which is a todolist app. I am trying to get users to register with email and login with it. This is the error that the debug shows me: ProgrammingError at /register/ no existe la relación «core_user» LINE 1: SELECT 1 AS "a" FROM "core_user" WHERE "core_user"."email" =... ^ Request Method: POST Request URL: http://127.0.0.1:8000/register/ Django Version: 5.0.2 Exception Type: ProgrammingError Exception Value: no existe la relación «core_user» LINE 1: SELECT 1 AS "a" FROM "core_user" WHERE "core_user"."email" =... My files have the following configuration models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField() complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Meta: ordering = ['complete'] views.py from django.shortcuts import render, redirect from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView, FormView from django.urls import reverse_lazy from django.contrib.auth.views import LoginView from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth import login from .models import Task from .forms import LoginForm, RegisterForm class CustomLoginView(LoginView): template_name = 'core/login.html' form_class = LoginForm redirect_authenticated_user = True def get_success_url(self): return reverse_lazy('task_list') class RegisterPage(FormView): template_name = 'core/register.html' form_class = RegisterForm … -
Django forms.ModelMultipleChoiceField appearance is different when an instance is passed to the form and when the form is empty
i have this ModelMultipleChoiceField, services = forms.ModelMultipleChoiceField( queryset=Services.objects.all(), widget=forms.SelectMultiple(attrs={'class': 'select2'}), required=False ) when the i display an empty form it appears like that: enter image description here but when i pass an instance to the form the field appears like that: enter image description here i want both to have the look of the first screenshot -
Troubleshooting Dynamic Image Updating and Color-Based Filtering in Django Product Html Page
I have created a hyperlink in html So, In product_detail_page.html: <div class="product-color"> <span>Color</span> {% for c in colors %} <div class="color-choose"> <a href="?colorID={{c.id}}" style="display: inline-block; width: 40px; height: 40px; background-color: {{c.code}}; border-radius: 50%; border: 2px solid #FFFFFF; cursor: pointer; float: left; margin-right: 10px; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.33);"> </a> </div> {% endfor %} </div> Now it is taking colors id (suppose if I click on red color it is taking {?colorID=1} in url) Now I created a view for this That if I Click in a color it will change the product Image So, In views.py def product_detail_view(request,pid): product=Product.objects.get(pid=pid) colors = Color.objects.all() sizes= Size.objects.all() p_image=product.p_images.all() products=Product.objects.filter(cagtegory=product.cagtegory) ColorID=request.GET.get('colorID') if ColorID: product=Product.objects.filter(color=ColorID) else: product=Product.objects.all() context={ "p":product, "p_image":p_image, 'colors': colors, 'sizes': sizes, 'products': products, } return render(request,"core/product_detail.html",context) and I created this models in models.py class Product(models.Model): pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) cagtegory=models.ForeignKey(Category, on_delete=models.SET_NULL ,null=True,related_name="category") vendor=models.ForeignKey(Vendor, on_delete=models.SET_NULL,null=True,related_name="product") color=models.ManyToManyField(Color,blank=True) size=models.ManyToManyField(Size,blank=True) title=models.CharField(max_length=100,default="Apple") image=models.ImageField(upload_to=user_directory_path,default="product.jpg") description=models.TextField(null=True, blank=True,default="This is a product") price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99) old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99) specifications=models.TextField(null=True, blank=True) product_status=models.CharField(choices=STATUS, max_length=10,default="In_review") status=models.BooleanField(default=True) in_stock=models.BooleanField(default=True) featured=models.BooleanField(default=False) digital=models.BooleanField(default=False) sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="abcdef") date=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(null=True,blank=True) class Meta: verbose_name_plural="Products" def product_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title def get_percentage(self): new_price=((self.old_price-self.price)/self.old_price)*100 return new_price class ProductImages(models.Model): images=models.ImageField(upload_to="product-image",default="product.jpg") product=models.ForeignKey(Product,related_name="p_images" ,on_delete=models.SET_NULL … -
Display Nested Categories with Single Model
class ProductCategory(models.Model): name = models.CharField(max_length=50, blank=True, null=True) parent_category = models.ForeignKey( 'self', null=True, blank=True, on_delete=models.CASCADE) category_image = models.ImageField( upload_to='categories/product/imgs/', verbose_name=_("Category Image"), blank=True, null=True, help_text=_("Please use our recommended dimensions: 120px X 120px")) category_description = models.TextField(verbose_name=_("Category Description")) slug = models.SlugField( blank=True, null=True, allow_unicode=True, unique=True, verbose_name=_("Slugfiy")) date = models.DateTimeField(auto_now_add=True, blank=True, null=True) I would like to display category with nested list.. Can anybody help me to do it..? -
problem with updating data using js in django chat
Good afternoon Here i have django application, where must be chat It dont need to be without delay, because of that i did it using simple models and tryed to make html grab new data about messages using js As i readed in internet, it must work, but i think i made error, if someone can help, i will be very gratefull here is chat.html {% extends 'women/base.html' %} {% load static %} {% block content %} <h1>Chat</h1> <ul> {% for message in messages %} <li> <strong>{{ message.author.username }}:</strong> {{ message.content }} - {{ message.timestamp }} </li> {% endfor %} </ul> <form method="post" action="{% url 'send_message' chat.id %}"> {% csrf_token %} <label for="message">Message:</label><br> <textarea id="message" name="content" rows="4" cols="50"></textarea><br> <button type="submit">Send</button> </form> {% endblock %} {% block javascript %} <script src="{% static 'women/js/chat.js' %}"></script> {% endblock %} it trying to call js file in my static folder women(application name)/static/women/js/chat.js $(document).ready(function(){ // Extract chat_id from the URL var chat_id = window.location.pathname.split('/')[2]; function fetchMessages(){ $.ajax({ url: '/chat/' + chat_id + '/', // replace with your view's URL success: function(data){ // assuming 'data' is a list of messages $('ul').empty(); // clear the current list data.forEach(function(message){ $('ul').append('<li><strong>' + message.fields.author + ':</strong> ' + message.fields.content + … -
showing invalid foreign key django
I am getting this invalid foreign key error in calendars, not sure how to fix it. Here is the code in my models: class Calendar(models.Model): name = models.CharField(max_length=100) description = models.TextField(blank=True, null=True) start_date = models.DateField() end_date = models.DateField() owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) I am trying to link it to the logged in user, but I don't think it is working. I also tried to print the entries in django shell, but it also gives an error of "NameError: name 'Calendar' is not defined" with this query: calendars = calendars.objects.all() -
In Django rest framework model serializer, error when updating a model via viewset for a unique column
I am working on Django rest framework viewsets. I try to update a model named machine by view set's default method update. In my model there is a unique field named machine_number. The model is given below. class Machine(models.Model): id = models.AutoField(primary_key=True) machine_number = models.IntegerField(unique=True) count = models.FloatField(default=None, null=True) variety = models.CharField(max_length=255, default=None, null=True) lycra_draft = models.CharField(max_length=255, default=None, null=True) feedback = models.CharField(max_length=10000, default=None, null=True) csp = models.FloatField(default=None, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) and my serializer is: class MachineSerializer(serializers.ModelSerializer): class Meta: model = Machine fields = ('id', 'machine_number', 'count', 'variety', 'lycra_draft', 'feedback', 'csp') Now, when I update the model using this serializer it throws below error. Machine with this machine number already exists. To resolve this error I have overwrite the serializer's update method. I want to avoid this. My viewset: class MachineViewSet(viewsets.ViewSet): serializer_class = MachineSerializer queryset = Machine.objects.all() def update(self, request, pk): try: machine = Machine.objects.get(pk=pk) request.data['machine_number'] = machine.machine_number except Machine.DoesNotExist: response = build_custom_response(False, 'Machine not found', '') return Response(response, status=status.HTTP_404_NOT_FOUND) serializer = self.serializer_class(data=request.data, partial=True) if serializer.is_valid(): serializer.save() serialized_data = serializer.data success = True message = "Machine updated successfully" status_code = status.HTTP_200_OK else: success = False status_code = status.HTTP_400_BAD_REQUEST err_msg = '\n' error_list = [(serializer.errors[error][0]).capitalize() for error in … -
Django CSRF Failed: CSRF token missing
I have an app in Django and React that I need Login and Logout for I wanna use SessionAuthentication but I get "detail": "CSRF Failed: CSRF token missing." Error every time I test it on postman Can you please let me know how to handle login I also have csrf_exempt on my view but it still requires csrf token Here is My Login @api_view(['POST']) @permission_classes([AllowAny]) @csrf_exempt @require_POST def user_login(request): data = json.loads(request.body.decode('utf-8')) username = data.get('username', '') password = data.get('password', '') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) session = request.session.session_key serializer = UserSerializer(user) user_info = serializer.data return JsonResponse({'message': 'Login successful', 'user': user_info, 'session': session}) else: return JsonResponse({'error': 'Invalid credentials'}, status=401) Here is my Logout @api_view(['POST']) @authentication_classes([SessionAuthentication]) @permission_classes([IsAuthenticated]) def logout_view(request): logout(request) return Response({"message": "Logout successful"}) Here is my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'backend.apps.BackendConfig', 'frontend.apps.FrontendConfig', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', # ... other renderer classes ], } SESSION_ENGINE = 'django.contrib.sessions.backends.db' # Set the session timeout (in seconds) SESSION_COOKIE_AGE = 60 * 15 # 15 minutes, adjust as needed # Set the session cookie name SESSION_COOKIE_NAME = 'myapp_session' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', … -
Python: Datetime countdown
I'm having problem with countdown. This is the code I use, and it's just show a static countdown, it will only change if I refresh the page. I want it to be like this, 0d 0h 1m 3s, 0d 0h 1m 2s and so on. I tried using for i in range, it seems like it only accepts integer? But my variable is date so it shows error. How can I make this possible? Thank you in advance! views.py def dateDiffInSeconds(date1, date2): timedelta = date2 - date1 return timedelta.days * 24 * 3600 + timedelta.seconds def daysHoursMinutesSecondsFromSeconds(seconds): minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) return (days, hours, minutes, seconds) def registration(request) access = WebsiteSettings.objects.all() now = datetime.datetime.today().replace(tzinfo=pytz.UTC) for item in access: countdown = "%dd %dh %dm %ds" % daysHoursMinutesSecondsFromSeconds(dateDiffInSeconds(now, item.date_open)) sleep(1) return render(request, 'registration.html', {'countdown': countdown}) -
ModuleNotFoundError: No Module name 'corsheaders' on google app engine project but works locally
I'm encountering an issue with CORS middleware not working in my Django application deployed on Google App Engine. Despite following the recommended steps, including installing the django-cors-headers package, adding it to the INSTALLED_APPS and MIDDLEWARE settings, and ensuring I'm using a virtual environment, the CORS headers are not being applied in the deployed environment. Steps Taken: Installed django-cors-headers in my virtual environment using pip install django-cors-headers. Added 'corsheaders' to the INSTALLED_APPS list in my Django settings (settings.py). Included 'corsheaders.middleware.CorsMiddleware' in the MIDDLEWARE list in my Django settings. Confirmed that the virtual environment is activated during deployment. Redeployed the application to Google App Engine after making the above changes. Expected Behavior: I expect the CORS middleware to add the necessary CORS headers to responses, allowing cross-origin requests to be processed correctly by my Django application deployed on Google App Engine. Actual Behavior: Despite following the steps above and redeploying the application, CORS headers are not being added to responses, resulting in CORS-related errors in client-side requests. -
Handling threads in Django and Gunicorn
I am trying to make a bot, that every few minutes makes an API request, performs some calculations and some action based on them. The way I did that was first make a model Bot, then a model BotGroup that runs bots on schedule using sched module. import sched import threading from django.db import models class Bot(models.Model): on_status = models.BooleanField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.busy = False def run(self): self.busy = do_stuff() class BotGroup(models.Model): name = models.CharField(max_length=16) bots = models.ManyToManyField(Bot) sch = sched.scheduler(time.time, time.sleep) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.on_status = False self.events = {} self.th = None def start(self, thread): self.th = thread self.on_status = True self._init_bots() self._run() def stop(self): self.on_status = False for bot in self.bot_set: if not bot.busy: if bot.id in self.events.keys(): for event in self.events[bot.id]: if event in self.sch.queue: self.sch.cancel(event) def _init_bots(self): self.bot_set = self.bots.all() for bot in self.bot_set: bot.bg = self def _check_bots(self): delay = self._get_delay() # Returns delay for bot in self.bot_set: if ((bot.busy or self.on_status and bot.on_status) and (bot.id not in self.events.keys() or self.events[bot.id] not in self.sch.queue)): self.events[bot.id] = self.sch.enterabs( delay, bot.id, bot.run) def _run(self): while self.on_status or self.sch.queue: self._check_bots() next_ev = self.sch.run(False) if next_ev is not None: time.sleep(min(5, next_ev)) … -
Why isn't my Django form sending data to the database?
I'm new to Django and Python. I created a blog for my project but when trying to use a form to add blog posts to the database I can't figure out how to make the send button to actually update the model in the database. I managed to make it show in the view but the send button is the problem. This is the model: class BlogPost(models.Model): title = models.CharField(max_length=250) content = models.TextField() post_author = models.CharField(max_length=30) creation_date = models.DateTimeField(auto_now_add=True) modification_date = models.DateTimeField(auto_now=True) image = models.ImageField(upload_to='blog/files/blog_images') categories = models.ManyToManyField('Category', related_name='posts') #Relaciona el atributo con la clase Category y permite usar category.posts def __str__(self): return self.title class Meta: verbose_name = "blog post" verbose_name_plural = "blog posts" This is the form: class newPostForm(forms.Form): title = forms.CharField(max_length=250) content = forms.CharField( widget=forms.Textarea() ) image = forms.ImageField() post_author = forms.CharField() This is the view: def new_post(request): if request.method == "POST": form = newPostForm(request.POST) if form.is_valid(): info = form.cleaned_data() new_post_info = BlogPost( title=info["title"], content=info["content"], image=info["image"], post_author=info["post_author"], ) new_post_info.save() return render(request, "") else: form = newPostForm() return render(request, "blog/new_post.html", {"form":form}) I don't know if you need any more information, let me know. Thanks in advance! -
Djoser 'users/me' endpoint only shows login_field and user_id field
I want that upon hitting the 'users/me' endpoint, I should get something like { "id": 10, "email": "test17@test.com", "first_name": "test", "last_name": null, "is_writer": true, "joined_on": "2024-03-03T17:54:43.629054Z" } Instead I only get { "id": 10, "email": "test17@test.com" } This is my serializer from djoser.serializers import UserCreateSerializer, UserSerializer from .models import CustomUser class CustomUserSerializer(UserSerializer): class Meta(UserSerializer.Meta): fields = ('id', 'email', 'first_name', 'last_name', 'is_writer', 'joined_on') def get_fields(self): fields = super().get_fields() fields['email'].read_only = True fields['first_name'].read_only = True fields['last_name'].read_only = True fields['is_writer'].read_only = True fields['joined_on'].read_only = True return fields # read_only_fields = ('email', 'first_name', 'last_name', 'is_writer',) class CustomUserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): fields = ('email', 'password', 'first_name', 'last_name', 'is_writer', 'joined_on') extra_kwargs = { 'last_name': {'required': False, 'allow_null': True}, } In my settings file I have added these INSTALLED_APPS = [ #DJANGO PRE-DEFINED APPS 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #APPS 'account', #3RD PARTY LIBRARIES 'rest_framework', 'djoser', ] ..... ...... ...... AUTH_USER_MODEL = 'account.CustomUser' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { 'AUTH_HEADER_TYPES': ('JWT',), 'ACCESS_TOKEN_LIFETIME' : timedelta(hours=3), } DJOSER={ 'SERIALIZERS': { 'user':'account.serializers.CustomUserSerializer', 'user_create': 'account.serializers.CustomUserCreateSerializer', } } Nothing seems to work. Is there any way to do it? I need to integrate it with React, so having an endpoint that could give me the details of … -
Are there libraries that support Proof of Possession (PoP) tokens for Django JWT?
I'm working on a web app using React for frontend and Django for backend. Currently, I'm using django simple-jwt in for auth purposes, and the JWT access and refresh tokens are exposed in browser cookies, so anyone who gets their hands on these tokens can theoretically log in on behalf of the actual user. I was wondering if there are ways to prevent issues like this, particularly using Django? I was looking into proof of possession (PoP) tokens, but didn't see any libraries that support this functionality in Django. Are PoP tokens necessary in this case or is it overkill to add this additional claim into JWT? Are there libraries that support this function in Django? -
session variable not being updated in django , only taking the first value
this view that sends a confirmation code to the email, each time it is executed it generates a new code-reset variable perfectly def codeSender(request,user): code = random.randint(100000, 999999) request.session['reset_code'] = code request.session.save() print(request.session['reset_code']) # will print a new code each time this view is being executed request.session['user'] = user.pk subject = "Password reset" message = render_to_string('authentication/emailResetPassword.html', {'code': code}) email = EmailMessage( subject, message, settings.EMAIL_HOST_USER, to=[user.email] ) email.send() this view is supposed to take the value of the username verify if it exists and then call the codeSender() view all along returning a json response indicating that the code confirmation form will be shown def resetPassword(request): if request.method == 'POST': form_name = request.POST.get('form_name') if form_name == "form1": username = request.POST["username"] userQuery = User.objects.filter(username=username) if not userQuery.exists(): clear_messages(request) messages.error(request, "You need to create an account, username doesn't exist!") serialized_messages = json.dumps([{ 'message': message.message, 'message_tag': message.tags, } for message in messages.get_messages(request)]) response_data = { 'show_form2': False, 'messages': serialized_messages} else: user = userQuery.first() codeSender(request,user) messages.success(request, "we've sent to your email a confirmation code please write it") serialized_messages = json.dumps([{ 'message': message.message, 'message_tag': message.tags, } for message in messages.get_messages(request)]) response_data = { 'show_form2': True, 'messages': serialized_messages} return JsonResponse(response_data) return render(request, "authentication/resetPassword.html") the problem lays here … -
How do we use django-allauth with a custom user model in Django?
Here's my User model: class UserManager(BaseUserManager): """Manager for CustomUser.""" def build_user(self, email, password=None, **extra_fields): """Instantiate and return a regular user with an email and password.""" if not email: raise ValueError(_('The Email field must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def build_superuser(self, email, password, **extra_fields): """Instantiate and return a superuser with an email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, **extra_fields) class User(AbstractUser): """CustomUser model""" email = models.EmailField(_('email address'), unique=True, blank=False, null=False) username = models.CharField(_('profile name'), max_length=150, unique=False, blank=False, null=False) gender = models.IntegerField(_('gender'), choices=Gender.choices, blank=True, null=True) birth_date = models.DateField(_('birth date'), blank=True, null=True) country = CountryField(blank_label='(select country)', blank=True, null=True) is_admin = models.BooleanField(default=False, blank=True, null=True) online_status = models.BooleanField(default=False, blank=True, null=True) # True for online, False for offline USERNAME_FIELD = 'email' # Use email to log in REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'gender', 'birth_date', 'country'] # 'email' is required by default objects = UserManager() def __str__(self): return self.email Here's my SignUpForm class on forms.py from django import forms from allauth.account.forms import SignupForm from .choices import Gender from django_countries.widgets import CountrySelectWidget from django_countries import countries from datetime import datetime years_range = list(range(datetime.now().year - 18, 1899, -1)) class CustomSignupForm(SignupForm): first_name = forms.CharField(max_length=30, label='First Name') last_name = forms.CharField(max_length=30, … -
After I redirect to another page(from homepage to another tamplate) css doesn't load
I have problem with my css file loading for specific templates(every beside homepage). The path for my css file is: Website/static/css/home.css and when I enter my webpage I'm starting at homepage where everything is okay, but then when I try to go to another page(for example mydomain.com --> mydomain.com/something/) the css doesn't load and in console I see this: http://example.com/something/static/css/home.css "Refused to apply style from 'http://example.com/something/static/css/home.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled." and I don't understand why does it now look for static css in different root path(If that's a problem?). What I use is django, aws-ec2: my settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') my urls.py: urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_URL) nginx conf: location /static/ { autoindex on; alias /home/ubuntu/Website/static/; } homepage.html <link rel="stylesheet" href="static/css/home.css" /> another template.html: {% extends './homepage.html' %} {% load static %} Thanks in advance! -
How can I create categories and subcategories in django models?
I am building a simple website for a car marketplace. I have written the brand, series and car models. (I purposefully want to treat each of them as seperate models.) Whenever I create a car in the admin panel I want to be able to pick a car brand - let's say Mercedes - and when I choose the brand I want the next option to be only the series of Mercedes not the series of other cars. Here is a representation of my code so far: class Brand(models.Model): brand = models.CharField(max_length=100) class Series(models.Model): brand = models.ForeignKey(Brand, on_delete=models.CASCADE) series = models.CharField(max_length=100) class Car(models.Model): brand = models.ForeignKey(Brand, on_delete=models.CASCADE) series = models.ForeignKey(Series, on_delete=models.CASCADE) -
Forbidden (403) CSRF verification failed. Request aborted. with Google OAuth2
Tengo los siguientes archivos de mi app frondend en React y backend con django: I have the following files from my frontend app in React and backend with django: // Router.jsx import { createBrowserRouter, Navigate, RouterProvider } from 'react-router-dom' import { useEffect } from 'react' import { Home } from '@pages/Home' import { Error } from '@pages/Error' import { NotFound } from '@pages/NotFound' export const Router = () => { const google = window.google const handleCallbackResponse = (response) => { console.log(response) const authorizationCode = response.credential if (authorizationCode) { console.log('Authorization code:', authorizationCode) fetch('http://localhost:8000/auth/google/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code: authorizationCode }) }) .then(response => { if (!response.ok) { throw new Error('Network response was not ok') } return response.json() }) .then(data => { console.log('Response from Django backend:', data) }) .catch(error => { console.error('There was an error with the fetch operation:', error) }) } } useEffect(() => { google.accounts.id.initialize({ client_id: 'No la pongo por seguridad', callback: handleCallbackResponse }) google.accounts.id.renderButton(document.getElementById('signInButton'), { theme: 'outline', size: 'large' }) }, []) const router = createBrowserRouter([ { path: '/', element: <Navigate to='/home' />, errorElement: <Error /> }, { path: '/home', element: <Home />, errorElement: <Error /> }, { path: '*', element: <NotFound /> … -
Django-React google calendar API redirect_uri_mismatch
my react is in http://localhost:3000 my django is in http://localhost:8000 im trying to get the info form my calendar, i found this code in link `class Test(APIView): def get(self, request): """Shows basic usage of the Google Calendar API. Prints the start and name of the next 10 events on the user's calendar. """ SCOPES = ['https://www.googleapis.com/auth/calendar'] creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists("token.json"): creds = Credentials.from_authorized_user_file("token.json", SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( "notes/credentials.json", SCOPES ) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open("token.json", "w") as token: token.write(creds.to_json()) service = build("calendar", "v3", credentials=creds) # Call the Calendar API now = datetime.utcnow().isoformat() + "Z" # 'Z' indicates UTC time print("Getting the upcoming 10 events") events_result = ( service.events() .list( calendarId="primary", timeMin=now, maxResults=10, singleEvents=True, orderBy="startTime", ) .execute() ) events = events_result.get("items", []) if not events: print("No upcoming events found.") return JsonResponse({'message': 'No upcoming events found.'}, status=200) # Prepare data … -
Troubleshooting Dynamic Image Updating and Color-Based Filtering in Django Product Page
I have created a hyperlink in html So, In product_detail_page.html: <div class="product-color"> <span>Color</span> {% for c in colors %} <div class="color-choose"> <a href="?colorID={{c.id}}" style="display: inline-block; width: 40px; height: 40px; background-color: {{c.code}}; border-radius: 50%; border: 2px solid #FFFFFF; cursor: pointer; float: left; margin-right: 10px; box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.33);"> </a> </div> {% endfor %} </div> Now it is taking colors id (suppose if I click on red color it is taking {?colorID=1} in url) Now I created a view for this That if I Click in a color it will change the product Image So, In views.py def product_detail_view(request,pid): product=Product.objects.get(pid=pid) colors = Color.objects.all() sizes= Size.objects.all() p_image=product.p_images.all() products=Product.objects.filter(cagtegory=product.cagtegory) ColorID=request.GET.get('colorID') if ColorID: product=Product.objects.filter(color=ColorID) else: product=Product.objects.all() context={ "p":product, "p_image":p_image, 'colors': colors, 'sizes': sizes, 'products': products, } return render(request,"core/product_detail.html",context) and I created this models in models.py class Product(models.Model): pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) cagtegory=models.ForeignKey(Category, on_delete=models.SET_NULL ,null=True,related_name="category") vendor=models.ForeignKey(Vendor, on_delete=models.SET_NULL,null=True,related_name="product") color=models.ManyToManyField(Color,blank=True) size=models.ManyToManyField(Size,blank=True) title=models.CharField(max_length=100,default="Apple") image=models.ImageField(upload_to=user_directory_path,default="product.jpg") description=models.TextField(null=True, blank=True,default="This is a product") price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99) old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99) specifications=models.TextField(null=True, blank=True) product_status=models.CharField(choices=STATUS, max_length=10,default="In_review") status=models.BooleanField(default=True) in_stock=models.BooleanField(default=True) featured=models.BooleanField(default=False) digital=models.BooleanField(default=False) sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="abcdef") date=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(null=True,blank=True) class Meta: verbose_name_plural="Products" def product_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title def get_percentage(self): new_price=((self.old_price-self.price)/self.old_price)*100 return new_price class ProductImages(models.Model): images=models.ImageField(upload_to="product-image",default="product.jpg") product=models.ForeignKey(Product,related_name="p_images" ,on_delete=models.SET_NULL … -
register viex in django
i have a problem: when I try to submit the form, the user's information is not being saved, and I cannot redirect to the index page . I have this error: ("POST /user/sign-up/ HTTP/1.1" 200 32209 [03/Mar/2024 07:58:43] "GET /static/fonts/simple-line-iconsc05f.woff?thkwh4 HTTP/1.1" 404 1963 [03/Mar/2024 07:58:43] "GET /static/fonts/fontawesome-webfont5b62.ttf?v=4.6.3 HTTP/1.1" 404 1967) i want when i go to the regiqter form i an put the information as user and then we redirect to the home page when i submit the register button -
Tag instances via django-taggit are not rendering as expected in update post form
{{ form.tags | as_crispy_field }} is not rendering as expected when retrieving the question instance. The same crispy forms syntax works and renders as perfectly when creating an initial post Pressing Submit leads to Server 500 error. Testing results are documented inline: <!-- templates/update_question.html --> {% extends "base.html" %} {% load static %} {% load crispy_forms_tags %} {% block extra_head %} <!-- django-quill-editor Media --> {% include 'django_quill/media.html' %} {% endblock %} {% block content %} <main class="flex-shrink-0 main-bg"> <div class="container-question my-5"> [...] <form id="standards-form" method="post" action="{% url 'question_update' slug=question.slug %}"> {% csrf_token %} [...] <h2 class="text-center">Subject line</h2> {{ form.subject | as_crispy_field }} <!-- rendering as expected--> <br> <h2 class="text-center">Details</h2> {{ form.content | as_crispy_field }} <!-- rendering as expected--> <br> <h2 class="text-center">Tags</h2> <div class="tag-input"> <div class="input"> <div> <i class="fa fa-tags"></i> {{ form.tags | as_crispy_field }} <!--not rendering as expected: reading as [<Tag: tag1>, <Tag: tag2>, <Tag: tag3>]. Expecting tag1 tag2 tag3 to be retrieved from django-taggit's TaggableManager--> </div> </div> <div class="tag-list mb-4"></div> </div> <button type="submit" class="btn btn-primary " id="question-submit">Submit</button> </form> </div> </main> {% endblock %} debugging steps the form is handled in this class I have tried print logs and moving the init function to the top. # main_forum/forms/question_form.py # … -
Using django-paypal and having trouvles with the IPN handshake
I'm trying to create an e-commerce platform for the first time. I followed a tutorial through and everything is working fine except for the IPN signal. Instead I'm getting the following error: ... raise ConnectTimeout(e, request=request) requests.exceptions.ConnectTimeout: HTTPSConnectionPool(host='ipnpb.sandbox.paypal.com', port=443): Max retries exceeded with url: /cgi-bin/webscr (Caused by ConnectTimeoutError(<urllib3.connection.HTTPSConnection object at 0x000002DA197233D0>, 'Connection to ipnpb.sandbox.paypal.com timed out. (connect timeout=None)')) This is my code: [signals.py] from paypal.standard.ipn.signals import valid_ipn_received from django.dispatch import receiver @receiver(valid_ipn_received) def payment_notification(sender, **kwargs): ipn = sender if ipn.payment_status == 'Completed': print("Succed") [apps.py] from django.apps import AppConfig class PaySystemConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'PaySystem' def ready(self): # import signal handlers import PaySystem.signals [init.py] default_app_config = 'PaySystem.apps.PaySystemConfig' I really have no idea where to start tracing the issue. Any lead will be thanked. -
My postgresql database doesn't persist between docker runs
I am learning docker and postgresql and I have problem with persisting data between the re-runs of the app. My docker-compose.yml: version: '3.7' services: web: build: . command: python3 /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:15 volumes: - postgres_data:/var/lib/postgresql/data environment: POSTGRES_PASSWORD: postgres ports: - "5432:5432" volumes: postgres_data: external: true I run my project with docker-compose up -d go with docker-compose exec web python3 manage.py migrate but after I go docker-compose down and I run the containers I have to migrate again. It's really bothersome. Can someone help, please?