Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - have multiple MEDIA_ROOT and MEDIA_URL
I've configured both MEDIA_ROOT and MEDIA_URL and this works perfectly fine. My MEDIA files stored in a directory named /media/, now I want to store newly uploaded files to a new directory (for ex. /media2/) without breaking previous files. For example I had a Book model like this: class Book(models.Model): # name # author cover = models.ImageField() Now imagine I have 500 objects of Book model, so each cover has a path and url like this: url: http://example.com/media/books/thumb.jpg path: /home/myproj/media/books/thumb.jpg Now, I want to store covers for my newly created books in another directory, for ex. : url: http://example.com/media2/books/thumb.jpg path: /home/myproj/media2/books/thumb.jpg without breaking previous 500 books! How can I achieve this ?! (Django 3.1.2) -
Django error while use when using inherit models
I have 2 models that affect 2 tables in my database, Gen_Persona and Ven_Vendedor. The Ven_Vendedor table has the Gen_Persona primary key as its primary key. I have investigated and managed to make the representation through abstract models, however, when I try to make a query I get the following error: django.db.utils.ProgrammingError: column vendedor.gen_persona_ptr_id does not exist LINE 1: ...M "ven"."vendedor" INNER JOIN "gen"."persona" ON ("ven"."ven... I understand that the "ptr_id" refers to a pointer, but since I'm new to Django, I don't understand what change I should make. I hope you can give me feedback on it. Model Gen_Persona: class Gen_Persona(models.Model): prs_id = models.BigAutoField(primary_key=True,db_column='prs_id') prs_identificacion = models.CharField(max_length=16) prs_nombres = models.CharField(max_length=128) prs_apellidos = models.CharField(max_length=128) prs_razonsocial = models.CharField(max_length=256) prs_fechanac = models.DateField(blank=True, null=True) prs_email = models.CharField(max_length=64, blank=True, null=True) prs_telef1 = models.CharField(max_length=16, blank=True, null=True) prs_numtlf2 = models.CharField(max_length=16, blank=True, null=True) prs_numcel = models.CharField(max_length=16, blank=True, null=True) prs_img = models.CharField(max_length=256, blank=True, null=True) prs_dirprinc = models.CharField(max_length=128, blank=True, null=True) prs_dirsecun = models.CharField(max_length=128, blank=True, null=True) prs_dirnum = models.CharField(max_length=32, blank=True, null=True) emp_id = models.ForeignKey(Adm_Empresa, models.DO_NOTHING, verbose_name=Adm_Empresa._meta.verbose_name) prs_estado = models.SmallIntegerField(default=True) tid_id = models.BigIntegerField() class Meta: verbose_name='Persona' managed = False db_table = 'gen\".\"persona' unique_together = (('prs_id', 'emp_id'),) Model Ven_Vendedor : class Ven_Vendedor(Gen_Persona): prs_id_ven = models.OneToOneField(Gen_Persona, models.DO_NOTHING, db_column='prs_id_ven',related_name='fk_genpersona_venvendedor') ven_codigov = models.CharField(max_length=32,verbose_name='Código') ven_comision = … -
Download a document with Django
I am using an API and the return is a document. I want to be able to download it. I am currently using beautifulsoup but I don't think it can download it scrapes data via tags and the tag for the document viewer is embedded. Are there any other modules I can use to do the download? -
Django Model Form doesn't seem to validate the BooleanField
In my model the validation is not validating for the boolean field. my model.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") } ) -
Is there a way to solve this: django.template.library.InvalidTemplateLibrary: Invalid template library specified
Help is needed here. I deployed my application successfully to Heroku only to encounter this problem. It has to do with my template tags. It works just fine in development. I tried adding 'libraries': { 'courses_tags': 'courses.templatetags.courses_tags', } to the TEMPLATES dictionary in settings.py. Nothing is working. Help. Here is a screenshot from my Heroku log heroku log screenshot Any help would be appreciated. Cheers. -
Python Heroku "ModuleNotFoundError: No module named '_tkinter'"
I tried to deploy my app on heroku for free, but when I deployed it, and it returns an error that stated: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 21, in <module> remote: main() remote: File "manage.py", line 17, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/__init__.py", line 24, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate remote: app_config.import_models() remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models remote: self.models_module = import_module(models_module_name) remote: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 991, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked remote: File "<frozen importlib._bootstrap>", line 671, in _load_unlocked remote: File "<frozen importlib._bootstrap_external>", line 783, in exec_module remote: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed remote: File "/tmp/build_13ee9e32/web/models.py", line 1, in <module> remote: from turtle import exitonclick remote: File "/app/.heroku/python/lib/python3.8/turtle.py", line 107, in <module> remote: import tkinter as TK remote: File "/app/.heroku/python/lib/python3.8/tkinter/__init__.py", line 36, in <module> remote: import _tkinter # If this fails your Python … -
Django get_context_data doesn't work in templates
I am trying to loop over 2 queryes in a django template and only one works. I tried using get_centext_data method and alos the context_object_name variable and it doesn' t work. Code : class HomeView(LoginRequiredMixin, ListView): model = Resorts template_name = 'aplicatie2/home.html' context_object_name = 'high_rated_resorts' def get_queryset(self): return Resorts.objects.filter(rating__gte = 4.6) class VisitedListView(ListView): model = AdditionalInformationModel template_name = 'aplicatie2/home.html' context_object_name = 'visited_resorts_list' def get_queryset(self): return AdditionalInformationModel.objects.filter(user = self.request.user) the for loop using high_rated_resorts works, while a for loop over visited_resorts_list doesn't show anything. I tried using the same logic with get_context_data but with no luck. -
Django Rest Framework and celery tasks
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 celery 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 create(self, request, *args, **kwargs): logger.info('Running results') serializer = ResultsSerializer(data=request.data) 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) serializers.py class ResultsSerializer(serializers.Serializer): result = serializers.CharField(required=True): Please help -
In Django how to retrieve substring till ocurrence of a dot, from a model, to show in a template
I have the following model: class News(models.Model): news_text = models.TextField(null=True) ... # other fields with the following view: def news(r): news= News.objects values = {'news':news} return render(r,'webapp1/news.html',values) I want to show in the template a substring for the column news_text, till the first 'dot' occurrence, like: {{news.news_text| split('.')[0] }} Tried this in template but got: "invalid filter: 'split'". First post on stackoverflow ;) -
Django / Heroku application Error when switching from sqlite to posgresql's heroku
After hours trying to figure out whats goin on on my bloody app and db-wise nothin' works i finally ask all mighty stack overflow. I'm running a Django app on heroku evrything's goin great but when i try to switch to heroku's DB i get an application error. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } #code i added make evrything facked up import dj_database_url db_from_env = dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) Heroku logs 2022-05-09T16:28:06.566720+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1361, in execute_sql 2022-05-09T16:28:06.566726+00:00 app[web.1]: cursor.execute(sql, params) 2022-05-09T16:28:06.566726+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 67, in execute 2022-05-09T16:28:06.566726+00:00 app[web.1]: return self._execute_with_wrappers( 2022-05-09T16:28:06.566727+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers 2022-05-09T16:28:06.566727+00:00 app[web.1]: return executor(sql, params, many, context) 2022-05-09T16:28:06.566727+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute 2022-05-09T16:28:06.566727+00:00 app[web.1]: with self.db.wrap_database_errors: 2022-05-09T16:28:06.566727+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__ 2022-05-09T16:28:06.566727+00:00 app[web.1]: raise dj_exc_value.with_traceback(traceback) from exc_value 2022-05-09T16:28:06.566728+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute 2022-05-09T16:28:06.566728+00:00 app[web.1]: return self.cursor.execute(sql, params) 2022-05-09T16:28:06.566728+00:00 app[web.1]: django.db.utils.ProgrammingError: relation "accounts_random_link" does not exist 2022-05-09T16:28:06.566728+00:00 app[web.1]: LINE 1: ...om_link"."id", "accounts_random_link"."link" FROM "accounts_... 2022-05-09T16:28:06.566728+00:00 app[web.1]: ^ 2022-05-09T16:28:06.566728+00:00 app[web.1]: 2022-05-09T16:28:06.566934+00:00 app[web.1]: [2022-05-09 16:28:06 +0000] [10] [INFO] Worker exiting (pid: 10) 2022-05-09T16:28:06.568949+00:00 app[web.1]: [2022-05-09 16:28:06 +0000] [9] [ERROR] Exception in worker process 2022-05-09T16:28:06.568950+00:00 app[web.1]: Traceback (most … -
'Post' object is not iterable even though i'm using filter
I'm trying to get all posts for a certain Vehicle and this is the code that i have: *vehicles/views.py* class UserVehicleListView(ListView): model = Vehicle template_name = 'vehicles/vehicles.html' # <app>/<model>_<viewtype>.html context_object_name = 'vehicles' def get_queryset(self): print(Vehicle.objects.filter(owner_id= self.request.user.id)) return Vehicle.objects.filter(owner_id= self.request.user.id) class UserVehicleDetailView(DetailView): model = Post template_name = 'vehicles/vehicle_detail.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' def get_queryset(self): vehicle = get_object_or_404(Vehicle, id =self.kwargs.get('pk')) print(Post.objects.filter(vehicle= vehicle)) return Post.objects.filter(vehicle= vehicle) *vehicles/urls.py* urlpatterns = [ path('vehicles/', UserVehicleListView.as_view(), name='vehicle-list'), path('vehicles/<int:pk>/', UserVehicleDetailView.as_view() , name='vehicle-detail'), ] urlpatterns += staticfiles_urlpatterns() *vehicles/templates/vehicles/vehicle.html* {% for vehicle in vehicles %} <div class="col-lg-6 mb-3 mb-lg-0"> <div class="hover-overlay" ></div> <div class="hover-1-content px-5 py-4"> <a href=" {%url 'vehicle-detail' vehicle.id %}"> <h3 class="hover-1-title text-uppercase font-weight-bold mb-0"> <span class="font-weight-light">Volvo </span></h3> </a> <p class="hover-1-description font-weight-light mb-0">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p> </div> {%endfor%} *vehicles/templates/vehicles/vehicle_detail.html* {% extends "blog/base.html" %} {% block content %} <article class="media content-section"> <h2> {% for post in posts %} {{post.date_posted}} {%endfor%} </h2> </article> {% endblock content %} When i print with Vehicle.objects.filter(owner_id= self.request.user.id) I get in the cmd: <QuerySet [<Post: Post object (1)>, <Post: Post object (3)>]> but when I pass the values with the for loop in the vehicle_detail.html I get: ** TypeError at /vehicles/1/ 'Post' object is not iterable** When i pass as … -
How to intergarte react native front end with django backend
I created a user API using djangorest framework and it is functioning well, however i dont know how to add it to my react native front end for authentication. I would like users to login and the drf to authenticate them. Is there a tutorial i can follow, i tried to look at a few but they didnt work for me. I'm new to react native. Would appreciate elaborate answers and shared resources Currently using expo cli and unable to fetch data from drf(django rest framework). -
Django - Can't install zappa
I am trying to install zappa for my Django project with the pip install zappa command. For some reason I am getting the error message: UnicodeDecodeError: 'charmap' codec can't decode byte 0x9c in position 2341: character maps to <undefined> [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. I haven't found any similar issues online so I could use some help to solve it. -
django export xls as zip doesn't work: format unknown
I want to make a view that produce xls file using xlwt and make file downloaded as zip file using zipfile. def export(request): filename = "myfile.xls" wb = xlwt.Workbook(encoding='utf-8') .... buffer1 = io.BytesIO() wb.save(buffer1) buffer2 = io.BytesIO() with zipfile.ZipFile(buffer2, mode='w') as zip_file: zip_file.writestr(zinfo_or_arcname=filename, data=buffer1.getvalue()) response = HttpResponse(content_type='application/x-zip-compressed') response['Content-Disposition'] = 'attachment; filename=myzip.zip' return response but when I try to unzip I got an error: file format unknown -
How to manage zappa settings to dev environment using django
What is the best practices to manage dev enviroment using zappa? Currently I have my zappa_settings.json in my project and inside it I have api urls, keys etc. when I deploy It to AWS these keys will be used correctly like: API_KEY = os.getenv('API_KEY') the code above will get the API_KEY from my zappa_seetings.json { "prod": { "API_KEY": "example 2938u2983j0fy28394yf2j98340j20934" } } But what if I want to run the code locally? I'll need to create a .env file with the same enviroment keys and every time I change the zappa_settings.json file I'll need to change the .env file too? If there is a different way to do it, I would like to know. -
Django web app with Windows Docker container on Azure: Invalid HTTP_HOST header: '10.40.0.7:30015'. You may need to add '10.40.0.7' to ALLOWED_HOSTS
I deployed my Django app with Windows Docker container to Azure app services. The app works fine locally. But after deploying to the server, the kudu site log gives: Bad Request: / "GET / HTTP/1.1" 400 69702 Invalid HTTP_HOST header: '10.40.0.7:30015'. You may need to add '10.40.0.7' to ALLOWED_HOSTS. I know that I can add allowed IP addresses to settings.py and my .env file. But the problem is that Azure uses dynamic IP addresses. So with each push to the container and restart the app, my public IP address changes. How can I fix this? -
how to make button upload song mp3 django
so i'm new use django. my backend project use python. and i want make button html to choose song from computer to upload it (but i don't use database) to process it. here's my models.py code : from django import forms from django.db import models class Audio_store(models.Model): record=models.FileField(upload_to='documents/') class Meta: db_table='Audio_store' forms.py code : from django import forms from .models import * class AudioForm(forms.ModelForm): class Meta: model=Audio_store views.py code : from MusicLockApp.forms import AudioForm def Audio_store(request): if request.method == 'POST': form = AudioForm(request.POST, request.FILES or None) if form.is_valid(): form.save() return HttpResponse('SUKSES BRUH') else: form = AudioForm() return render(request, 'homepage.html', {'form' : form}) urls.py code : from django.contrib import admin from django.conf.urls import url from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.urls import path, re_path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^decode/$', views.decode), url(r'^$', views.homepage), path('audio', views.Audio_store), ] urlpatterns += staticfiles_urlpatterns() fields=['record'] add settings.py : STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) MEDIA_URL = '/mp3/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mp3') and my html code : <div class="row" style="margin-right: 10px;"> <form action="audio" method="post" enctype="multipart/form-data"> {% csrf_token %^} {{ form }} <a type="button" class="dsnupload"> <i class="large material-icons" style="font-size: 50pt; margin-top: 10px;">audiotrack</i> <p style="font-weight: … -
Using Django render() function without "template_name" but a string variable?
I've built an html generator for my app's view to display all relational fields and their further relations in one form. But this html also includes template filters, tags and some context variables. So generator returns an html but it needs to be parsed too for this reason. Is there anyway to use render() function with html string instead of template_name argument? My related question is: Combining custom django crispy forms' FormHelper and HttpResponse with context I've asked another question because I want an answer in narrow scope now. If you can suggest another method, you can mention it too. -
Django - Event loop is closed on custom object
I'm using a django app which imports a custom library. The library provides a factory class which also uses the AIOHttp and Asyncio libraries for HTTP calls. When I try to make the request (from views.py) I get an error saying 'event loop closed'. If I were to take the same code from views.py and request the ticket directly in apps.py, where the initial factory instantiation occurs, it works fine. I'm guessing that something isn't persisting like I thought it would. It's nothing more than a class which stores an aioHttp.ClientSession() object which I want to setup and persist once. That way other parts of my app can benefit from things like connection pooling, and other custom objects the factory can create. Although this works fine from within apps.py fine, trying to pull the stored ClientSession() object out from apps.py isn't playing ball for some reason in views.py. Any ideas what the problem might be? apps.py Defines what to do when the app is ready def ready(self): asyncio.run(self._ready()) async def _ready(self): creds = load_creds_from_file('creds.json') self.factory = TestFactory(creds) await self.factory.start() self.tickets = self.factory.get_ticket() print("setup completed...") views.py Attempts to access/pull back the instantiated objects held in apps.py my_app_config = apps.get_app_config('api') tickets = … -
How can I use higher abstraction level of class based views in django?
I have a project where literally each view has a lot of custom validation methods and context data that are being generated by given get or post user data, and when I was reading through the docs, I couldn't find any examples of how to mix django class based views with custom validators and context, that is generated after request coming. For example I have a view(the code below) where I have to to validate a lot of data before saving these incoming data in the database, and I don't like such approach of using CBV. And I have no idea how can I make my CBV abstraction level upper then it is now. Can you please give me some advises, tips, tutorials or just explain me how can I not to use base django.views.View class in such a difficult case, but instead of it use high abstraction level CBV . Here is the example of one of my class based views: class UnauthorizedUserMixin(View): def dispatch(self, request, **kwargs): if not request.user.is_authenticated: return redirect("login") return super().dispatch(request) class SendMailView(TemplateView, UnauthorizedUserMixin): template_name = "new_mail.html" def post(self, request): self.request = request if self.request.POST.get("back"): return redirect("all-sent-mails") all_data_validation_methods = [ self._check_if_not_all_fields_are_filled, self._check_if_recipient_doesnt_exists, self._check_if_sender_is_equal_to_recipient, self._check_if_input_fields_are_too_long ] self.form … -
ModuleNotFoundError: No module named ' '
I am attempting to run python manage.py runserver and I am getting a ModuleNotFoundError: No module named ' ' The entirety of the output can be seen here: (venv) danieljohnson@MACHPXNV2CL2Y project % python manage.py runserver /Users/danieljohnson/Documents/code/project/venv/lib/python3.9/site-packages/tzwhere/tzwhere.py:62: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray. self.timezoneNamesToPolygons[tzname] = WRAP(polys) Traceback (most recent call last): File "src/gevent/greenlet.py", line 906, in gevent._gevent_cgreenlet.Greenlet.run File "/Users/danieljohnson/Documents/code/project/venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/danieljohnson/Documents/code/project/venv/lib/python3.9/site-packages/channels/management/commands/runserver.py", line 51, in inner_run http_consumer=self.get_consumer(*args, **options), File "/Users/danieljohnson/Documents/code/project/venv/lib/python3.9/site-packages/channels/management/commands/runserver.py", line 157, in get_consumer return StaticFilesConsumer() File "/Users/danieljohnson/Documents/code/project/venv/lib/python3.9/site-packages/channels/handler.py", line 347, in __init__ self.handler = self.handler_class() File "/Users/danieljohnson/Documents/code/project/venv/lib/python3.9/site-packages/channels/staticfiles.py", line 18, in __init__ super(StaticFilesHandler, self).__init__() File "/Users/danieljohnson/Documents/code/project/venv/lib/python3.9/site-packages/channels/handler.py", line 194, in __init__ self.load_middleware() File "/Users/danieljohnson/Documents/code/project/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 56, in load_middleware mw_class = import_string(middleware_path) File "/Users/danieljohnson/Documents/code/project/venv/lib/python3.9/site-packages/django/utils/module_loading.py", line 20, in import_string module = import_module(module_path) File "/opt/homebrew/Cellar/python@3.9/3.9.12/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", … -
Unexpected keyword argument incoming allow when trying to create Twilio Audio ChatRoom
Following this tutorial to build a drop-in-audio chat application using Django, React and Twilio Programmable Voice. When I carry out GET request using fetch to create a chatroom, I get the error: Response {type: 'cors', url: 'http://127.0.0.1:8000/voice_chat/token/Emmanuel', redirected: false, status: 500, ok: false, …} and in my server: TypeError: __init__() got an unexpected keyword argument 'incoming_allow' This is the fetch function in my frontend: const handleSubmit = e => { e.preventDefault(); const nickname = state.nickname; setupTwilio(nickname); history.push('/rooms'); } const setupTwilio = (nickname) => { console.log('inside setupTwilio function', nickname) fetch(`http://127.0.0.1:8000/voice_chat/token/${nickname}`) .then(response => { console.log('resp', response) }) the API end-point I am interacting with: path('voice_chat/', include('voice_chat.urls')) urls.py containing voice_chat.urls: urlpatterns = [ path("rooms", RoomView.as_view(), name="room_list"), path("token/<username>", TokenView.as_view(), name="rooms"), ] Here is my TokenView: class TokenView(View): def get(self, request, username, *args, **kwargs): voice_grant = grants.VoiceGrant( outgoing_application_sid=settings.TWIML_APPLICATION_SID, incoming_allow=True, ) access_token = AccessToken( settings.TWILIO_ACCOUNT_SID, settings.TWILIO_API_KEY, settings.TWILIO_API_SECRET, identity=username ) access_token.add_grant(voice_grant) jwt_token = access_token.to_jwt() return JsonResponse({"token": jwt_token.decode("utf-8")}) -
Limitar 4 dados no return da função [closed]
Can I limit view for return 4 objects? @login_required(login_url='/login/') def lista_colaboradores(request): usuario = request.user colaborador = Colaborador.objects.filter(local_adm=usuario) dados = {'colaboradores':colaborador} return render(request, 'colaboradores.html', dados) -
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?