Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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! -
How to Handle and Send Various File Types (Images, Videos, Audios, PDFs, Documents) in a Django Chat App Using WebSockets and Django REST Framework
I'm working on a chat application where I need to handle and store various types of files such as images, videos, audios, PDFs, and documents using Django and Django REST framework. I have a WebSocket consumer with events like connect, disconnect, and receive. In the receive event, I'm trying to handle video files. Here's a simplified version of my code: # consumers.py async def video(self, event): stream = File(BytesIO(event['file']), name=event['file_name']) data = JSONParser().parse(stream) event['file'] = data await self.send(text_data=json.dumps(event)) # serializers.py class MessageSerializer(serializers.ModelSerializer): image = Base64ImageField(required=False) file = MyBase64FileField(required=False) class Meta: model = ChannelMessages fields = '__all__' I'm facing issues with sending video files over the WebSocket. What changes do I need to make in my code to handle video files properly and send them over the WebSocket? Additionally, I'm looking for a solution that allows me to handle and send other file types like images, audios, PDFs, and documents as well. -
How to serve images from backend to frontend
I have an application with following three different docker containers:- Frontend(react) Back-end(django) Nginx for serving static files from frontend, I am trying to access nginx website in Kubernetes (minikube). all other data is being served from backend container but only image is not being sent Can someone please help. debug is true and MEDIA_URL = ‘/media/’ MEDIA_ROOT = os.path.join(BASE_DIR ,“/app/media”) I have kept the name of django app as django-service, should I change the following lines in setttings.py file to django-service as well ? ROOT_URLCONF = 'backend.urls' WSGI_APPLICATION = 'backend.wsgi.application' here is entrypoint.sh file with same name #!/bin/sh gunicorn backend.wsgi:application --bind 0.0.0.0:8000 and following is deploment resources # Django Deployment apiVersion: apps/v1 kind: Deployment metadata: name: django-app spec: replicas: 1 selector: matchLabels: app: django-app template: metadata: labels: app: django-app spec: containers: - name: django-container image: ash414/e-cart-backend:v1.0 ports: - containerPort: 8000 # Django Service apiVersion: v1 kind: Service metadata: name: django-service labels: app: django-app spec: selector: app: django-app ports: - protocol: TCP port: 8000 targetPort: 8000 # Nginx Deployment apiVersion: apps/v1 kind: Deployment metadata: name: nginx-app labels: app: nginx-app spec: replicas: 1 selector: matchLabels: app: nginx-app template: metadata: labels: app: nginx-app spec: containers: - name: nginx-container # Not working images # … -
How to implement preview page with files Django?
I have my News model: class News(models.Model): subject = models.CharField(max_length=30) text = models.TextField() created = models.DateTimeField(auto_now_add=True) I also have File model to store files and NewsFile model to connect models to each other: class File(models.Model): file = models.FileField( 'файл' ) class NewsFile(models.Model): file = models.ForeignKey( File, on_delete=models.CASCADE, verbose_name='файл', related_name='news_files' ) news = models.ForeignKey( News, on_delete=models.CASCADE, verbose_name='новость', related_name='files' ) Here is my news form: class MultipleFileInput(forms.ClearableFileInput): allow_multiple_selected = True class MultipleFileField(forms.FileField): def __init__(self, *args, **kwargs): kwargs.setdefault("widget", MultipleFileInput()) super().__init__(*args, **kwargs) def clean(self, data, initial=None): single_file_clean = super().clean if isinstance(data, (list, tuple)): result = [single_file_clean(d, initial) for d in data] else: result = single_file_clean(data, initial) return result class NewsForm(forms.ModelForm): files = MultipleFileField(required=False) class Meta: model = News fields = ('subject', 'text') I want to make a page with a preview of the news and buttons to publish or edit the news. I have started implementing publish button, I can't pass files with form. My view: def form_valid(self, form): files = form.cleaned_data.get('files') if self.request.GET.get('save') == 'true': res = super().form_valid(form) for file in files: file_obj = File.objects.create(file=file) NewsFile.objects.create(news=self.object, file=file_obj) return res img_files = [] non_img_files = [] for file in files: if file.name.split('.')[-1] in settings.IMAGE_FORMATS: img_files.append(file) else: non_img_files.append(file) images = [] for file in img_files: … -
Google Authentication Not Appearing in Django Project
Body: I am trying to set up Google authentication in my Django project using django-allauth, but the Google login option is not appearing on my login page. I suspect I might be missing a configuration step or setting. I have confirmed the site ID is correct by checking the link: http://127.0.0.1:8000/admin/sites/site/3/change/ Could someone help me identify what I might be missing or doing wrong? Here are the relevant parts of my settings.py: SOCIALACCOUNT_PROVIDERS = { "google": { "app": [ { "client_id": "myid", "secret": "mysecret", }, ], "SCOPE": [ "profile", "email", ], "AUTH_PARAMS": { "access_type": "online", }, } } SITE_ID = 3 MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'allauth.account.middleware.AccountMiddleware', 'livereload.middleware.LiveReloadScript', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'core.views.site_settings', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] LOGIN_REDIRECT_URL = 'login' # Redirect after login LOGOUT_REDIRECT_URL = 'home' # Redirect after logout