Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Overriding TinyMCE Styling after using dangerouslySetInnerHTML
I have a dynamic page with a lot of text in RTL format. TinyMCE cannot display the RTL text properly. It shows up something like this: While I want it to be displayed like this: Searching for a solution, I found out that dangerouslySetInnerHtml will help me get the text clean, however, I cannot get my desired formatting for the dynamic text. The code is as follows: const getWelcomeText = () => { return( <div> {texts.map((data, index) => ( <div className='backgroundnawishta'> <p className='title'> {data.title} </p> <p className='para' dangerouslySetInnerHTML={{__html: data.body}} /> </div> ))} </div> ) } and the css styling. .para{ font-size: clamp('1.5rem, 2vw, 5rem !important') ; line-height: clamp('2rem, 4vw, 5rem !important') ; font-family: titr !important; text-align: center !important; direction: rtl !important; color: #112D4E; padding: 0 !important; margin: 0 !important; text-shadow: 2px 2px #ffffff !important; } Is there a way for me to get clean text without using dangerouslySetInnerHTML or Can I override TinyMCE styling? -
Django, website with changed prefix, how to fix urls globally
I recently deployed my app locally with the help of Apache. I use server name and sufix to get to the content as http://my-server/app. The Problem is every button ignores what the root of my app is. So from my main view at my-server/app I try to redirect to /second_page and it sends me to server/second_page instead of server/app/second_page. Do I have to change every form by hand or is there any way to configure it through settings.py or urls.py? -
Django: how to update django models every couple of minutes
I am building an app, where I need to fetch some data from a website likes a news website or articles website, add it to my django models and update all the models with that data every few minutes, let's say every 15 minutes. What would be a clean and clear way to accomplish something like this? How do i requests data from external sources, let's say bbc.com How do i add these to my models automatically How would i update the models every 5 minutes I need a guide on how to accomplish this task? -
Django media image file is not displaying in template
I have a problem with media files in Django 4.0.4, here are the code and some screenshots to understand the problem : Settings.py STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / 'staticfiles' MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('sites_events.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py photo = models.FileField() # I'm not able to use ImageField, I have troubles setting up Pillow. index.html {% load static %} <h1>{{ object.title }}</h1> <p>{{ object.description }}</p> <p>link: {{ object.link }}</p> <p>Category: {{ object.category }}</p> <p>Date: {{ object.date_time|date }} at {{ object.date_time|time }}</p> {% for photo in photo_list %} {{photo.photo.url}} <img scr="{{ photo.photo.url }}" width="250" height="250"> {% endfor %} If I copy the img src url, For example (http://127.0.0.1:8000/media/canvas_gb9uMM8.png), the image is well displayed. Thank you for your help. -
Standalone application in Django
I'm studying in Coursera. I like Django models and instruments and want to use it in my standalone Python application. How I can do in Django project? So my application must be leading and work not as request handler as all apps in Django, but in "pooling" mode. -
Why new pulled code from git not applied when Gunicorn running on ubuntu server?
I have a django project on ubuntu server that works with Nginx and Gunicorn correctrly. I change some django code and push on git server and then pull from git server on ubuntu server. It seems new changes not implemented on server. How to fix it? I restart and reload Gunicorn and Nginx but not happend. -
DRF create serializer for nested OneToOnefield
I have some Models that have OnetoOnefield in it. Question how can I update them to create serializer method, and create all fields in ModelB and ModelC thought OnetoOnefield Models: class ModelA(models.Model): name = models.TextField() class ModelB(models.Model): description = models.TextField() record = models.OneToOneField(ModelA) class ModelC(models.Model): name = models.TextField() link = models.OneToOneField(ModelB) Serializers: class RecordSerializer(ModelSerializer): link = LinkSerializer() class Meta: model = ModelB fields = '__all__' class TestSerializer(ModelSerializer): record = RecordSerializer() class Meta: model = ModelA fields = '__all__' def create(self, validated_data): record_data = validated_data.pop('record') record = RecordSerializer.create(RecordSerializer(), validated_data=record_data) modelA, created = ModelA.objects.create(record=record) return modelA View class TestViewSet(ListModelMixin, RetrieveModelMixin, CreateModelMixin, GenericViewSet): permission_classes = [IsAuthenticated] serializer_class = TestSerializer queryset = ModelA.objects.all() -
Django Channels. How to create a variable (or a object) that can live only during the WebSocket?
I have a websocket and i want to create a global variable that lives during all the life time of the websocket itself. The main issue is that the variable is actually shared between all the client that connect to the websocket while i need it to be specific to the single client. Do you know any possible solution? -
How to set tls version in Django database settings
I have an application deployed on azure, with the new releases I want to increase minimum tls version to 1.2 Python version 3.8 production MySQL version is 8.0.15 When we increase it from the mysql server app crashes and gives us the following error exception when mysql server increases the minimum tls version Here is my database connection settings DATABASES[database_name] = { 'ENGINE': 'django.db.backends.mysql', 'NAME': database_name, 'USER': os.getenv("DB_USER"), 'PASSWORD': os.getenv("DB_PASSWORD"), 'HOST': os.getenv("DB_HOST"), 'OPTIONS': { 'ssl': {'ssl-ca': 'configs/public-azure-mysql-certificate.pem'} } I tried adding an additional field like this under the 'ssl' option field like this import ssl later in the code DATABASES[database_name] = { 'ENGINE': 'django.db.backends.mysql', 'NAME': database_name, 'USER': os.getenv("DB_USER"), 'PASSWORD': os.getenv("DB_PASSWORD"), 'HOST': os.getenv("DB_HOST"), 'OPTIONS': { 'ssl': {'ssl-ca': 'configs/public-azure-mysql-certificate.pem', 'ssl-version': ssl.PROTOCOL_TLSv1_2} } it gives the same error as well, How can I set the TLS version to 1.2 so that I can set mysql server to accept minimum TLSv1.2 ? Thanks! -
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)