Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Can't specify STATICFILES_DIRS correctly in Django
I'm getting the warning: (staticfiles.W004) The directory 'C:/frontend/build' in the STATICFILES_DIRS setting does not exist. It seems like i'm not able to reference my react build folder correctly, all this happened after trying to move django api folders. Here is what my folders look like: enter image description here And here's how my path related setting look like in my settings.py import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(BASE_DIR, "frontend/build")], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ STATIC_URL = "static/" # Default primary key field type # https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" STATICFILES_DIRS = [ os.path.join( BASE_DIR, "/frontend/build") ] I've tried debugging my settings.py, it seems like the BASE_DIR is never set correctly, im not able to understand os.path.join -
Django Admin - Add a tabularInline section referred to another class (without foreign key)
I'm developing a Django Admin interface for a sort of ecommerce. I have some database model linked using foreign key. In Django Admin interface, I want to show a TabularInline section inside Customer page to show me all items buyed by a specific customer but I have a classic error about "foreign key" because Customer model and OrderItems model are not directly linked. class Customer(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) name = models.CharField(max_length=150) mobile = models.CharField(max_length=20, blank=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] class Meta: verbose_name = "Account" verbose_name_plural = "Accounts" def email_user(self, subject, message): send_mail( subject, message, 'l@1.com', [self.email], fail_silently=False, ) def __str__(self): return self.email class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="order_user") full_name = models.CharField(max_length=50) email = models.EmailField(max_length=254, blank=True) address1 = models.CharField(max_length=250) address2 = models.CharField(max_length=250) city = models.CharField(max_length=100) phone = models.CharField(max_length=100) postal_code = models.CharField(max_length=20) country_code = models.CharField(max_length=4, blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) total_paid = models.DecimalField(max_digits=5, decimal_places=2) order_key = models.CharField(max_length=200) payment_option = models.CharField(max_length=200, blank=True) billing_status = models.BooleanField(default=False) class Meta: ordering = ("-created",) def __str__(self): return str(self.created) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name="items", on_delete=models.CASCADE) product = models.ForeignKey(ToolTable, related_name="order_items", on_delete=models.CASCADE) price = models.DecimalField(max_digits=5, decimal_places=2) … -
Get param on anothe page and edit : Vue-Axios-Django-Python
I would like to retrieve the data passed as a parameter via the route and make one of the modifications, but I can't. This is my Python-Django code # CompanyApi @csrf_exempt def companyApi(request, id=0): if request.method == "GET": companies = Companies.objects.all() # companies = Companies.objects.first() # companies = Companies.objects.order_by("company_id").first() companies_serializer = CompanySerializer(companies, many=True) # companies_serializer = CompanySerializer(companies) return JsonResponse(companies_serializer.data, safe=False) elif request.method == "POST": company_data = JSONParser().parse(request) companies_serializer = CompanySerializer(data=company_data) if companies_serializer.is_valid(): companies_serializer.save() return JsonResponse("Added Successfully", safe=False) return JsonResponse("Failed to Add", safe=False) elif request.method == "PUT": company_data = JSONParser().parse(request) company = Companies.objects.get(company_id=id) # company = Companies.objects.get(company_id=company_data["company_id"]) companies_serializer = CompanySerializer(company, data=company_data) if companies_serializer.is_valid(): companies_serializer.save() return JsonResponse("Updated Successfully", safe=False) return JsonResponse("Failed to Update") elif request.method == "DELETE": company = Companies.objects.get(company_id=id) company.delete() return JsonResponse("Deleted Successfully", safe=False) This is my code is my CompanyEdit page <script setup> import axios from "axios"; import { computed, ref, onMounted, reactive } from "vue"; import { useRoute } from "vue-router"; import CardBoxModal from "@/components/CardBoxModal_JTO.vue"; import FormField from "@/components/FormField.vue"; import FormControl from "@/components/FormControl.vue"; import BaseButton from "@/components/BaseButton.vue"; import SectionMain from "@/components/SectionMain.vue"; import CardBoxWidget from "@/components/CardBoxWidget.vue"; import CardBox from "@/components/CardBox.vue"; const modalOneActive = ref(false); const form = reactive({ company_id: "", company_name: "", company_email: "", company_phone: "", company_address: "", company_city: "", … -
Django signal when model instance with custom field is deleted?
I've got a custom model field in my Django app: secret = VaultField(max_length=200) This takes the value passed and saves it to HashiCorp Vault and stores the path to it in the database, and retrieves it from Vault when accessing. That's all good, I can use this on many models. But now when I delete an instance of a model it doesn't delete it from Vault. I could add a post delete signal on all models that have the VaultField field, but that seems like a lot of duplicate work. Is there anything to add in the class VaultField(CharField): class? Or maybe a post delete signal just on a field being deleted? -
Django or Javascript/Node: learning times in relation to difficulty?
I've been using Python for years, but always for desktop apps. I know Html, Css and little Javascript, but I've never programmed in backend for websites. I would like to learn Django, but having a look I found it very difficult. Knowing Python well and knowing little about Javascript, does it take less time to learn Django from scratch to carry out projects of medium difficulty, or does it take less time to learn Node.js from scratch with Express? (also considering the time to learn Javascript at least sufficiently)