Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem when styling django form fields upon errors
I have a bug I've been trying to fix for months but can't figure out. I'm building a website with Django. The site has a form, that, among other fields, has a field to input the name (called "nombre") and a field for the last name (called "apellido") of the user. I've declared a CSS rule (applied to the fields with the class "error" that gives a specific style to the fields that didn't pass the form validation, highlighting them in red. In a "forms.py" file, I wrote some code that assigns the class "error" to the fields that did not pass the validation. The problem is that, when I input invalid data into the "apellido" field and try to submit the form, both de "apellido" and "nombre" fields get highlighted in red. I have no clue why this could be happening. I figure it must be something with the "forms.py" file, where I assign the "error" class to the invalid fields. Here is the code of the "forms.py" file: from django import forms from .models import Turno class TurnoForm(forms.ModelForm): class Meta: model = Turno fields = ['nombre', 'apellido', 'email', 'fecha', 'hora'] widgets = { "nombre": forms.TextInput(attrs={"class": "form-control", "name": "nombre"}), … -
Dockerizing django app with Nginx, gunicorn and docker-compose - data base connectivity issue
Amateur programer here. I usually can google my way out of every issue but I struggle with the huge diversity in set ups for docker (and honestly feel al ittle overwhelmed). I am aware the the biggest tutorials out there (including the famous digitalocean one), but it didn't help. As title says, I am trying to dockerize a django app (in order to deploy to a VPS) using Nginx en gunicorn. My docker-compose file has a data base service, a django_unicorn service and a nginx container. The data base and nginx containers seem to set up correctly. But when my django_unicorn runs, in fails to connect to the data base. The error message is : django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on 'db' ([Errno 111] Connection refused)")] After a while, it stops and gives me the localhost server to connect to, but it obviously shows nothing. I tried checking on the data base within my docker container. It is working fine and I connect within it with root user and my custom user. I uses the exact same credentials in my settings.py file in django. The HOST and PORT look ok to me (referring the db service in docker-compose … -
Override CSS when Debug=True
In order to avoid confusion between my production and development instance (where DEBUG = True), I'd like to override the CSS of my bootstrap Navbar in development (only) to show up e.g. in red instead of blue. What is the most elegant way to accomplish this? I can override get_context_data() everywhere to include my settings.DEBUG, or inherit from a newly generated base classes, but that doesn't seem very DRY. -
Display a converted .docx to PDF file from Django REST framework backend in React frontend
I am running a django REST framework backend and a React frontend. I want to convert a .docx to PDF bytes in the backend and display it on the frontend but I keep getting Failed to load PDF Document error. I have tried several pdf modules and different methods to display the PDF bytes in the frontend but I keep getting the same error. I will really appreciate any help . Below is what I came up with: views.py from docx import Document @api_view(['POST']) def viewFile(request): data = request.data file = File.objects.get(id=data['id']) try: pdf_bytes = convert_file_to_pdf(file) pdf_base64 = base64.b64encode(pdf_bytes).decode('utf-8') return Response({'pdf_base64': pdf_base64}) except Exception as e: return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) def convert_file_to_pdf(file): if file: if file.filename.endswith('.docx'): doc = Document(file.file) pdf_bytes = BytesIO() doc.save(pdf_bytes) pdf_bytes.seek(0) return pdf_bytes.read() elif file.filename.endswith('.xlsx'): wb = load_workbook(file.file) # Convert to PDF using appropriate method (e.g., Excel to PDF) # Return PDF bytes elif file.filename.endswith('.pptx'): prs = Presentation(file.file) # Convert to PDF using appropriate method (e.g., PowerPoint to PDF) # Return PDF bytes else: raise ImproperlyConfigured("Unsupported file format") else: raise ImproperlyConfigured("File not found") DocumentViewer.js function DocumentViewer() { const [fileId,] = useState('327'); const [pdfUrl, setPdfUrl] = useState(null); useEffect(() => { const getPdf = async () => { try … -
How to store my user-uploaded files on Digital Ocean Spaces using django-storages?
I am totally new to this. My Django app is run in Docker. My app allows users to upload files which are stored, followed by executing some functions on the file then generating a new file that the user can download. I'd like to store the initial user-uploaded file and the output-file my django code generates. Here is my code: models.py: class TranscribedDocument(models.Model): id = models.CharField(primary_key=True, max_length = 40) audio_file = models.FileField(upload_to='ai_transcribe_upload/', null= True) output_file = models.FileField(null= True) date = models.DateTimeField(auto_now_add=True, blank = True, null=True) views.py: #save uploaded file if form.is_valid(): uploaded_file = request.FILES['file'] request.session['uploaded_file_name'] = uploaded_file.name request.session['uploaded_file_size'] = uploaded_file.size#add to models.py session_id = str(uuid.uuid4()) request.session['session_id'] = session_id transcribed_doc, created = TranscribedDocument.objects.get_or_create(id=session_id) transcribed_doc.audio_file = uploaded_file transcribed_doc.save() request.session['uploaded_file_path'] = transcribed_doc.audio_file.path #generate new file with open(file_location, 'r', encoding=charenc) as f: file_data = f.read()## transcribed_doc, created = TranscribedDocument.objects.get_or_create( id = request.session['session_id'] ) transcribed_doc.output_file = transcript_path transcribed_doc.date = timezone.now() transcribed_doc.save() settings.py: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "postgres", "USER": "postgres", "PASSWORD": "postgres", "HOST": "db", # set in docker-compose.yml "PORT": 5432, # default postgres port } } AWS_ACCESS_KEY_ID = 'key_id' AWS_SECRET_ACCESS_KEY = 'secret_key_id' AWS_STORAGE_BUCKET_NAME = 'name' AWS_DEFAULT_ACL = 'public-read' #change to private AWS_S3_ENDPOINT_URL = 'https://nyc3.digitaloceanspaces.com/' # Make sure nyc3 is correct AWS_S3_OBJECT_PARAMETERS = … -
Dynamic in the setting file
In the code below, I want to make it dynamic, for example using models, what should I do so that it is called in the settings file EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = False EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_HOST_USER = 'example.com' EMAIL_HOST_PASSWORD = '12345678' In the code below, I want to make it dynamic, for example using models, what should I do so that it is called in the settings file -
Django's filter clears foreign keys
In views.py, if I defining variable like clients_list = Clients.objects.all() and reading them in html like {{ clients_list }} then I get all data correct. But if I make filtering like clients_list = Clients.objects.filter(cli_account='123').values() then all the foreign keys are converted to integers and not displayed if requested in html (only in all queryset). I need to filter clients list but keep all foreign keys as they were unfiltered, not integer - strings. p.s.: if I trying to get {{ obj.cli_status }} in the first version, I get "ready", but in the second version i get blank (an integer in queryset) -
create ONE TIME model in django e.g site apperance || settings?
iam using django to create an ecommerce website n iam trying to make my site style & components dynamic and some settings i wonder how i can do that ? to be more clear like this : class SiteAppearance(models.Model): headerType = models.Choices('some choices') mainPagesStyle = models.Choices('some choices too') mainColor = models.CharField(max_length=100) enableBlog = models.BooleanField(default=False) enableShop = models.BooleanField(default=False) recommendedPaymentMethod = models.CharField(max_length=100) class SiteSettings(models.Something): # some fields i want this model so it cannot be created more than once is it possible? i have tried to do something like this : siteAppearance .objects.create(some fields) appearance = siteAppearance.objects.get(pk=1) siteSettings.objects.create(some fields) site_settings = siteSettings.objects.get(pk=1) but i dont think its an effective way to do it :) -
Django authentication weird behaviour (data available only after rendering)
I am currently having a problem in getting correct auth info in Django project. After entering login/password info and pressing the button, server does POST request and opens next page. But inside this page I always get AnonymousUser as "user" for request.user variable AND correct variable for request.POST.username. But the problem is that I can not retreive request.POST.username before page render, in views.py. If I set it that way, I get error 'QueryDict' object has no attribute 'username'. BUT... if I just make html code to print what I have at requestPOST it returns the following <QueryDict: {'username': ['alpha'], 'password': ['omega'], 'csrfmiddlewaretoken': ['F3DvmyA8DCrWiwQHfg2sVlpChdFYDLe1mkxulT0qjtMiO3pNJxSxbBNxCpwJ1FuM']}> and inside html I can get name correctly... In other words, I can get username at html part but can not get the same in views.py prior to rendering page. The part of views.py def user_login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(username=cd['username'], password=cd['password']) if user is not None: if user.is_active: login(request, user) return HttpResponse('Authenticated successfully') else: return HttpResponse('Disabled account') else: return HttpResponse('Invalid login') else: form = LoginForm() return render(request, './login.html', {'form': form}) def results_page(request): clients_list = Clients.objects.all() requestAlone = request requestPost = request.POST dict_obj = {'clients_list': clients_list, 'user': … -
Django Password form not loading
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/5/password/ Using the URLconf defined in My_Blog_Project.urls, Django tried these URL patterns, in this order: admin/ account/ blog/ [name='index'] The current path, 5/password/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. @`login_required def pass_change(request): current_user = request.user change = False form = PasswordChangeForm(current_user) if request.method == 'POST': form = PasswordChangeForm(current_user, data=request.POST) if form.is_valid(): form.save() change = True return render(request, 'App_Login/pass_change.html', context={'form': form, 'change': change}) its my Views.py {% extends 'base.html' %} {% load crispy_forms_tags %} {% crispy form %} {% block title_block %}Change Password{% endblock %} {% block body_block %} {% if change %} Password changed successfully. {% endif %} {% csrf_token %} {{ form|crispy }} Change Password {% endblock %} its my pass_change.html path('password/',views.pass_change, name='pass_change') its my url pattern for my App_login app from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('admin/', admin.site.urls), path('account/',include('App_Login.urls')), path('blog/', include('App_Blog.urls')), path("",views.Index, name='index'), ] its my main url.py How can i solve this issue` -
Overwrite django rest response for return only pk
I'm trying to overwrite the response that is sended by django when create a new object. I need to return only the primary key of the created object instead the whole object. The function that I'm trying to overwrite is this: def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) data = serializer.data print(data['id']) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) Where the name of the field "id' inside the data object can be different by each entity. The final code should be something like: return Response(pk, status=status.HTTP_201_CREATED, headers=headers) Any idea about how can I make it work? Thanks in advance -
How to get all relations for items in database model in Django
I'm trying to make an online business canvas. In this app, we have a database containing Project, User and 9 other models. All models are connected to one specific project. In the app, when user click on on of the items (which is stored previously in the database, I want to retrive all the related items to it. For example, when user click on a cost-structure, I have to bring everything which is related to that cost-structure or if user click on one value-proposition, I have to bring everything which is connected to that value-proposition. below is the database model: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass class Project(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255) def __str__(self): return self.name def get_all_relationships(self): relationships = { 'value_propositions': self.value_propositions.all(), 'customer_segments': self.customer_segments.all(), 'channels': self.channel.all(), 'customer_relationships': self.customer_relationship.all(), 'revenue_streams': self.revenue_stream.all(), 'key_resources': self.key_resources.all(), 'key_activities': self.key_activity.all(), 'key_partners': self.key_partner.all(), 'cost_structures': self.cost_structure.all(), } return relationships class ValueProposition(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="value_propositions") value = models.CharField(max_length=255) description = models.CharField(max_length=1023) def __str__(self): return self.value class CustomerSegment(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="customer_segments") value_propositions = models.ManyToManyField(ValueProposition, related_name="customer_segments") customer_segment = models.CharField(max_length=255) def __str__(self): return self.customer_segment class Channel(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="channel") customer_segment = models.ManyToManyField(CustomerSegment, related_name="channel") channels = models.CharField(max_length=255) def … -
Forbidden (CSRF cookie not set.) Django and Angular
I am gettig error CSRF cookie not set here is my angular coponent.ts file sendMessage(nick:string){ const formData = new FormData(); this.nickname = nick; formData.append('nickname',this.nickname); const headers = new HttpHeaders({ 'X-CSRFToken':this.getCookies('csrftoken') }); this.http.post('http://127.0.0.1:8000/api/send/', formData, {headers:headers, withCredentials:true }).subscribe( (response:any) => { if(response.success){ this.messageStatus = 'Message sent succesfully'; } else{ this.messageStatus = 'Failed to send message'; } }, error => { this.messageStatus = 'Failed to message' console.log('erorr is ',error) console.log(this.getCookies('csrftoken')) console.log(headers) } ) } method getCookies in component.ts private getCookies(name:string):any{ const cookieValue = document.cookie.match('(^|;)\s*' + name + '\s*=\s*([^;]+)'); return cookieValue ? cookieValue.pop() : ''; } Here is views.py django def send_message_to_telegram(request): if request.method == 'POST': telegram_nickname = request.POST.get('nickname') # Replace 'YOUR_BOT_TOKEN' with your actual Telegram bot token bot_token = 'My _ token' bot_chat_id = '789829434' # Replace with your bot's chat ID message = f"Hello, @{telegram_nickname}! This is a message from our bot." # Sending message via Telegram Bot API url = f"https://api.telegram.org/bot{bot_token}/sendMessage" payload = { 'chat_id': bot_chat_id, 'text': message } response = requests.post(url, json=payload) if response.ok: return JsonResponse({'success': True, 'message': 'Message sent successfully'}) else: return JsonResponse({'success': False, 'message': 'Failed to send message'}) else: return JsonResponse({'success': False, 'message': 'Method not allowed'}, status=405) here is my settings.py CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True ALLOWED_HOSTS … -
Django async - OperationalError: the connection is closed - does not recover after db restart
I have something like the following coroutine, running by an async task: from django.db import OperationalError from my_app.models import User async def update_user_name(user: User): while True: try: user.name = coolname.generate_slug() await user.asave(update_fields=["name"]) except OperationalError: logging.exception( "DB operational error occurred, Wait 2 seconds and try again." ) await asyncio.sleep(10) when the db is inaccessible I'm getting OperationalError which makes sense. But then after fixing the db I keep getting those OperationalErrors and the connection does not really recovers I wonder why? I would expect a new connection to be opened and to be able to save to db since the issue was fixed. Im using Django 5.0.4 I noticed that my CONN_MAX_AGE db setting was 5 minutes. I changed it to 0 (close connection after each request) and it didn't help. -
I cant implement AJAX in my django forum app to post a question
I have a forum app in which users can post their questions. I want to prevent page reloading each time a user post a comment for a question. I've tried implementing ajax but it didn't work. I've done this: this is forms.py: class CommentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CommentForm, self).__init__(*args, **kwargs) # add a "form-control" class to each form input # for enabling bootstrap for name in self.fields.keys(): self.fields[name].widget.attrs.update({ 'class': 'form-control', }) class Meta: model = Comment fields = ('question', 'reply_to', 'text') this is views.py: def post_comment(request): # request should be ajax and method should be POST. if request.is_ajax and request.method == "POST": # get the form data form = CommentForm(request.POST) # save the data and after fetch the object in instance if form.is_valid(): instance = form.save() # serialize in new friend object in json ser_instance = serializers.serialize('json', [instance, ]) # send to client side. return JsonResponse({"instance": ser_instance}, status=200) else: # some form errors occured. return JsonResponse({"error": form.errors}, status=400) # some error occured return JsonResponse({"error": ""}, status=400) this is urls.py: urlpatterns = [ path('comment/', post_comment, name='post-comment'), ] this is base.html: {% block content %} {% endblock content %} <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> {% block javascript %} {% endblock … -
create entire project on django admin user frontend also view in django admin
I want to create a project in django that admin can add traders user login means do CRUD operation but i want to show all the front end data also in admin panel of django user also login in django with less permission set by admin is it possible ? -
Django Project Depolyment in Windows Server using Apache
I have installed python 3.12 , Installed Django and Installed Apache and tested all without pasting my project inside htdocs and that run.Now in htdocs i have kept my project two folder core and myenv. Inside core main project files C:\Apache24\htdocs\core\core\wsgi.py httpd.conf LoadFile "C:/Program Files/Python312/python312.dll" LoadModule wsgi_module "C:/Program Files/Python312/site-packages/mod_wsgi/server/mod_wsgi.cp312-win_amd64.pyd" WSGIPythonHome "C:/Program Files/Python312" WSGIScriptAlias / "C:/Apache24/htdocs/core/core/wsgi.py" WSGIPythonPath "C:/Program Files/Python312/Lib/site-packages" <Directory "C:/Apache24/htdocs/core/core/"> Require all granted Alias /static "C:/Apache24/htdocs/core/static/" <Directory "C:/Apache24/htdocs/core/static/"> Require all granted ////// Listen 3080 ServerName example.com:80 But when i start apache and run its shows error Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at admin@example.com to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. and in logs>error: mod_wsgi (pid=1648): Failed to exec Python script file 'C:/Apache24/htdocs/core/core/wsgi.py'. Traceback (most recent call last):\rFile "C:/Apache24/htdocs/core/core/wsgi.py", line 16, in \r line 16, in \r File "C:\Program Files\Python312\lib\site-packages\django\init.py", line 19, in setup\r [Thu May 02 16:40:44.634611 2024] [wsgi:error] [pid 1648:tid 1228] [client ::1:50356] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)\r ModuleNotFoundError: No module named 'core'\r mod_wsgi (pid=1648): Failed to exec Python script … -
Django hidden field obligatory field error
I'm developing a Django page where a user fills out a lottery form. This data is stored in a MySQL database. Part of the functionality of the page is that the user can retrieve the form with the lottery data already entered to add more, modify some, or rerun the lottery without needing to re-enter all the data. Now, for this purpose, I have these forms that I am using to retrieve the lottery, add participants, add lottery data, etc... class SorteoForm(forms.ModelForm): class Meta: model = Sorteo fields = ['organizer', 'celebration_date', 'budget'] class ExclusionForm(forms.Form): participants_to_exclude = forms.CharField(label='Participants to exclude', max_length=100) class SorteoRecuperadorForm(forms.Form): recuperator_lottery = forms.CharField(label='Lottery code', max_length=50, required=False) class ParticipanteExclusionForm(forms.Form): name = forms.CharField(label='', max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Name'})) email = forms.EmailField(label='', max_length=100, widget=forms.EmailInput(attrs={'placeholder': 'Email'})) exclusions = forms.CharField(label='', max_length=100, required=False, widget=forms.TextInput(attrs={'placeholder': 'Exclusions'})) ParticipanteExclusionFormSet = formset_factory(ParticipanteExclusionForm) ParticipanteFormSet = formset_factory(ParticipanteForm) ExclusionFormSet = formset_factory(ExclusionForm) The data control for these forms, both to rerun the lottery and to retrieve the data, is done through this method: def recover_lottery(request): lottery_form = SorteoForm(request.POST or None) ParticipanteExclusionFormSet = formset_factory(ParticipanteExclusionForm, extra=0) participant_formset = ParticipanteExclusionFormSet(request.POST or None, prefix='participant') recuperator_form = SorteoRecuperadorForm(request.POST or None) lottery = None participants = None if request.method == 'POST': if recuperator_form.is_valid(): # Retrieve the lottery and participants lottery … -
Comments asigned correctly to answer objects but display in one answer objects
I'm building a question-and-answer platform to help companies understand their customers' needs. As you can see in the view_question views, I'm displaying an answer based on the question, and it is working perfectly. However, when displaying comments on the answer using this method: answers = Answer.objects.filter(post=question) answers_comment = CommentA.objects.filter(post=answers) This method return an error in the template saying: The QuerySet value for an exact lookup must be limited to one result using slicing. then i try to display it using this method: answers = Answer.objects.filter(post=question) answers_comment = CommentA.objects.filter(post__id__in=answers) It seems like the problem is solved, but it is not. The answers_comment display all comment objects to a single answer object, even though they were not assigned to that answer. {% for answer in answers %} <div class="row border-bottom"> <div class="col col-answer"> <div class="answer-icons"> <a style="text-decoration: none;" href=""> <span><i class="fas fa-arrow-up"></i></span> <span>{{ answer.up_vote }}</span> </a> <a style="text-decoration: none;" href=""> <span><i class="fas fa-arrow-down"></i></span> <span>{{ answer.down_vote }}</span> </a> </div> <div class="answer-text"> <p>{{answer.your_answer|convert_markdown|safe}}</p> </div> </div> </div> {% endfor %} <div class="comment-container m-2"> {% for answer_comment in answers_comment %} <div class="row"> <small>{{ answer_comment.comment }}</small> {% with answer_comment.user.account as account %} <a style="text-decoration: none;" class="user-avatar" href="{% url 'Public-Profile' slug=account.slug %}"> <span>{{ answer_comment.user.username }} </span> </a> <small>{{ … -
how to tokenize a filed in elk?
I want to tokenize a field(text) in all documents(60k) of index(post) what is the best approach? GET /_analyze { "analyzer" : "standard", "text" : ["this is a test"] } need tokenized text for tag cloud in my Django app -
Why can't I deploy project (passenger wsgi)
When I change the passenger_wsgi.py to import <project_name>.wsgi application = <project_name>.wsgi.application I encounter with below error: Web application could not be started by the Phusion Passenger(R) application server. Please read the Passenger log file (search for the Error ID) to find the details of the error. I change wsgi.py in project to: os.environ["DJANGO_SETTINGS_MODULE"] = "project.settings" -
Django : Locally save an instance of a Model
Using signals, I try to track the difference between the old instance of an object and the new instance when the Model is saved. I tried this : But logically in the model_post_init_handler method, it's a reference of the object that is stored in __original_instance. So, instance.__original_instance.is_used and instance.is_used will always be the same. How could I store a "snapshot" of the object when he is initiated, so that I will be able to track what is edited ? -
Integrating Microsoft Forms Authentication in Python Django: Troubleshooting Terminal Error
To integrate the Microsoft Forms authentication flow into my Python Django project for accessing various forms URLs and storing form details and responses, I'm employing the provided MS Forms authentication code within my project's backend. Additionally, I've configured my project to run within a Docker container. The MS Forms authentication code snippet, enclosed below, outlines the process: import json import os import django.core.management.base import requests from azure.identity import DefaultAzureCredential, InteractiveBrowserCredential, AzureCliCredential # Custom Django command definition class Command(django.core.management.base.BaseCommand): def handle(self, *args, **options): # Select one of the credential objects to obtain an access token # cred = AzureCliCredential() # e.g., via `az login` cred = InteractiveBrowserCredential() # cred = DefaultAzureCredential() # Request an access token with the specified scope scope = "https://forms.office.com/.default" token = cred.get_token(scope) print("===============================") print(f"{token.expires_on = }") print("===============================") tenantId = "tenant id" groupId = "group id" formId = "form id" # Provide the access token in the request header headers = {"Authorization": f"Bearer {token.token}"} # Retrieve all Forms for a Microsoft 365 Group url = f"https://forms.office.com/formapi/api/{tenantId}/groups/{groupId}/forms" list_response = requests.get(url, headers=headers) print(f"All Forms: {list_response.json()}") # Retrieve details for a specific group form url = f"https://forms.office.com/formapi/api/{tenantId}/groups/{groupId}/forms('{formId}')" list_response = requests.get(url, headers=headers) print(f"Form Detail: {list_response.json()}") # Retrieve questions from a group form … -
How do I write tests for my django-extensions cron job?
I have a cron job in my Django app that's defined as a MinutelyJob (from django-extensions). How do I write tests for the job? The module documentation is quite sparse, and doesn't tell me how to call the job from code as opposed to the command line. I don't want to write test code that depends on undocumented interfaces. Alternatively, should I reimplement the job using a different module? I only have the one job so Celery is a bit heavyweight for my use case. -
How can I customize Django Rest Framework documentation without using decorators?
I'm currently working on a Django project and utilizing Django Rest Framework (DRF) for building APIs. I've integrated drf-pectacular for automatic API documentation generation, but I'm finding that using decorators to customize the documentation is making my codebase messy. I'm interested in exploring alternative approaches to customize my DRF documentation without relying heavily on decorators. Could someone provide guidance on how to achieve this? I'm specifically looking for methods or techniques that allow me to customize the documentation while keeping my code clean and maintainable. Any suggestions, examples, or best practices would be greatly appreciated. Thank you!