Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJango - JS - Ajax - Upload file to NRM/Nexus (another domain) - CORS Issue
PLEASE HELP With the following JS function `function nexusUploader(file) { let filename = file.name, formData = new FormData(); formData.append('package', file); $.ajax({ url: "https://<external domain (NRM/NEXUS)>", type: "PUT", data: formData, contentType: false, cache: false, cors: false , crossDomain: true, secure: true, processData: false, mimeType: "multipart/form-data", headers: { 'X-CSRFTOKEN': $.cookie("csrftoken"), "Authorization": "Basic <KEY>" }, success: function(data) { console.log(data); }, error: function(e) { console.log(e); } }); }` I am getting the following error: Access to XMLHttpRequest at 'https://' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. global.js:37 09/28/2023 22:06:20: {readyState: 0, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …} jquery-3.7.0.min.js:2 PUT https:// net::ERR_FAILED -
'MoneyField' object has no attribute '_currency_field' in django-money when running migration
For the following Model, I added a new field gst_amount: from djmoney.models.fields import MoneyField class Invoice(Model): gst_amount = MoneyField(max_digits=14, decimal_places=2, default="0 USD") The migration completed and I can use the field in my views without issue. When I try to run the following data migration: from djmoney.money import Money from django.db import migrations def migrate_invoices(app, _): Invoice = app.get_model("users", "Invoice") for invoice in Invoice.objects.all(): invoice.gst_amount = Money(10, 'AUD') class Migration(migrations.Migration): operations = [ migrations.RunPython(migrate_invoices, migrations.RunPython.noop) ] I get the following error: File "/app/blah/users/migrations/0159_auto_20230929_0113.py", line 9, in migrate_invoices for invoice in Invoice.objects.all(): File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 280, in __iter__ self._fetch_all() File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 69, in __iter__ obj = model_cls.from_db(db, init_list, row[model_fields_start:model_fields_end]) File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 515, in from_db new = cls(*values) File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 437, in __init__ _setattr(self, field.attname, val) File "/usr/local/lib/python3.9/site-packages/djmoney/models/fields.py", line 111, in __set__ and self.field._currency_field.null AttributeError: 'MoneyField' object has no attribute '_currency_field' Not sure what I'm missing? -
How do I make these Tables?
We'll have to make these tables in HTML, but I'm not sure how to do them. [[These are the images of the tables. We have to use DJango and add them info there. But we are not sure how to desing the tables ourselves, how to make one cell in a row and then 2 cells.](https://i.stack.imgur.com/Gx1dS.png)](https://i.stack.imgur.com/ggbHz.png) Another example: | Column A | Column B | | -------- | -------- | | Cell 1 | | Cell 2 | Cell 3 | | Check Marck o | | Cell 4 | Image | <table border="1" width="70%"> <caption>Listado Clientes Septiembre 2023</caption > <tr> <th>Codigo de venta</th> <th>Precio del Producto</th> <th>Cantidad</th> <th>Valor unitario</th> <th>Total a pagar</th> </tr> <tr> <td>{{CCodigoVenta}}</td> <td>{{PProducto}}</td> <td>{{CCantidad}}</td> <td>{{ValorUnitario}}</td> <td>{{TTotalPagar}}</td> </tr> </table> That's how we made a table like the third image, but I don't know how to make something like the Cell 1, or puit a check mark for example. qwp -
Issue with outputting tolls using Google routes API
I am able to get toll information correctly using Google routes Api when running the code on localhost. Response on localhost is : {'routes': [{'legs': [{'travelAdvisory': {'tollInfo': {'estimatedPrice': [{'currencyCode': 'INR', 'units': '170'}]}}}], 'distanceMeters': 112558, 'duration': '7729s', 'travelAdvisory': {'tollInfo': {'estimatedPrice': [{'currencyCode': 'INR', 'units': '170'}]}}}]} When the same code is migrated to cloud server , toll information becomes blank. Response on Cloud comes like this : {'routes': [{'legs': [{}], 'distanceMeters': 112558, 'duration': '7729s'}]} Expecting the same response on cloud as it is coming on localhost because code is same. -
Django Rest and Dropzone React "The submitted data was not a file. Check the encoding type on the form."
I've got a react frontend with django backend trying to upload some images to django api enpoint I have 1 model in django but i want to first upload an image and then submit the rest of the data, the issue is when i try to upload the photos i get an error response photos [ "The submitted data was not a file. Check the encoding type on the form." ] I am using Dropzone to upload photos by the way Here is the react component handling uplaod function ImageUploader() { const [fileNames, setFileNames] = useState([]); const handleDrop = async (acceptedFiles) => { try { // Create a new FormData object to send files const formData = new FormData(); acceptedFiles.forEach((file) => { // Append each file to the FormData object formData.append('photos', file); }); // Make a POST request to your photo upload endpoint //axios.defaults.headers.post['Content-Type'] = 'multipart/form-data'; const response = await axios.post('http://localhost:8000/api/quotes/create/', formData, { headers: { 'Accept': 'application/json', 'Content-Type': 'multipart/form-data', }, }); // Handle the response (e.g., show success message) console.log('Upload successful:', response.data.message); // Update the list of file names for display setFileNames(acceptedFiles.map((file) => file.name)); } catch (error) { console.error('Upload failed:', error); } }; return ( <div className="App"> <Dropzone onDrop={handleDrop} accept={{ … -
ModuleNotFoundError: No module named 'simple_history' Pythonanywhere
I have a Django app running on pythonanywhere server. I have installed the requirements.txt and everything is okay, python manage.py migrate also successfully done. now when I reload my app I get following error. 2023-09-29 00:42:43,481: Error running WSGI application 2023-09-29 00:42:43,514: ModuleNotFoundError: No module named 'simple_history' 2023-09-29 00:42:43,514: File "/var/www/app_umrahpro_me_wsgi.py", line 16, in <module> 2023-09-29 00:42:43,514: application = get_wsgi_application() 2023-09-29 00:42:43,514: 2023-09-29 00:42:43,514: File "/home/HBNmughal/.local/lib/python3.10/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2023-09-29 00:42:43,515: django.setup(set_prefix=False) 2023-09-29 00:42:43,515: 2023-09-29 00:42:43,515: File "/home/HBNmughal/.local/lib/python3.10/site-packages/django/__init__.py", line 24, in setup 2023-09-29 00:42:43,515: apps.populate(settings.INSTALLED_APPS) 2023-09-29 00:42:43,515: 2023-09-29 00:42:43,515: File "/home/HBNmughal/.local/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate 2023-09-29 00:42:43,516: app_config = AppConfig.create(entry) 2023-09-29 00:42:43,516: 2023-09-29 00:42:43,516: File "/home/HBNmughal/.local/lib/python3.10/site-packages/django/apps/config.py", line 193, in create 2023-09-29 00:42:43,516: import_module(entry) 2023-09-29 00:42:43,516: *************************************************** 2023-09-29 00:42:43,520: If you're seeing an import error and don't know why, 2023-09-29 00:42:43,520: we have a dedicated help page to help you debug: 2023-09-29 00:42:43,521: https://help.pythonanywhere.com/pages/DebuggingImportError/ 2023-09-29 00:42:43,521: *************************************************** It should be reloaded without any error -
Docker Error build during Deployment on Railway services
please I had previously deployed my Django project on Railway which worked fine. Unfortunately, when I tried to add up SendGrid mail functionality by using django-sendgrid-v5 package to help me handle that, everything worked pretty well in the development environment including SendGrid mails like Signup user. However, when I deployed it on Railway which uses Nixpacks to manage its default project build, I kept getting this weird error that ENV cannot be blank. I followed their deployment procedures on Python since they have a similar deployment infrastructure to Heroku. I made sure that all the (env) variables needed to run the project in their platform were set correctly. I had checked my settings.py files and my .env files to know whether I was missing anything there, but I could not find the error. I even uninstall the django-sendgrid-v5 which I believed could have introduced the error, still my deployment kept on crashing. Below is the deployment build code which has been persistent. ` ╔══════════════════════════════ Nixpacks v1.16.0 ══════════════════════════════╗ ║ setup │ python310, postgresql, gcc ║ ║──────────────────────────────────────────────────────────────────────────────║ ║ install │ python -m venv --copies /opt/venv && . /opt/venv/bin/activate ║ ║ │ && pip install -r requirements.txt ║ ║──────────────────────────────────────────────────────────────────────────────║ ║ start │ python … -
MultiValueDictKeyError at /register
I keep getting this whenever I try to register a user on my test website using Django please can anyone help me out MultiValueDictKeyError at /register 'email' Request Method: POST Request URL: http://localhost:8000/register Django Version: 4.2.5 Exception Type: MultiValueDictKeyError Exception Value: 'email' Exception Location: C:\Users\user\Envs\myapp\lib\site-packages\django\utils\datastructures.py, line 86, in getitem Raised during: myapp.views.register Python Executable: C:\Users\user\Envs\myapp\Scripts\python.exe Python Version: 3.10.9 Python Path: ['C:\Users\user\Desktop\Python Tutorial\Django tutorials\myproject', 'C:\Users\user\anaconda3\python310.zip', 'C:\Users\user\anaconda3\DLLs', 'C:\Users\user\anaconda3\lib', 'C:\Users\user\anaconda3', 'C:\Users\user\Envs\myapp', 'C:\Users\user\Envs\myapp\lib\site-packages'] here is views.py code def register(request): if request.method == "POST": username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] repeat_password = request.POST['repeat password'] if password == repeat_password: if User.objects.filter(email=email).exists(): messages.info(request, 'Email Already Used') return redirect('register') elif User.objects.filter(username=username).exists(): messages.info(request, 'Username Already Used') return redirect('register') else: user = User.objects.create_user(username=username, email=email, password=password) user.save(); return redirect('login') else: messages.info(request, 'Password Not The Same') return redirect('register') else: return render(request, 'register.html',) -
how to pass a string variable in django urls?
so i made a variable named urlname in my django model and want to pass it in my urls like this: path('example/<str:url>/', views.example, name='example'), and in my views i did this: def example(request, url): example = Example.objects.get(urlname=url) context = {'example':example} return render(request, 'example/example.html', context) lets say in the models, urlname has the value 'test'. when i enter the url 'example/test/' in my browser it gives me this error: ValueError at /example/test/ Field 'id' expected a number but got 'test'. i've read and checked my code, im pretty new at coding, i hope i get my answer here and my explanation was not unclear. -
Creating a wrapper for a Python3 based project with Django
Calling for help!! I have a python3 based project (it's a huge one with a lot of command line interfaces and tools/scripts running off of it) that's basically used as a resource repo. This was actually written in python2 and I am in process of migrating it over to python3. The guy who wrote this used django.models as a way to interact with the DB. Mind you, this wasn't a django project! Now, what I am thinking is, how can I migrate this project and get it to use the same everything, by just creating a django app that wraps the models for it, without disrupting anything else?! I don't have any idea regarding where to start this from and am looking forward to suggestions from developers who have done similar sort of work! -
Django rest framework API View
I am trying to make an API view for a custom user model, however I get the following error (Method Not Allowed: /api/v1/users/create), also when I access the API through the browser I get none of the custom fields, but instead I get a media type and a content block. The serializer: class UserSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) first_name = serializers.CharField() last_name = serializers.CharField() email = serializers.EmailField() phone = serializers.IntegerField() password = serializers.CharField(write_only=True) ``` The View: ``` class CreateUser(APIView): def post(self, request): serializer = UserSerializer(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data return Response(serializer.data) ``` The url: `path('users/create', CreateUser.as_view()),` I expect to get the api view with the first_name, last_name, etc fields to create a user -
How to prevent the user from changing some fields in Django Rest?
My Django REST application has an entity where during creation/update some fields are set by the backend and not by the user, but the user can still submit requests to update these fields. Fields to change only by backend: by_backend_only = [ "company", "schedule_format", "file_url", "is_valid", "err_msg", "total_flights" } Serializer: class ScheduleSerializer(ModelSerializer): class Meta: model = RP_Schedule fields = [ "id", "name", "season", "airport", "company", "schedule_type", "schedule_format", "file_url", "err_msg", "is_valid", "total_flights", "date_range_start", "date_range_end", ] How can I prevent the user from changing these fields, but leave them in the serializer to create/update entities? -
Google analytics not tracking specific page views
Issue: When checking google analytics specific pages on my site are not being tracked. It just shows my websites name for every page view. Code: base .html <head> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-11111"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-11111'); </script> other pages: {% extends "blog/base.html" %} From what I can tell its configured correctly as it seems to be tracking events properly Cant seem to track down the cause. -
EnumType.__call__() missing 1 required positional argument: 'value' in Djano admin panel (blogs - posts)
when I was customizing my admin panel in Django , this error happened : EnumType.call() missing 1 required positional argument: 'value' in Djano admin panel (blogs - posts) enter image description here This is my admin.py code : from django.contrib import admin from .models import * Register your models here. @admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ['title','author' ,'publish', 'status' ] my app name is Blog and class name is POST then I added at the end of this code (deleted @admin.register(Post)): #admin.site.register(Post,PostAdmin) SO WHAD SHOUD I DO ??????? -
Multiple django-tenants using only one domain
I have a Django application running, right now we have different schemas into different subdomains (ex: schema 1: subdomain1.domain.com, schema 2: subdomain2.domain.com). I need to change this for different schemas into one domain. Problems: Authentication: today the auth is made in TENANT_APPS, but I think that need to change, for the auth works. Maintaining the session: I tried some solutions, but the times I managed to authenticate the user, the session was not maintained or was not created, so I could not navigate through the application. Can somebody help me? I've tried some of the issues in django-tenants (https://github.com/django-tenants/django-tenants) -
pytest-django ERROR django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured
I have a Django project with pytest and pytest-django packages. I have an app "api" with tests/ folder with all of my tests. After running pytest in the terminal, I get an error: ==================================================== short test summary info ===================================================== ERROR apps/api/tests/test_db_queries.py - django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must eithe... !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ======================================================== 1 error in 0.45s ======================================================== I have a test to test my User model. When I don't use my model and delete import from api app everything is working fine. settings.py is in meduzzen_backend folder. test_db_queries.py: import pytest from api.models import User # Create your tests here. @pytest.mark.django_db def test_queries_to_db(): User.objects.create(username="sfdf") users = User.objects.all() assert len(users) == 1 My project hirearchy: ├───.pytest_cache │ └───v │ └───cache ├───apps │ └───api │ ├───migrations │ │ └───__pycache__ │ ├───tests │ │ └───__pycache__ │ └───__pycache__ ├───code └───meduzzen_backend └───__pycache__ My tests/ folder has __init__.py file. pytest.ini: [pytest] DJANGO_SETTINGS_MODULE = meduzzen_backend.settings python_files = tests.py test_*.py *_tests.py Where is the problem? I've tried to rename my api app in INSTALLED_APPS setting in settings.py from: INSTALLED_APPS = [ ... # Django apps 'api.apps.ApiConfig', ... ] to: INSTALLED_APPS = [ ... # Django apps 'api', ... ] … -
Django form submission returning 405 when using Ajax
I have a Date form. My desired outcome is that, when the user selects a date, a list of all available time slots for that date are shown (I have a function to do this separately). They should be able to select any date and this will occur, without the page refreshing so that if they wish they can select another date. However, at the moment, upon submission of the SelectDateForm, I'm led to a 405 page (the URL does not change though). Forms.py class SelectDateForm(forms.Form): select_date = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'})) views.py: class CreateBookingView(View): template_name = 'bookings/create_booking.html' form_class1 = SelectDateForm def get(self, request, *args, **Kwagrs): date_form = self.form_class1() listing = get_object_or_404(Listing, slug=self.kwargs['slug']) context = { 'date_form': date_form, 'listing': listing, } return render(request, self.template_name, context=context) class CalculateAvailabilityView(View): def post(self, request, *args, **kwargs): selected_date = request.POST.get('selected_date') listing_slug = request.POST.get('listing_slug') listing = get_object_or_404(Listing, slug=listing_slug) # call function to calculate availability available_time_slots = calculate_dynamic_availability(listing, selected_date) # html_output = '<ul>' # for slot in available_time_slots: # html_output += f'<li>{slot}</li>' # html_output += '</ul>' return JsonResponse({'available_time_slots': available_time_slots}) urls.py from django.urls import path from .views import ( CreateBookingView, ViewBookingsView, EditBookingView, DeleteBookingView, CalculateAvailabilityView ) app_name = 'bookings' urlpatterns = [ path('createbooking/<slug>/', CreateBookingView.as_view(), name='create_booking'), path('viewbookings/<slug>/', ViewBookingsView.as_view(), name='view_booking'), path('editbooking/<slug>/', EditBookingView.as_view(), name='edit_booking'), … -
django gunicorn nginx forward to <domain>/app
I have searched tutorials and SO all over but unfortunately I still don't understand how to forward requests for my domain to a specific app (not the project). this is my project structure django_project || bjsite -- settings.py -- wsgi.py -- ... || bj -- models.py -- views.py -- templates -- ... || manage.py static requirements.txt venv ... in settings.py, this is my WSGI_APPLICATION = 'bjsite.wsgi.application' gunicorn service [Unit] Description=gunicorn daemon Requires=bj.socket After=network.target [Service] User=bj Group=www-data WorkingDirectory=/home/bj/bjsite ExecStart=/home/bj/bjsite/venv/bin/gunicorn \ --access-logfile /home/bj/bjsite_deploy/gunicorn_access.log \ --error-logfile /home/bj/bjsite_deploy/gunicorn_error.log \ --workers 3 \ --bind unix:/run/bj.sock \ bjsite.wsgi:application [Install] WantedBy=multi-user.target and my nginx cong in sites-available server { listen 80; server_name domain.de www.domain.de; location = /favicon.ico { access_log off; log_not_found off; } location / { include proxy_params; proxy_pass http://unix:/run/bj.sock; } location /static/ { root /home/bj/bjsite_deploy; } location /media/ { root /home/bj/bjsite_deploy; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/domain.de/fullchain.pem; # managed by Certb> ssl_certificate_key /etc/letsencrypt/live/domain.de/privkey.pem; # managed by Cer> include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.domain.de) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = domain.de) { return 301 https://$host$request_uri; } # managed by Certbot server_name domain.de www.domain.de; listen … -
IntegrityError at /accounts/verify/ UNIQUE constraint failed: accounts_user.mobile_number
when i try login this error is appear.first i make otp and sent to client then i login him/her. this is login view: class UserLoginView(LoginRequiredMixin, View): form_class = LoginForm def get(self, request): form = self.form_class() return render(request, 'accounts/login.html', {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): cd = form.cleaned_data rcode = random.randint(1000, 9999) send_otp_code(cd['phone'], rcode) OtpCode.objects.create(mobile_number=cd['phone'], code=rcode) request.session['login_info'] = { 'email': cd['email'], 'mobile_number': cd['phone'], 'password': cd['password'] } messages.success(request, 'we sent you a code', 'success') return redirect('accounts:verify_code') return render(request, 'accounts/login.html', {'form': form}) class UserLoginVerify(View): form_class = VerifyCodeForm def setup(self, request, *args, **kwargs): self.next = request.GET.get('next') return super().setup(request, *args, **kwargs) def get(self, request): form = self.form_class() return render(request, 'accounts/verify_code.html', {'form': form}) def post(self, request): user_session = request.session['login_info'] code_instance = OtpCode.objects.get(mobile_number=user_session['mobile_number']) form = self.form_class(request.POST) if form.is_valid(): cd = form.cleaned_data if cd['code'] == code_instance.code: user = authenticate(email=user_session['email'], mobile_number=user_session['phone'], password=user_session['password']) if user is not None: login(request, user) messages.success(request, 'you login successfully', 'success') return redirect('home:home') else: messages.error(request, 'your password or email is wrong', 'danger') return render(request, 'accounts/login.html', {'form': form}) this is my error in browser. The error shown is in the registration section, but I am logging in -
how to use simple jwt withour user class abstraction in django
"how can use simple jwt token generation and validation without using user class abstraction i wanna make something like text to generate api and have limitation for time and count of token request i have model named domain its gonna send request to a server under my server and i have a service model that have that server details to send request now i want to make it with token validation cause i want to have limit for it " -
Django form is rendering via AJAX but with no data inside fields
I'm trying to render a Django form with AJAX : Here are my files : Models.py class models_projects(models.Model): id = models.CharField(primary_key=True, max_length=50) reference = models.CharField(max_length=50) model = models.CharField(max_length=50) class Meta: db_table = 'table_projects' Forms.py class forms_projects(forms.ModelForm): id = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={"placeholder":"id", "class":"form-control"}), label="id") reference = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={"placeholder":"reference", "class":"form-control"}), label="reference") model = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={"placeholder":"model", "class":"form-control"}), label="model") class Meta: model = models_projects exclude = ("user",) View.py def update_project_mobile(request): project_id = request.POST.get('project_num') if request.user.is_authenticated: record = models_projects.objects.get(id = project_id) projects_form = forms_projects(request.POST or None, instance=record) if projects_form.is_valid(): projects_form.save() return render(request, 'projects_mobile.html', {'projects_form':projects_form}) else: messages.success(request, "You Must Be Logged In...") return redirect('home') template.html <select name="project_num" id="project_num"> <option value="2"> "2" </option> </select> <div id="projects_container" ></div> <!-- This is where projects_mobile.html is rendered --> <script> function load_projects (){ $.ajaxSetup( { data: {project_num: $('#project_num').val(), csrfmiddlewaretoken: '{{ csrf_token }}' }, }); $.ajax({ type: "POST", url: "../update_project_mobile/", //dataType: 'json', success: function (data) { $("#projects_container").html(data); } }); } </script> urls.py ... path('update_project_mobile/', views.update_project_mobile,name='update_project_mobile'), ... projects_mobile.html <body> {{ projects_form }} </body> The form is rendering well as the content of projects_mobile.html displays well inside the <div id="projects_container" ></div> but there is no data inside the form's fields, only the placeholders are displayed. The Database is very easy and there is an entry … -
Can Django be utilized in a Python chat app based on sockets
i am new in python. i have created a chat app using kivy and socket(not socket-io and not web-socket). it works well but i want to use Django in server side. "Can Django be utilized in a Python chat app based on sockets, incorporating its features for user authentication, database management, and static content handling alongside real-time communication?" -
Django form wizard can't return to the first step after last summarized page
I use SessionWizardView for gain initial data from user via wizard. I have four required steps and one optional (customed). After last step I forward to summarized page. If press refresh browser's button at this point I will expect redirect to the first page of my wizard. But in fact I redirected to second page, for some reason. Could anyone help me to undestand this behavior? This is my templates: TEMPLATES = { 'select_type': "poneraapp/select_type.html", 'select_features': "poneraapp/select_features.html", 'select_model': "poneraapp/select_model.html", 'set_objects_number': "poneraapp/set_objects_count.html", 'select_support': "poneraapp/select_support.html" } My form list: form_list = [ ('select_type', FormStepOne), ('select_features', FormCustomStep), ('select_model', FormStepTwo), ('set_objects_number', FormStepThree), ('select_support', FormStepFour) ] done function: def done(self, form_list, **kwargs): self.storage.reset() return render(self.request, 'done.html', { 'form_data': [form for form in form_list], }) -
How to apply Bootstrap style to RichTextUploadingField?
I attached CKeditor to my site. When I load a high-resolution image, all Bootstrap responsiveness breaks. This can be corrected - you need to manually assign the style and CSS class to the picture. It’s inconvenient to do this manually every time, and the styles for other elements will also have to be written manually, and this takes a long time. How can I apply Bootstrap style to all elements of this field? Maybe there is some kind of Bootstrap settings preset that needs to be written somewhere in settings.py? I tried to manually set the image style in the ckeditor editor. I want the Bootstrap style to be automatically applied to all elements (such as , , , etc.) -
Django Sending Email: sending activation use django sendgrip
I want to send the email activation using django registration. Below is my production settings.py EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'apikey' # EMAIL_HOST_PASSWORD = get_secret('SENDGRID_API_KEY') EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' DEFAULT_FROM_EMAIL = 'noreply@uralholidays.com' # EMAIL_BACKEND = "sendgrid_backend.SendgridBackend" The project is running fine on my local server. but when I pushed it to the production (beta version)- it did not have any SSL. I need the settings to work for both production (beta version) and (the main version -having SSL). I am getting the below issue. SMTPServerDisconnected at /accounts/signup/ Connection unexpectedly closed Request Method:POSTRequest URL:http://beta-uralholidays.com/accounts/signup/Django Version:3.2.20Exception Type:SMTPServerDisconnectedException Value:Connection unexpectedly closedException Location:/usr/lib/python3.10/smtplib.py, line 405, in getreplyPython Executable:/usr/bin/python3Python Version:3.10.12Python Path:['/home/booking_app-beta-20230928-130136/booking_app/booking_app', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/usr/local/lib/python3.10/dist-packages', '/usr/lib/python3/dist-packages']Server time:Thu, 28 Sep 2023 14:05:55 +0000 I am trying to make it work in both my local server the production beta version (not having SSL) and the production main version (having SSL). Please suggest to me the exact changes I need to do. The hosting web server is digital ocean