Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest CORS Permissions Default
I am in the process of building a React App to talk to Django as the backend via the Django Rest Framework. I have installed the relevant packages and am trying to configure my default behavour when accessing the views to block access and have the following in my settings.py file REST_FRAMEWORK = { 'DEFAULT_PREMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', ] } My view access the data is: from django.shortcuts import render from django.http import JsonResponse from .models import Articles from .serializers import ArticleSerializer # Create your views here. def articles_list(request): articles = Articles.objects.all() serializer = ArticleSerializer(articles, many=True) return JsonResponse(serializer.data, safe=False) def get_article(request, articlename): article = Articles.objects.get(name=articlename) serializer = ArticleSerializer(article, many=False) return JsonResponse(serializer.data, safe=False) Am I missing something completely simple as I can still access this when when not currently authenticated to the Django backend. Thanks -
Django: django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: account
I want to use django-helpdesk (which uses account) with django-allauth (which uses allauth.account). Obviously these conflict. I already have a forked version of django-allauth and I don't want to change any code as I am using the forked package in other projects. Is there any way I can change the app label of django-allauth without modifying source code? -
How to have a 'Folder' ForeignKey sorted by folders and subfolders
I have models for scripts and folders, with the scripts inside the folders. When registering a new script (or modifying an existing one) in the Django Admin page, the folders are not represented as folders and subfolders, but rather all at the same time under the form of a list, without anything to distinguish which one is a parent or a child of another one in the list. What I want is to have them clearly ordered, with subfolders underneath their parent (Or atleast display the path from the root folder instead of just the name of the folder to be able to tell where they are if what I want is not possible). I hope I'm clear, but to try explaining differently, have like a ChoiceField with the following choices : FOLDER_CHOICE= [ ('Folder1', ( ('folder1-1', 'Folder1-1'), ('folder1-2', 'Folder1-2'), ) ), ('Folder2', ( ('folder2-1', 'Folder2-1'), ('folder2-2', 'Folder2-2'), ) ) ,... ] The code of the models.py class : import importlib.util import os import shutil import types from django.db import models from django.urls import reverse from django.utils.html import format_html class Folder(models.Model): folder_name = models.CharField(max_length=200, unique=True) parent_folder = models.FilePathField(path=r'media/', allow_files=False, allow_folders=True, recursive=True) def __init__(self, *args, **kwargs): super(Folder, self).__init__(*args, **kwargs) self.initial_folder_name = … -
Delete folder or directory using API (django)
I have written down a Python script to delete or remove a folder from file directory. The code is below: import os import sys import shutil base_dir = os.path.dirname(os.path.realpath(__file__)) path = 'media/user110' try: path = os.path.join(base_dir, path) shutil.rmtree(path) print("Deleted: " + path) except OSError as e: print("Error: %s - %s." % (e.filename, e.strerror)) This worked. But it's not working in API using Django. If I print path it shows '/home/Desktop/my_project/media/user110/ But when I want to do this in API using Django, using same code, and print path I got /media/user110/ and it throw an Exception saying this directory doesn't exist Now I want to delete or remove file directory using API. I want the solution. BTW, I am using Linux, and my project will deploy in Linux server. -
Django Custom Vlaidation For Boolean Field not working
the validation is not working for the boolean field in django, models.py product_filed = models.BooleanField(default=False) def clean(self): if (self.product_field is not None) < 1: raise ValidationError( { "product_field": _(" Product field can be select once") } ) -
How can I extract timestamps from this formats?
I have certain strings like Bert interview starts (4:00) 4:32 Understanding VC fund metrics Magic of being a fan (1:20:50) How can I get timestamps from this? -
Mocking a method_decorator in django pytest?
I need a bit of guidance on the correct way to mock a method_decorator for a dispatch function. I have a method_decorator that appends log to a log file. I want to mock the method_decorator(log_request) for the dispatch function in my view. Tried to patch it but it doesn't seem to work. What could I be doing wrong ? class DummyView(APIView): serializer_class = DummySerializer @method_decorator(log_request) def dispatch(self, *args, **kwargs): return super(DummyView, self).dispatch(*args, **kwargs) class TestCustomersView: @patch("dummy.api.create_dummy") @patch("dummy.api.log_request") def test_dummy_view(self, mock_log_request,mock_create_dummy): post_data = dict(first_name="Test") mock_log_request.return_value = "Ok" mock_create_dummy.return_value = {"id": "12345", "First_Name": "Test"} req = RequestFactory().post("/api/dummies/", data=post_data) response = DummyView.as_view()(req) -
drf_yasg only renders filterset parameters on list view
I have defined a filterset for a DRF ViewSet. drf_yasg correctly renders all the filterset fields as parameters in Swagger for the list endpoint, but not for any other endpoints. Any idea why? views.py: from rest_framework import mixins, viewsets from django_filters import rest_framework as filters from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema from my_app.models import MyModel from my_app.serializers import MySerializer class MyFilterSet(filters.FilterSet): class Meta: model = MyModel fields = { "status", } class MyViewSet( mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet, ): filter_backends = (filters.DjangoFilterBackend, ) filterset_class = MyFilterSet queryset = MyModel.objects.all() serializer_class = MySerializer -
Django authentication to Cloud SQL postgresql through GCP IAM
I am setting up a Django project on GCP and I just created a Cloud SQL instance with IAM authentication. I have CloudSQL proxy set up to allow me to connect from my local machine. Unfortunately, when it comes to setting up the Django backend connection, there's only third-party packages for AWS IAM. Has anyone here managed to connect to a CloudSQL instance with GCP IAM? -
Error: [@formatjs/intl Error MISSING_TRANSLATION] Missing message: "currentStage." for locale "he", using id as fallback
so im trying to get data from DB, but i get this error and i dont know how to fix it. this is where im fetching the data - this is where im trying to print it - this is my he.json file constants - everything is printed but with error - -
How to Auto Approve After Some particular time in Django
class LeaveTable(models.Model): emp_name = models.CharField(max_length=50,null=True) emp_id = models.CharField(max_length=50, null=True) leave_type = models.CharField(max_length=50,null=True) applied_date = models.DateTimeField(null=True,blank=True) start_date = models.DateField() end_date = models.DateField() no_days = models.IntegerField() agent_reason = models.TextField(null=True) tl_approval = models.BooleanField(default=False) manager_approval = models.BooleanField(default=False) final_status = models.BooleanField(default=False) I want to make tl_approval, manager_approval and final_status as True automatically after 48 Hours from applied_date if it is False. I can Write the function in views.py to do same but how will it be triggered that function automatically after 48 Hours? -
How can I export a function return in Django
I have a function called on_loading_booking_deal return a dic and I am interested to use the amount key and I want to export it to use it in another file @receiver(loading_deal, sender=Booking) def on_loading_booking_deal(deal_id: str, load_company: bool = False, **kwargs): deal = get_deal(deal_id) if not deal: return None formatted_deal = { 'id': deal_id, 'amount': get_entity_property(deal, 'amount'), 'occupational_use': get_entity_property(deal, 'occupational_use') } contact = None if len(deal['associations']['associatedVids']) > 0: contact = get_contact(deal['associations']['associatedVids'][0]) if not contact: logger.warning("Unable to load hubspot contact") if contact: formatted_deal['contact'] = { 'first_name': get_entity_property(contact, 'firstname'), 'last_name': get_entity_property(contact, 'lastname'), 'email': get_entity_property(contact, 'email'), 'type_of_business_model': get_entity_property(contact, 'type_of_business_model') } if load_company: company = None if len(deal['associations']['associatedCompanyIds']) > 0: company = get_company(deal['associations']['associatedCompanyIds'][0]) if not company: logger.warning("Unable to load hubspot company") if company: formatted_deal['company'] = { 'name': get_entity_property(company, 'name') } print(f"Loaded deal {formatted_deal['amount']}") return formatted_deal ## I want to export this return into another folder/file -
why django-split-json-widget can't use in my model.form
i have tried many times, but it seems like the widget didn't work. There's nothing in my page. I use jsonfield to save the data with json, now , i want to tranform these json data into html input form, and i have found the django-split-json-widget. I've tried to use but i don't know what's the problem views.py class Message(models.Model): myQOS = ( ('0','0'), ('1','1'), ('2','2'), ) name = models.CharField(max_length=200, null=True) description = models.CharField(max_length=300, null=True) topic = models.CharField(max_length=300) qos = models.CharField(max_length=200, choices=myQOS, null=True) retain = models.BooleanField(null=True) payload =jsonfield.JSONField(null=True) def __str__(self): return self.name forms.py class MessageForm(ModelForm): def render(self, name, value, attrs=None): attrs = {'class': 'special', 'size': '25'} data = forms.CharField(widget=SplitJSONWidget(attrs=attrs, debug=True)) class Meta: model = Message fields = ('name','description', 'topic', 'qos', 'retain') views.py def Update_Message(request, pk): messages = Message.objects.get(pk=pk) json = messages.payload messageform = MessageForm(request.POST or None, instance=messages, initial={'data': json}) print(messageform.data) context = {'messageform' : messageform} if request.method == 'POST': if messageform.is_valid(): Mesform = messageform,save(commit=False) Mesform.payload = messageform.cleaned_data['payload'] Mesform.save() return redirect('/Update_Message/{}'.format(messages.id)) return render(request, 'apps/Update_Message.html',context) html <a href="{% url 'MessageList' %}">back to list</a> <form method="POST"> {% csrf_token %} {{ messageform.payload }} <input type="submit" value='Update' class="buttonupdate"> </form> -
ImportError: cannot import name '..' from partially initialized module '..' (most likely due to a circular import)
I have an app with a form that has been working fine until now. I'm not sure what I did to cause this error since it's been working fine for months now. I've tried changing the file names, where I import the models, nothing is working I'm attaching relevant parts of my code : This is my models.py class SingleEnd(models.Model): file = models.FileField(upload_to='documents/') email = models.CharField(max_length=100) def __str__(self): return self.email THis is my forms.py from app.models import SingleEnd class SingleEndForm(forms.ModelForm): class Meta: #shows which model to use from models.py model = SingleEnd #fields = 'all' fields = ['file', 'email'] labels = { 'file': 'input your fasta/fastq file (min 3 sequences)', 'email':'input your email to get a notification for your results in a timely manner', } widgets = { 'email':forms.EmailInput(attrs={'class':'form-control'}), 'file':forms.FileInput(attrs={'class':'form-control'}), } This is my views.py #defines a view function def snippet_detail(request): #path to save inputs media_path = "/home/project/media/documents/" #path to save outputs result_path = '/home/project/media/results' max_timeout = 1246060 #dayshoursminssecs #dictionary-like object that uses form data if request.method == 'POST': #use the form to upload form info (post) and files form = SingleEndForm(request.POST, request.FILES) if form.is_valid(): #saves full form form = SingleEndForm(file=request.FILES['file']) form.save() #changes file name if the name is the … -
404 Error message in Django after hitting the submit button
I got a the following error in Django after clicking the submitbutton in the browser: Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/send Using the URLconf defined in contactform.urls, Django tried these URL patterns, in this order: admin/ [name='index'] The current path, send, didn’t match any of these. i have two urls in my code. They are: django.urls import path from . import views urlpatterns = [ path('', views.index, name="index"), ] and from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls')), ] How can i solve this? I Hope that you have a solution to this problem. Kind Regards Win -
how to post data of two models in single view.py using serializer? django rest framework
Suppose I've 2 models created namely: booking and passenger. Both have a relationship of Many-to-many. Now, without using a nested serializer, how do I use both models' serializers to post data inside DB? model.py class Passenger(models.Model): name = models.CharField(max_length=100,blank=True, default='') contact_number= models.IntegerField() email = models.EmailField(max_length=254) gender = models.IntegerField(choices=GENDER_CHOICES) age= models.IntegerField() user=models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.name class Booking(models.Model): user =models.ForeignKey(User,on_delete=models.CASCADE) flights =models.ForeignKey(Flight,on_delete=models.CASCADE) **passenger =models.ManyToManyField(Passenger)** booking_number= models.IntegerField(default=0, blank= True) booking_time = models.DateTimeField(auto_now=False, auto_now_add=False) no_of_passengers= models.IntegerField(default=0, blank= True) def __str__(self): return self.booking_number and the Corresponding serializer serializer.py class PassengerSerializer(serializers.ModelSerializer): class Meta: model= Passenger fields = '__all__' class BookingSerializers(serializers.ModelSerializer): class Meta: model= Booking fields = '__all__' Now what I've to do is that in views.py I'm creating "class BookingAPIView(APIView):" NOw in this I've to use POST method def post(self, request, format=None): bookserializer = BookingSerializers(data=request.data) passengerserializer = PassengerSerializer(data=request.data) HOW to save data from both serializers in this single POST method? view.py class BookingAPIView(APIView): def get(self, request, format=None): bookings = Booking.objects.all() serializer = BookingSerializer(bookings, many=True) return Response(serializer.data) def post(self, request, format=None): bookserializer = BookingSerializers(data=request.data) passengerserializer = PassengerSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Create and persist service object in root of django app
I've created a basic django app that has a custom library installed (uses Asyncio). I need to instantiate a factory class from the library and then use it to get some service objects back to use in the app. creds = load_creds('./creds.json') async with TestFactory(creds) as factory: tickets = factory.get_ticket() results = await tickets.find_by_number('IN12345678') print (results.ticket_group) I've only been looking at Django for the last few days. So I'm not sure where is best to place this code. I just need it to persist the service objects I'm generating from the factory class and make them accessible to the rest of the app for as long as the app is running i.e. scaffold once, always accessible. From a c# perspective, I could do this during app startup and pass it down via DI. -
Django Ajax success send context in new url
I have a first page with a Launch button, the process is done and them all is redirect to a result page where I can download the different results. Without Ajax and with "regular" Django, the process is working. However, because of other functionalities in the first page, I have to work with Ajax. And if I do not redifined the success part of Ajax, nothing is appenning.. I have a function view for the first page : def launchCtd(request): """ This Function is activate when user click on the launch button of the convertToDose page. It receive the request, create the JSON file and launch the ConvertToDose Analysis. Then it redirect to the Result page """ if request.method == 'POST': #DO stuff context = { 'filename': img_out_path, 'protocol_file': json_pactrlRectth, } #return render(request, 'result.html', context) return JsonResponse(context, safe=False)# I trie to pass the url but it was not a success... else: #Ini Forms context = { #Send Forms } return render(request, 'template.html', context) the template of the first page (only ajax part) $.ajax({ url: "", type: "POST", data: formData, processData: false, contentType: false, beforeSend: function (xhr, settings) { xhr.setRequestHeader("X-CSRFToken", $('input[name="csrfmiddlewaretoken"]').val()); }, success: function(data){ //print okay with JSONResponse in view console.log(data.protocol_file) … -
Django REST framework: Serializer to use max_length from model
I have a model class Person(models.Model): name = models.CharField(max_length=254) and related serializer class PersonSerializer(serializers.Serializer): name = serializers.CharField(max_length=254) Is there a way to make CharField automatically detect max_length from the model and use that in validation? Using Person._meta.get_field('name').max_length could be an option but feels a bit cumbersome to be used in every field. Maybe overriding CharField with custom implementation? Or is there other options? -
Django REST view + celery
I would like to create a new GET or POST endpoint (which will be better?) to run specific celery task. In JSON body I will provide a text, and depends of this text the needed task will be launched. If in body I will provide - 'first', then task generate_first_results will be launched. If 'second', then generate_second_results will be launched. If 'third', then generate_third_results will be launched. I have created: urls.py router.register('get_results', views.ResultsViewSet, basename='get_results') views.py class ResultsViewSet(viewsets.ViewSet): def get(self, request): logger.info('Running results') try: # need to make a separation depending of the body generate_first_results.delay() generate_second_results.delay() generate_third_results.delay() return Response(status=status.HTTP_202_ACCEPTED) except Exception as e: logger.debug('Failed', e) return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) -
How to use __ (double underscore) in SQLAlchemy query like django ORM
I have 3 models @dataclass class Plans(db.Model): id = db. Column(db.Integer, primary_key=True, autoincrement=False) name = db.Column(db.String(100), nullable=True,) feature = db.relationship('PlanFeatures', backref = 'planfeatures') def __str__(self): return str(self.name) @dataclass class PlanFeatures(db.Model): id = db. Column(db.Integer, primary_key=True, autoincrement=False) plan_id = db.Column(db.Integer, db.ForeignKey('plans.id')) feature = db.Column(db.String(100), nullable=True,) plan = db.relationship('Plans', backref ='planfeatures') def __str__(self): return str(self.feature) @dataclass class UserPlans(db.Model): id = db. Column(db.Integer, primary_key=True, autoincrement=False) plan_id = db.Column(db.Integer, db.ForeignKey('plans.id')) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=True,) def __str__(self): return str(self.plan_id) In Django For example plan_of_user=UserPlans.objects.get(,plan__plan_features__feature=feature_choice) where feature_choice is my value. How to write a query filter equivalent to this in flask SQLAlchemy? Thanks in advance -
django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found
Tried all the possible suggested ways available on the internet based on my research but still got the same error. Error : django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') Kindly refer to the codes below. views.py def home(request): if request.method=="POST": con=pyodbc.connect( r'Driver={ODBC Driver 17 for SQL Server};' r'Server=srver;' r'Database=data;' r'USER=admin;' r'PASSWORD=1234;' ) cursor=con.cursor() cursor.execute("select Email, EmployeeID from [data].[dbo].[profiles] where EmployeeID='45678'") result=cursor.fetchall() cursor.close() return render(request, 'index.html',{'databasecon':result}) models.py from django.db import models # Create your models here. class databasecon(models.Model): empid=models.CharField(max_length=8) email=models.CharField(max_length=50) settings.py DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'data', 'USER':'admin', 'PASSWORD':'1234', 'HOST':'PROD123', 'PORT':'8000', 'OPTIONS':{ 'driver':'ODBC Driver 17 for SQL Server', 'isolation_level':'READ UNCOMITTED' #to prevent deadlocks } } } -
dj-rest-auth token not deleted in backend after logout
I started using the django dj-rest-auth package with react and i ran across the following issue: When i logout it will clear the key inside the local storage but not inside the Django backend. When i go to the API endpoint page and click the "send post request" button it will do it, but it won't do it when i use my frontend to logout. This is the code i'm using to accomplish this: navbar.js import { useContext } from "react"; import { Link, useNavigate } from "react-router-dom"; import axios from "axios" import { AuthContext } from "../contexts/AuthContext"; import { API } from "../api" export function Navbar() { const { user, logout } = useContext(AuthContext) const navigate = useNavigate() function handleSubmit() { axios.post(API.auth.logout) .then(res => { logout() navigate('/login') }) } api.js const baseURL = "http://127.0.0.1:8000" const apiURL = `${baseURL}/api` export const API = { auth: { login: `${baseURL}/dj-rest-auth/login/`, logout: `${baseURL}/dj-rest-auth/logout/`, passwordReset: `${baseURL}/dj-rest-auth/password/reset/`, passwordResetConfirm: `${baseURL}/dj-rest-auth/password/reset/confirm/`, signup: `${baseURL}/dj-rest-auth/registration/`, verifyEmail: `${baseURL}/dj-rest-auth/registration/verify-email/` } } app.js import React, { useContext } from "react"; import { BrowserRouter as Router, Routes, Route, Navigate } from "react-router-dom"; import { AuthContext, AuthContextProvider } from './contexts/AuthContext' import { Login } from './components/Login' import { Reset } from './components/Reset' import { … -
Combining custom django crispy forms' FormHelper and HttpResponse with context
I am working on a django project with an app which has lots of related fields like ForeignKey and ManyToManyField. There is a Model that I can call it "OriginModel" for I can access all other models through it. I've tried to render this model with a template and form using context but it seems like not manageable or hard to manage further changes and additions. Because I was hardcoding one OriginModel's all relations in a template. I've changed my method by using inclusive tags for repeating relations but I think it's a bad practice for manageability reason once again for my case. So I've changed my method again. I've tried crispy forms' FormHelper and Layout classes to create OriginModel's form. But I've faced a problem: I couldn't populate related fields with this method. Only OriginModel's direct fields (like "initials" in the code below) could be rendered. And after this failure I coded classes like FormHelper and Layout but my classes have functions to return html string just like my template file, so those are like HTML generators with extra steps I think. Because these classes have been built to return html ultimately, I used HttpResponse in the view of … -
How to color in region based on postal code using Leaflet?
I'm trying to color in an entire region on my map based on a Postal Code. So I want the entire postal code region to be colored in basically. I am using the plugin Leaflet for this. Right now I display circles on the map (Click the link to see): Current Map This is the JS code I am using to display it: $(document).ready(function(){ /* Initialising the map */ var map = L.map('map').setView([50.84673, 4.35247], 9); L.tileLayer('https://tile.openstreetmap.be/osmbe/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors' + ', Tiles courtesy of <a href="https://geo6.be/">GEO-6</a>', maxZoom: 18 }).addTo(map); var popup = L.popup(); function onMapClick(e) { popup .setLatLng(e.latlng) .setContent("You clicked the map at " + e.latlng.toString()) .openOn(map); } map.on('click', onMapClick); // Fetching the postal codes for each representative $.ajax({ url: dynamicmapurl, method: "GET", dataType: 'json', beforeSend: function(xhr, settings) { if(!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, success:function(data) { data = data.reverse(); for(var i = 0; i < data.length; i++){ //Drawing a circle on the map based on the //Postal code dictionary array I'm receiving from the backend L.circle([data[i].lat, data[i].lon], 500, { color: data[i].fillColor, fillColor: data[i].fillColor, fillOpacity: 0.8 }).addTo(map).bindPopup("Vertegenwoordiger: " + data[i].vertegenwoordiger + " <br> " + " Postcode: " + data[i].postcode) } }, error: function(data){ console.log(data); …