Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to make download link inside excel auto save
I was trying to make excel file using openpyxl v3.1.2 in Django, Python v3.9, the excel file contains link displayed as 'Click Here', those are links to files, despite the links are open correctly, but they are not save into the machine.. I mean they open in browser, or in the suitable program, but they are not saved (downloaded) into my machine. How to make them downloaded directly into my machine, like when u download file from internet. here is my code: #views.py def export_applicants_xls(request, pk, applicant_id=None): job = get_object_or_404(Job, pk=pk) if applicant_id: candidate_list = Applicant.objects.filter(job=pk, pk=applicant_id) else: candidate_list = Applicant.objects.filter(job=pk) if not candidate_list: messages.error(request, _('No applicants for this job'), 'danger') return redirect('employer-job-detail', pk=pk) response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') if applicant_id: response['Content-Disposition'] = f'attachment; filename=applicant_{applicant_id}_details.xlsx' else: response['Content-Disposition'] = f'attachment; filename=all_applicants_#{job.slug}.xlsx' wb = Workbook() ws = wb.active ws.title = 'Applicants' # Set header row in bold header_font = Font(bold=True) columns = [ 'CV File', 'ID card', 'Tawjihi file', 'University File', 'Experience File', 'Master file', 'Profession', 'Injury Insurance', 'Membership File', 'Temporary Membership'] for col_num, column in enumerate(columns, 1): cell = ws.cell(row=1, column=col_num, value=column) cell.font = header_font ws.column_dimensions[get_column_letter(col_num)].width = 15 # Adjust column width # Populate data rows for row_num, applicant in enumerate(candidate_list, 2): row_data … -
Search results are not showing. And my URL Tab shows: "http://127.0.0.1:8000/search?" instead of this: "http://127.0.0.1:8000/search?q=name"
Codes on views.py def searching(request): prod = None query = None if 'q' in request.GET: query = request.GET.get('q') prod = Products.objects.all().filter(Q(name__contains=query) | Q(des__contains=query)) return render(request, 'search.html', {'qr': query, 'pr': prod}) Codes on urls.py urlpatterns = [ path('', views.home, name='hm'), path('<slug:c_slug>/', views.home, name='prod_cat'), path('<slug:c_slug>/<slug:product_slug>', views.prodetails, name='details'), path('search', views.searching, name='searching'), ] Codes on search.html <div class="row flex px-xl-5"> {% for i in pr %} <div class="col-lg-3 col-md-4 col-sm-6"> <div class="product-item bg-light mb-4"> <div class="product-img position-relative overflow-hidden"> <a href="{{i.get_urls}}"><img class="img-fluid w-100" src="{{i.img.url}}" alt="" style="height:250px; width:500px;"> </a> </div> <div class="text-center py-4"> <a class="h6 text-decoration-none text-truncate" href="{{i.get_url}}">{{i.name}}</a> <p>{{i.des|truncatechars:80}}</p> <div class="d-flex align-items-center justify-content-center mt-2"> <h5>RS {{i.price}}</h5><h6 class="text-muted ml-2"><del>RS 123.00</del></h6> </div> <p>Stocks left: {{i.stock}}</p> <div class="d-flex align-items-center justify-content-center mb-1"> <small class="fa fa-star text-primary mr-1"></small> <small class="fa fa-star text-primary mr-1"></small> <small class="fa fa-star text-primary mr-1"></small> <small class="fa fa-star text-primary mr-1"></small> <small class="fa fa-star text-primary mr-1"></small> <small>(99)</small> </div> </div> </div> </div> {% endfor %} </div> Codes on base.html <div class="col-lg-4 col-6 text-left"> <form action="{% url 'searching' %}" method="get"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search for products"> <div class="input-group-append"> <span class="input-group-text bg-transparent text-primary"> <i class="fa fa-search"></i> </span> </div> </div> </form> </div> Actually, my problem is that when I search for a product, on the URL tab, it should be shown … -
Cannot resolve keyword 'calendar_id' into field. Choices are: description, end_date, event, id, name, owner, owner_id, start_date
Here is the code where I define the Event and Calendar 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) def __str__(self): return self.name class Event(models.Model): name = models.CharField(max_length=100) description = models.TextField(blank=True, null=True) date = models.DateField( ) start_time = models.TimeField() # Example default time duration = models.DurationField() # Example default duration of 1 hour calendar = models.ForeignKey(Calendar, on_delete=models.CASCADE) # owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name Here is the view I am trying to use: class EventListView(LoginRequiredMixin, ListView): model = Event template_name = 'list.html' context_object_name = 'EventListView' def get_queryset(self): calendar_id = self.kwargs['calendar_id'] return Calendar.objects.filter(calendar_id=calendar_id) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if not self.request.user.is_authenticated: for event in context['EventListView']: event.name = '' return context I have another similar view that looks like this, also using the calendar_id and this view works fine. I am not sure why the EventListView is showing this error. class CalendarDetailView(DetailView): model = Calendar template_name = 'calendars/detail.html' context_object_name = 'calendar' pk_url_kwarg = 'calendar_id' def get_queryset(self): return Calendar.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context -
Django Auth fails, even if user/pass exist in DB
Given I have this create user view class UserView(View): def post(self, request): try: data = json.loads(request.body) encrypted_username_hex = data.get('username', None) encrypted_password_hex = data.get('password', None) phone_number = data.get('phone_number', None) email = data.get('email', None) missing_fields = [field for field in ['username', 'password', 'email'] if data.get(field) is None] if missing_fields: return JsonResponse({"error": f"Missing required field(s): {', '.join(missing_fields)}"}, status=400) session_id = request.session.session_key print("user create ses", session_id) private_key_pem, _ = RSAKeyManager.get_keys(session_id) if not private_key_pem: return JsonResponse({"error": "Invalid session or RSA keys not found"}, status=404) print("private key", private_key_pem) username = RSAHandler.decrypt_from_hex(private_key_pem, encrypted_username_hex) password = RSAHandler.decrypt_from_hex(private_key_pem, encrypted_password_hex) user = CustomUser.objects.create_user(username=username, email=email, password=password, phone_number=phone_number) return JsonResponse({"user": user.email, "phone_number": user.phone_number}, status=201) except IntegrityError as e: if 'username' in str(e): return JsonResponse({"error": "This username is already taken."}, status=400) elif 'email' in str(e): return JsonResponse({"error": "This email is already in use."}, status=400) else: return JsonResponse({"error": "There was an error with your request."}, status=400) except ValidationError as e: return JsonResponse({"error": str(e.messages[0])}, status=400) except Exception as e: traceback.print_exc() return JsonResponse({"error": "Internal server error."}, status=500) And this custom user model: class CustomUserManager(BaseUserManager): def create_user(self, username, email, password=None, phone_number=None, **extra_fields): if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(username=username, email=email, phone_number=phone_number, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, … -
Skin Detection and Color Clustering Not Executing in Django Web Application Using YOLOv8n-face Model
I'm currently working on integrating a YOLOv8n-face model with Django for a web application. The objective is to perform various tasks including face detection, skin detection, and color clustering upon clicking a button on an index.html page. However, while the face detection function is running smoothly, the functions for skin detection and color clustering are not executing as expected. Here's an overview of my setup: I have a Django project with a Python file (color_clustering.py) containing functions for skin detection and color clustering. I'm using the YOLOv8n-face model for face detection, and it's integrated into the Django project successfully. Within the detect_face function, I'm calling the detect_skin and cluster_colors functions to perform skin detection and color clustering on the detected face regions. Here's a simplified version of the code structure: # color_clustering.py def detect_skin(face_region): # Skin detection logic pass def cluster_colors(face_region): # Color clustering logic pass # views.py (Django) from django.shortcuts import render import cv2 from ultralytics import YOLO def detect_face(frame, model): # Face detection logic using YOLOv8n-face pass def index(request): # Load YOLOv8n-face model model = YOLO("yolov8n-face.pt") # Capture a frame and process it # Call detect_face with model # Inside detect_face, call detect_skin and cluster_colors # Render the … -
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 …