Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Select2 Bootstrap5 Theme
I'm having a problem getting the Django-Select2 Bootstrap5 theme working. The select2 element is displaying the correct field from the DB, and my search function works correctly, it's just the theme aspect that's the problem. select2_init.js $(document).ready(function () { $('#id_school').select2({ theme: 'bootstrap-5', }); }); base.html {% load static %} <!DOCTYPE html> <html lang="en" data-bs-theme="dark"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{% block title %}{% endblock %}</title> {% block css %} <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}" type="text/css"> <link rel="stylesheet" href="{% static 'css/custom.css' %}" type="text/css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css"/> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css"/> {% endblock %} </head> <body> {#TODO: Messages#} <div class="container flex-fill pt-5"> {% block content %} {% endblock %} </div> <div class="container"> <footer class="d-flex justify-content-between mt-3 my-4 border-top"> <p>© 2023 Company</p> </footer> </div> {% block js %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.7/dist/umd/popper.min.js" integrity="sha384-zYPOMqeu1DAVkHiLqWBUTcbYfZ8osu1Nd6Z89ify25QV9guujx43ITvfi12/QExE" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.min.js" integrity="sha384-Y4oOpwW3duJdCWv5ly8SCFYWqFDsfob/3GkgExXKV4idmbt98QcxXYs9UoXAB7BZ" crossorigin="anonymous"></script> <script src="{% static 'js/select2_init.js' %}"></script> {% endblock %} </body> </html> register.html {% extends 'base.html' %} {% load static %} {% block css %} {{ block.super }} {{ form.media.css }} {% endblock %} {% block title %} Maths Root: Register {% endblock %} {% block content %} <h1>Create an account</h1> <p>Please use the form below to register.</p> <form method="post"> {% csrf_token %} … -
Django | <title> object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used
I get an error using with using form.save(commit=False) and I cannot figure out what I'm doing wrong. My view looks something like this: views.py def make_electable(request, election_id): election = get_object_or_404(CommissionElection, id=election_id) if request.method == 'POST': form = MakeElectable(request.POST) if form.is_valid(): electable = form.save(commit=False) electable.election.set(election) form.save() forms.py class MakeElectable(forms.ModelForm): class Meta: model = ElectablePerson fields = ['commission',] commission = forms.ModelChoiceField(queryset=Commissie.objects.all(), widget=forms.RadioSelect()) models.py class CommissionElection(models.Model): title = models.CharField(max_length=64) commission = models.ManyToManyField(Commissie) electable_time = DateRangeField() voting_time = DateRangeField() class ElectablePerson(models.Model): commission = models.CharField(max_length=128) election = models.ManyToManyField(CommissionElection) The error I get is: "<ElectablePerson: ElectablePerson object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. I don't see why the object is None. I suspect it has something to do with the manytomanyfield. -
Python developer
First of all, I have learned all main concepts for this programming language(python) After that I have no idea what I should do next. My first question was how I started I had already got answer. At the moment, I am searching how to get requests from websites through the library requests. Now I am wondering how to get a job ??? I tried many times through the internet websites like hh, My question is how easily learn libraries for the python programming language . firstly , My attempts were successfully , because I tried through the replit.com this website provide me fully access to the any labrary . -
Django: dumpdata cannot connect to database
We have a legacy Django application and I am trying to migrate the old app to a new location. The Django version is 2.2. I want to execute dumpdata command to load the output fixture to the new location. The old machine containing the app has default configurations for database i.e. it is using a PostreSQL installed in the same machine and use localhost as address. When running dumpdata, I cannot seem to connect to the database. (venv) software# python manage.py dumpdata > dump.json CommandError: Unable to serialize database: could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? I also tried the command python manage.py inspectdb to check the connection and it is still not able to connect. I can access the admin page of the app and can view details which is a clear indicator that database is running well and can index what is on the admin page. Why am I getting this error? Could it be I am using wrong machine user? -
Django Rest Framework test not working with DRF APIClient() instance
I am trying to run this Django test of my DRF API endpoint: def test_list_settlements(self): url = reverse('settlements:settlement_api-list', kwargs={'team_slug':'team-slug'}) try: team = Team.objects.get(slug=self.venue.team.slug) # Check if the team from the URL is one of the user's teams except Team.DoesNotExist: raise Http404("No team matches the given slug for this user.") pdb.set_trace() url = reverse('settlements:settlement_api-list', kwargs={'team_slug': 'team-slug'}) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data), 1) self.assertEqual(response.data[0]['id'], self.settlement.id) I set the pdb.set_trace() to see if I could discover anything fishy, and I'm super stumped. With the client, I verified it's properly logged in, and can make calls to any other endpoint successfully returning values. In swagger, if I use this particular end point, of which the reverse() computes to /a/team-slug/settlements/api/ it will return all the settlements correctly in the swagger UI. But when I make the call here with self.client.get(url), it returns a 404. When the pdb.set_trace() starts, I can call the client, and other endpoint calls successfully, but this particular one gives me a 404. I cannot for the life of me figure out why it works in every other situation (being Swagger UI and my dev environment calling from localhost:8000), except my test APIClient() instance, which can successfully call other endpoints in … -
iOS - Django Python - Oauth2
I am trying to build an authentication system for an iOS app. Those are the steps: The user will log via Google oauth and will receive an auth code. iOS app will send to BE this auth code and will exchange with an access token. The BE will create a new token using Django Oauth Toolkit and send back to iOS app and will be stored into keychain. Now the problem I have: When the app launches freshly (previously logged in), I try to use .onAppear and inside I have GIDSignIn.sharedInstance.restorePreviousSignIn, and make a call to Auth server that issued my token to verify if it is still active and renew it using the refresh token. The url that I want to use is /o/introspect/, but is there any way to send the token without sending client id and client secret? I don't want them to be exposed on the iOS app. Or should I create a new url that accepts only the token and verifies? Thank you! -
Django complex data display in template
I am not able to proceed with data display. My db is: type month user First 2023-05-01 1 second 2023-04-01 1 second 2023-05-01 1 First 2023-03-01 1 second 2023-02-01 1 First 2023-02-01 1 second 2023-02-01 1 I want to display this data in template like below: Type First data: user 2023-05-01 2023-04-01 2023-03-01 2023-02-01 1 Yes No Yes Yes Notes: I need to filter last 6 months data for each user, seperate them by type and display whether they were present in each month or note. I have tried regroup with below code: {% regroup datadump by type as ret_type %} <ul> {% for type in ret_type %} <li>{{ type.grouper }} <ul> {% for data in type.list %} <li style="padding-left:20px;">{{data.user}}</li> {% endfor %} </ul> </li> {% endfor %} </ul> I am not able to make table with each month for last six months and show it there. -
save django pghistory tracker
So I want to track some fields in model,therefore I used pghistory this is my code: @pghistory.track( pghistory.BeforeUpdate( "trailer_changed", condition=Q( old__rate__df=F("new__rate"), old__truck__df=F("new__truck"), ), ), fields=["rate", "truck"], model_name="loadtracker", ) but problem is that, if I change only "rate" field, it also saves unchanged value of "truck" field too, then when I want to display changes on front, I get messed up, because there is also unchanged values too, example: if I change only truck field 10 times, in DB result will be like this rate - truck value1 - changed_value1 value1 - changed_value2 value1 - changed_value3 value1 - changed_value4 value1 - changed_value5 value1 - changed_value6 value1 - changed_value7 value1 - changed_value8 ... how can I resolve this? that would be good if I save for unchanged field "None" or null or something else Btw, what is the best practice to save history tracker? for other models I have to track about 10 fields, and is it ok to use like that? or should I create tracker table for every field? -
Searching objects by pressing button in django
I want to create a search form but using button instead of text input. I have a table with categories and each category has a button that leads to subcategories that share this category. When I click the button I somehow want to send name of the category to the view and filter subcategories that will be then rendered to specific template. Here is my template: <table> <thead> <tr> <th>ID</th> <th>Category name</th> <th>Updated at</th> <th>Subcategories</th> <th>Edit</th> <th>Delete</th> </tr> </thead> <tbody> {% for category in categories %} <tr> <td>{{category.id}}</td> <td>{{category.name}}</td> <td>{{category.updated|date:"d.m.Y G:i:s"}}</td> <td><a href="#">Subcategories</a></td> <!-- This link should be modified --> <td><a href="#">Edit</a></td> <td><a href="#">Delete</a></td> </tr> {% endfor %} </tbody> </table> So as you can see I have a link 'Subcategories' which should open subcategory page where I will display all subcategories of that category Here is my models.py: class Category(models.Model): name = models.CharField(max_length=100, null=True, blank=True) icon = models.CharField(max_length=50, null=True, blank=True) updated = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name class Subcategory(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True, blank=True) icon = models.CharField(max_length=50, null=True, blank=True) updated = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Subcategories' def __str__(self): return self.name I have no idea how to do this. I'm … -
Dependant permissions in django rest framework
I have a query - Suppose I have a notebooks (Physics,Chemistry,Math,...) and I want to put note in these notebooks by implementing some permissions - If I have permissions to view notebooks and I must be able to see all/some note books in drop down I should be able to add/delete/view note inside any notebook if I am allowed to access that notebook and allowed to add/delete/view note inside that notebook What could be best approach to implement this situation best I walk around stack overflow but did not find any answer regarding it -
Why DRF modelserializers are returning 400 error code instead of 404, for the objects (foreign keys) they couldn't find?
I've been using modelserializers for a while, without noticing that when we enter an out-of-range id in request_body for foreign key fields, drf returns a 400 status code instead of 404! Is it right to do so? How can we change this behavior to return 404 status code in our modelserializers? -
Date Validatind Error When Trying To Migrate From sqllite to mssql in django
from django.db import models from tinymce import models as tinymce_models from django.core.exceptions import ValidationError from django.utils import timezone # Create your models here. class Role(models.Model): roleName = models.CharField(max_length=200) active =models.BooleanField(default=True) createdBy =models.CharField(max_length=200) modifiedBy =models.CharField(max_length=200) createdat = models.DateTimeField( db_column='createdAt', blank=True, null=True, auto_now_add=True) updatedat = models.DateTimeField( db_column='updatedAt', blank=True, null=True, auto_now=True) class Meta: verbose_name_plural="Role" def __str__(self): return self.roleName class CMSUser(models.Model): fullName =models.CharField(max_length=200) email =models.CharField(max_length=200) password =models.CharField(max_length=200) active =models.BooleanField(default=True) createdBy =models.CharField(max_length=200) modifiedBy =models.CharField(max_length=200) createdat = models.DateTimeField( db_column='createdAt', blank=True, null=True, auto_now_add=True) updatedat = models.DateTimeField( db_column='updatedAt', blank=True, null=True, auto_now=True) class Meta: verbose_name_plural="User" def _str_(self): return self.fullName class Campus(models.Model): campusName = models.CharField(max_length=200,unique=True) createdat = models.DateTimeField( db_column='createdAt', blank=True, null=True, auto_now_add=True) updatedat = models.DateTimeField( db_column='updatedAt', blank=True, null=True, auto_now=True) class Meta: verbose_name_plural="Campus" def __str__(self): return self.campusName class Group(models.Model): groupName =models.CharField(max_length=200) active =models.BooleanField(default=True) createdBy =models.CharField(max_length=200) modifiedBy =models.CharField(max_length=200) createdat = models.DateTimeField( db_column='createdAt', blank=True, null=True, auto_now_add=True) updatedat = models.DateTimeField( db_column='updatedAt', blank=True, null=True, auto_now=True) class Meta: verbose_name_plural="Group" def __str__(self): return self.groupName class Menu(models.Model): menuName =models.CharField(max_length=200) active =models.BooleanField(default=True) createdBy =models.CharField(max_length=200) modifiedBy =models.CharField(max_length=200) createdat = models.DateTimeField( db_column='createdAt', blank=True, null=True, auto_now_add=True) updatedat = models.DateTimeField( db_column='updatedAt', blank=True, null=True, auto_now=True) class Meta: verbose_name_plural="Menu" def _str_(self): return self.menuName class Content(models.Model): contentTitle =models.CharField(max_length=200) contentImage =models.ImageField(upload_to='upload/content/') contentData =tinymce_models.HTMLField() menuID =models.ForeignKey(Menu, on_delete=models.CASCADE) active =models.BooleanField(default=True) createdBy =models.CharField(max_length=200) modifiedBy =models.CharField(max_length=200) createdat =models.DateTimeField(db_column='createdAt', blank=True, null=True, auto_now_add=True) … -
How to use the field "email" as "username" in django?
Hello everyone I am new to django and I am creating a project where I created a database with a table "tblusuarios" and managed to insert the necessary data such as name, surname, email, password, however, when I go to make the login I am using the field "mail" as username, but so far fails to make the login. Any advice you can offer me? User model: class TblUsuarios(AbstractBaseUser, models.Model): nombre = models.CharField(max_length=80) apellidos = models.CharField(max_length=80, blank=True, null=True) correo = models.CharField(max_length=80, unique=True) telefono = models.CharField(max_length=11, blank=True, null=True) password = models.CharField(max_length=80) foto = models.ImageField(upload_to='images/') tbl_roles = models.ForeignKey(TblRoles, models.DO_NOTHING, default=1) # object = CustomAccountManager() USERNAME_FIELD = 'correo' #le damos el username por defecto a la tabla REQUIRED_FIELDS=(['nombre']) class Meta: db_table = 'tbl_usuarios' View function: def login_user(request): if request.method == 'POST': correo = request.POST['email'] password = request.POST['password'] user = authenticate(request, username = correo, password = password) print(user) if user is not None: login(request, user) messages.info(request, 'Has ingresado correctamente a la aplicacion!!') return redirect('home') else: messages.error(request, 'Ha ocurrido un error a la hora de iniciar sesion!') return redirect('login') else: context = {} return render(request, 'users/login.html', context) Login form: {% extends "layouts/layout.html" %} {% block content %} {% if user.is_authenticated %} <h2>Ya estas logueado en … -
Model fields won't appear through Django development server. How do I fix it?
I am following the Tech With Tim Django + React tutorial (although naming some variables differently)(https://youtu.be/uhSmgR1hEwg) and ran into a problem with views when running the server. My urls work properly but when I go onto the page I can't find any of my model fields. I am new to Django and VSCode (having mostly only used PyCharm in the past) so it may end up being a very simple solution. Here is my code and directories: Directories models.py: from django.db import models import string import random def generate_unique_code(): length = 6 while True: code = ''.join(random.choices(string.ascii_uppercase, k=length)) if Room.objects.filter(code=code).count() == 0: break return code class Room(models.Model): code = models.CharField(max_length=8, default="", unique=True) host = models.CharField(max_length=50, unique=True) guest_can_pause = models.BooleanField(null=False, default=False) votes_to_skip = models.IntegerField(null=False, default=1) created_at = models.DateTimeField(auto_now_add=True) serializers.py: from rest_framework import serializers from .models import Room class RoomSerializer(serializers.ModelSerializer): class Meta: model = Room fields = '__all__' urls.py: from django.urls import path from .views import RoomView urlpatterns = [ path('home', RoomView.as_view()), ] views.py: from django.shortcuts import render from rest_framework import generics from .serializers import RoomSerializer from .models import Room class RoomView(generics.ListAPIView): queryset = Room.objects.all() serializer_class = RoomSerializer urls.py: """URL Configuration The `urlpatterns` list routes URLs to views. For more information please … -
How to filter HTML select tags in django
i am trying to use How to use Q objects to filter complex queries, it works with search type input but not with select tag. when I try to filter a set of an input and two selects it returns an empty QuerySet. image below: Debugger image I have no idea why this happens. There is another way to filter sets of HTML tags? My model tfrom django.db import models from categories.models import Category from choices.stt_choices import STATE_CHOICES from choices.occupation_choices import OCCUPATION_AREA_CHOICES class Vacancy(models.Model): name = models.CharField('Name', max_length=255) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) contact_number = models.PositiveBigIntegerField('Phone number') contact_whatsapp = models.PositiveBigIntegerField('WhatsApp') contact_email = models.EmailField('E-mail') occupation_area = models.CharField( 'Occupation area', max_length=3, choices=OCCUPATION_AREA_CHOICES ) state = models.CharField('State', max_length=2, choices=STATE_CHOICES) city = models.CharField('City', max_length=255) number = models.IntegerField('Vacancies number', default=0) date_posted = models.DateTimeField(auto_now=True) img = models.ImageField( 'Image', upload_to='vacancies_img/%Y/%m/%d', blank=True, null=True ) salary = models.CharField('Salary', max_length=255) about_company = models.TextField('About the company') requirements = models.TextField('Requirements') activities = models.TextField('Activities') benefits = models.TextField('Benefits', blank=True, null=True) schedule = models.TextField('Schedule') def __str__(self) -> str: return self.name My view from vacancies.models import Vacancy from django.views.generic.list import ListView from django.shortcuts import render from django.db.models import Q class VacancyHome(ListView): model = Vacancy template_name = 'vacancies/index.html' context_object_name = 'vacancies' class VacancySearch(VacancyHome): template_name = 'vacancies/search.html' def get_queryset(self): … -
Sending email via Django gives me (_ssl.c:3895) error
It looks like there is a problem with the ssl certificate when trying to send emails using django.core.mail.backends.smtp.EmailBackend. Settings.py EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'email@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_SSL_CERTFILE = certifi.where() EMAIL_SSL_CA_BUNDLE = certifi.where() The password is an app password I created in my google account. I even tried to use third party services like Elastic Email and SendGrid, but it still gives me an error. Removing the EMAIL_SSL_CERTFILE and EMAIL_SSL_CA_BUNDLE will then give me a (_ssl.c:997) error. views.py @api_view(["POST"]) def signupUser(request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializers.py import random from user_api.models import CustomUser from django.contrib.auth.hashers import make_password from django.core.mail import EmailMessage from django.core.mail import send_mail from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ['username', 'email', 'password', 'profile_image', 'api_key'] extra_kwargs = {'password': {'write_only': True}, 'id': {'read_only': True}} def update(self, instance, validated_data): instance.username = validated_data['username'] instance.email = validated_data['email'] instance.api_key = validated_data['api_key'] instance.profile_image = validated_data['profile_image'] instance.save() return instance def create(self, validated_data): verification_code = random.randint(100000, 999999) user = CustomUser.objects.create(username=validated_data['username'],email=validated_data['email'], password=make_password(validated_data['password']), verification_code=verification_code) user.set_password(validated_data['password']) user.save() email = EmailMessage( 'Hello', f'This is your verification code : {verification_code}', 'email@gmail.com', [validated_data['email']] ) email.fail_silently=False email.send() return user I … -
handle many html files with React and Django
I have a hybrid django+react implementation. Django renders the initial HTML, then react takes control. However, the URLs are managed by Django. In react, the index.js file is supposed to correspond with one html right? Please correct me if I'm wrong. So, which is the correct approach if I have several HTML files that need react. My index.js file looks like this: import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import { EfestoComponent, WorkTimeComponent, AresComponent } from './components/pulseHome'; import { PulseComponent} from "./components/pulseHistory"; import reportWebVitals from './reportWebVitals'; const efestosData = JSON.parse(document.getElementById('efestos-data').textContent); const efesto = ReactDOM.createRoot(document.getElementById('efesto')); const worktime = ReactDOM.createRoot(document.getElementById('worktime')); const ares = ReactDOM.createRoot(document.getElementById('ares')); const pulse = ReactDOM.createRoot(document.getElementById('pulse')); efesto.render( <EfestoComponent objects={efestosData}/> ); worktime.render( <WorkTimeComponent/> ) ares.render( <AresComponent/> ) pulse.render( <PulseComponent/> ) As you can see, the efesto, worktime and ares components belong to 1 js file called pulseHome, it holds the components for a file called pulse_home.html. Then the pulse component lives in a pulseHistory js file which holds the components for a pulse_history.html. When I visit any of the two htmls, it raises the error: Uncaught TypeError: document.getElementById(...) is null of course, since the first elements are not present in the second html, and vice versa. I could … -
Understanding django grafana dashboard
I am trying out django dashboards for grafana. I imported a dashbord from grafana.com. One of the panels looks like below: I am unable get the meaning of the information shown by the graph. Naively, I believe it is meant to show average request latency for the selected duration. But then what does it mean by 50th quantile here? Also what is meant by by (le) here? -
Keyerror in django restframework
Views.py class EventCalenderEventListView(ListAPIView): permission_classes=[AllowAny,] serializer_class = serializer.EventCalenderSerializer def get_queryset(self, *args, **kwargs): data = json.loads(self.request.GET.get('filter')) category = data.get('category') query_list = Event.objects.all().values('start_date').distinct() date_list = [] for i in query_list: for key, value in i.items(): date_list.append(datetime.datetime.strftime(value,'%Y-%m-%d')) datas = [] result = {} for dates in date_list: result[dates]= [] query = Event.objects.filter(start_date=dates).order_by('start_date') for i in query: result[dates].append(i) datas.append(result) result = {} return datas Models.py class Event(BaseFields): name = models.CharField(max_length=250) category = models.ForeignKey(EventCategory,on_delete=models.CASCADE,null=True,blank=True) other_event_category = models.CharField(max_length=250,null=True,blank=True) meeting_link = models.CharField(max_length=250,null=True,blank=True) description = models.TextField(null=True,blank=True) start_date = models.DateField(null=True,blank=True) end_date = models.DateField(null=True,blank=True) serializer.py class EventCalenderSerializer(ModelSerializer): category = SerializerMethodField() status = SerializerMethodField() class Meta: model = Event fields = fields=('id','name','category','start_date','end_date','status') def get_category(self, obj): category = {} if obj.category: category['id'] = obj.category.id category['name'] = obj.category.name return category else: category = "" return category def get_status(self,obj): current_date = datetime.strftime(datetime.today(),'%Y-%m-%d') start_date = datetime.strftime(obj.start_date,'%Y-%m-%d') if obj.end_date is not None: end_date = datetime.strftime(obj.end_date,'%Y-%m-%d') if start_date == end_date and start_date < current_date: return "completed" elif start_date < current_date and end_date < current_date: return "completed" elif start_date < current_date and end_date > current_date: return "progress" elif start_date == current_date: return "progress" else: return "upcoming" else: if start_date < current_date: return "completed" elif start_date == current_date: return "progress" else: return "upcomng" Expecting output: [{'2023-06-01':[{"name":event 1,"start_date":"2023-06-01","end_date":"2023-06-07"}], {'2023-06-01':[{"name":event 2,"start_date":"2023-06-01","end_date":"2023-06-07"}, {"name":event … -
Forms dynamique django
what I want my form to do is that when I select a student, for example, the "input" material disappears and gives way to the "input" sector. Hi, I have a problem that I can't solve, the problem is with the django form, what I want my form to do is that when I select a student, for example, the "input" material disappears and gives way to the "input" sector. I try but I can't help. -
How To stop git accessing my changes made in django project in vscode
I had pushed my django project into github from vscode,later i deactivated my virtual environment,but even after deactivating if i try to make any changes in my project it is asking me to apply local changes to git,how to prevent it?Please Help me To Solve this Issue i deactivated the virtual environment and made changes on my project,but it is still asking me to apply those changes to git.I dont want this changes to be applied to github,how to prevent it? -
JS element returns 'null' when retrieving value from textarea
For my project, I'm submitting a "tweet" form asynchronously, but I'm having trouble retrieving the textarea value to pass into my function and update the UI. The values from the tweet/post are saving to my models (including the tweet) and every other field in (username, user profile picture, tweet image) are displaying properly, but its just the textarea that's causing me problems and not displaying at all. Here is the relevant code for reference. Section of index.html <form id="tweet-form" method="post"> <div class="post-section-row"> <a class="creator" href="{% url 'change_profile' %}"> <img src="{{ user_profile.profile_picture.url }}" class="profile-pic small-post-section" > </a> <!-- Cannot retrieve value from this line --> <textarea id="post-content" name="tweet" placeholder="What's Happening?" oninput="autoExpand(this); checkCharacterCount(this)"></textarea> </div> <!-- To display tweet image preview and delete functionality --> <div id="tweet-picture-preview" style="display: none;"></div> <div class="post-section-row"> <div class="error-message"></div> <div class="tweet-actions"> <label for="picture" title="Upload Picture"> <span class="material-symbols-outlined">photo_library</span> <span class="tooltiptext">Upload Picture</span> <input type="file" id="picture" name="tweet-picture" class="file-input" accept="image/jpeg, image/png, image/gif, image/jpg" onchange="previewTweetImage(event)"> </label> <input type="submit" id="post-button" value="Post"> </div> </div> </form> JS file (code within DOMContentLoaded listener) tweetForm.addEventListener('submit', function(event) { event.preventDefault(); const csrftoken = getCookie('csrftoken'); const formData = new FormData(tweetForm); fetch("/post_tweet/", { method: "POST", body: formData, headers: { 'X-CSRFToken': csrftoken, }, }) .then(response => response.json()) .then(data => { console.log(data.message); // This returns … -
How to serve Files with Django Rest Framework
In my django app I have a "Incidence" model that has several FileField and ImageField. I want to create an endpoint with Django Rest Framework to retrieve the information about an "Incidence" but what I have done so far only retrieves the url of the files. I need to return the files in a format that can be downloaded by the client application like binary data or other suggestion. How can I do it? This is what I have done so far Model Definition: class Incidence(BasicAuditModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) geom = models.PointField(verbose_name=_("Localización"), srid=4326, blank=True, null=True) name = models.CharField(_("Nombre"), max_length=255) incidence_type = models.CharField(_("Tipo incidente"), max_length=50, choices=INCIDENCE_TYPE_CHOICES, default="tipo1") description = models.TextField(_("Descripción"), blank=True, null=True) status = models.CharField(_("Status"), max_length=50, choices=STATUS_CHOICES, default="creado") image1 = models.ImageField(verbose_name=_("Foto 1"), upload_to="incidencia_fotos", null=False, blank=False) image2 = models.ImageField(verbose_name=_("Foto 2"), upload_to="incidencia_fotos", null=False, blank=False) image3 = models.ImageField(verbose_name=_("Foto 3"), upload_to="incidencia_fotos", null=False, blank=False) audio = models.FileField(verbose_name=_("Audio"), upload_to="incidencia_audioa", null=False, blank=False) video = models.FileField(verbose_name=_("Video"), upload_to="incidencia_video", null=False, blank=False) def __str__(self): return self.name class Meta: db_table = 'sini_incidence' managed = True verbose_name = 'Incidencia' verbose_name_plural = 'Incidencias' class BasicAuditModel(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="+", verbose_name=_("Creado por"), null=True, blank=False, on_delete=models.SET_NULL) modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="+", verbose_name=_("Modificado por"), null=True, blank=False, on_delete=models.SET_NULL) created = models.DateTimeField(auto_now_add=True, verbose_name=_("Fecha creado")) modified = models.DateTimeField(auto_now=True, verbose_name=_("Fecha … -
django connecting to mysql in docker gets "wrong" IP address
I am attempting to connect to a remote mysql db from my dockerized django app. This works as expected: In [2]: pymysql.connect(host='remote-host.com', user='user', password='bogus') Out[2]: OperationalError: (1045, "Access denied for user 'user'@'172.XX.XX.XX' (using password: YES)") In [3]: pymysql.connect(host='remote-host.com', user='user', password='secret') Out[3]: <pymysql.connections.Connection at 0x401ef682b0> But this does not (from within django runserver): File "/usr/local/lib/python3.8/site-packages/pymysql/protocol.py", line 221, in raise_for_error err.raise_mysql_exception(self._data) File "/usr/local/lib/python3.8/site-packages/pymysql/err.py", line 143, in raise_mysql_exception raise errorclass(errno, errval) django.db.utils.OperationalError: (1045, "Access denied for user 'user'@'192.168.80.4' (using password: YES)") So somehow the shell-based connection is picking up a 172/ IP address for the client (presumably the docker bridge IP - it doesn't correspond to my laptop's en0 IP at any rate), where the exact same code, exact same connection params within runserver causes the mysql server to see the IP of the docker container. Anyone know what's going on, and more importantly how I can prevent it? Attempted: Well, not really much I can do since I don't have access to modify mysql's accepted host list or how it determines the client IP. Expected: The same IP address to be used in both connections. -
Django: Generating a file on page load and deleting it upon exit
Something I would like to do in my Django app is: every time a user views page A, grab information from my database, generate an image based off this and display it to the user. Since I am regenerating an image each time I view the page, I would like it to be unique to each user and deleted when they leave page A to go to any arbitrary page B (and ideally when they simply click x on the browser too, but if not that's okay). So far I can generate the image file and save it just fine. I have tried a few things unsuccessfully and can't figure out how to go forward. Things I have tried: @receiver(request_finished) @receiver(request_finished) def handle_request_finished(sender, **kwargs): ... clean up files here ... My issue with this one is that it happens too quickly and won't load the picture on page A because it will be deleted already. Using a JavaScript function that activates when leaving the page paired with a function in my views.py In template.html: <script> $(window).on('beforeunload', function () { $.ajax({ url: pageLeaveUrl, // links to page_leave function in views.py type: 'GET', async: false // Ensure the request completes before page …