Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JavaScript Redundancy Selection Prevention and Delete Button Implementation
I am implementing a page that displays information about the option when I select the option of the product using JavaScript. My source code is attached below. If I select an option, I want to display the option information, price, and product name, and if I press del_li_btn, I want to delete that option information. However, according to my source code, only the price is deleted. What should I do to delete all the information I've posted? Also, I want to implement the option to be selected only once. If you answer my question, I'd really appreciate it. I look forward to your kind cooperation. html <form method="POST" action="{% url 'zeronine:join_create' id=product.product_code %}"> <div class="form-group row" style="margin-top: -5px"> <label for="optionSelect" class="col-sm-6 col-form-label"><b>옵션</b></label> <div class="col-sm-6" style="margin-left: -90px;"> <select type="text" class="form-control" name="value_code" id="optionSelect" value="{{ form.value_code }}"> <option value="none">옵션을 선택하세요.</option> {% for option in option_object %} {% if option.option_code.option_code.option_code == value.option_code %} {%if option.product_code == product %} <optgroup label="{{option.name}}"> {% for value in value_object %} {% if value.option_code.option_code == option.option_code %} {%if value.product_code == product %} <option data-price="{{value.extra_cost}}"value="{{value.value_code}}">{{value.name}} (+{{value.extra_cost}}원)</option> {% endif %} {% endif %} {% endfor %} {% endif %} {% endif %} {% endfor %} </optgroup> </select> </div> <div id="selectOptionList" style="margin-top:10px; … -
How to use <input type="datetime-local"> with django function based view
I want to make a simple html form with datetime-local input field. Django in the backend to receive and save it to the database. my template: <form method="POST"> {% csrf_token %} <input type="datetime-local" name="startingTime" class="form-control" required> </form> my models.py: class QuestionSet(models.Model): startingTime = models.DateTimeField() In views.py: def index(request): if request.method == 'POST': this_startingTime = request.POST['startingTime'] QuestionSet_obj = QuestionSet.objects.create( startingTime = this_startingTime ) QuestionSet_obj.save() return redirect('app:index') But this gives error. Maybe I need to change the format of this_startingTime . How can I fix this? -
Data is not being retrieve from Django Rest to Flutter App
I am trying to retrieve json data from django api restframework to flutter app but it shows nothing. Even retrieveRecord function in main.dart do not print text when app starts. django returning json code on http://localhost:8000/records/?format=api it also shows json without format on http://localhost:8000/records/?format=json but in flutter list views it shows nothing Main.dart import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter_application_1/ann.dart'; import 'package:http/http.dart' as http; import 'package:http/http.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Test Phase Assignment', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Test Phase Assigment'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { Client client = http.Client(); List<AnnSystem> annSystem = []; @override void initState() { _retrieveRecord(); super.initState(); } _retrieveRecord() async { annSystem = []; List response = json.decode((await client .get(Uri.parse('http://10.0.2.2:8000/records/?format=json'))) .body); response.forEach((element) { annSystem.add(AnnSystem.fromMap(element)); }); print(response); // it does not print on terminal print("function calling"); //it does not print on terminal setState(() {}); } _addRecord() {} @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: … -
Compare different layers using Django and OpenLayers
I'm developing a GIS project with Django and Openlayers. I've created a comparison map that with a slider allow to compare two WMS. Now I would like to do something more tricky because I would to give to the user the possibility to select which WMS to compare. So in my model I've created a ForeignKey that represent a static layer and a ManyToManyField that contain the list of layers to compare with the static layer. I'm be able to create a template that give to the user the possibility to active/deactive a single layer: {% for layer in webgis_single.layers.all %} const source{{ layer.wms_layer_name|cut:"_" }} = wmsMainSource.createWMSLayer( '{{ layer.title }}', '{{ layer.wms_layer_path }}', '{{ layer.wms_layer_name }}', {% if layer.wms_layer_style == None %}null{% endif %}{% if layer.wms_layer_style != None %}'{{ layer.wms_layer_style }}'{% endif %}, {{ layer.set_max_zoom }}, {{ layer.set_min_zoom }}, {{ layer.set_zindex }}, {{ layer.set_opacity }} ); $('#{{ layer.pk }}_{{ layer.wms_layer_name }}').on('change', function() { let isChecked = $(this).is(':checked'); if (isChecked) { mapCanvas.addLayer(source{{ layer.wms_layer_name|cut:"_" }}); } else { mapCanvas.removeLayer(source{{ layer.wms_layer_name|cut:"_" }}); } }); {% endfor %} But I'm locked on the possibility to deactive the active layer when there is a list of activable layers: {% for layer in webgis_single.map_swipe_right.all %} const … -
How can i make a Query through Many-To-Many-Relationship
I want to display the trainer for a course date. A course can have several dates and a different trainer can be used on each date. A trainer can have a different role on each course date. (Instructor, helper...) How do I make the correct query? Are the models correct for this? Models: class Course_dates(models.Model): date = models.DateField() start = models.TimeField() end = models.TimeField() def __str__(self): return str(self.id) """return self.date.strftime("%d.%m.%Y")""" class Course(models.Model): course_number = models.CharField(max_length=24, blank=True) course_location = models.ForeignKey(Course_location, on_delete=models.CASCADE) course_dates = models.ManyToManyField('Course_dates', through="Course_Course_dates") def __str__(self): return self.course_number class Trainer_Course_Course_date_role(models.Model): trainer = models.ForeignKey(Trainer, on_delete=models.CASCADE) role = models.CharField(max_length=24, blank=True) def __str__(self): return str(self.id) class Course_Course_dates(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) course_dates = models.ForeignKey(Course_dates, on_delete=models.CASCADE) trainer = models.ForeignKey(Trainer_Course_Course_date_role, on_delete=models.CASCADE, null=True) def __str__(self): return str(self.id) class Trainer(models.Model): salutation = models.CharField(max_length=8,choices=GENDER_CHOICES) last_names = models.CharField(max_length=56) first_names = models.CharField(max_length=56) date_of_birth = models.DateField() address = models.ForeignKey(Address, on_delete=models.CASCADE) email = models.EmailField() phone = models.CharField(max_length=56, blank=True) mobile = models.CharField(max_length=56, blank=True) def __str__(self): return self.last_names View: def course(request): courses = Course.objects.all() course_list = [] for course in courses: sorted_date_list = course.course_dates.all().order_by('date') course_list.append({'course': course, 'sorted_date_list': sorted_date_list }) context = { 'course_list': course_list, } return render(request, 'kursverwaltung_tenant/course.html', context) -
Cant access a private s3 image however I can upload
I have created an s3 bucket. I have created a user and granted the access AmazonS3FullAccess. The images are uploaded correctly, however the link is not working and I get the following xml error: "The request signature we calculated does not match the signature you provided. Check your key and signing method" I am new to aws and perhaps I am doing something wrong. I want the link to be secure, e.g. with an expiration date. Settings: AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = 'xxxxxx' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_REGION_NAME = 'eu-central-1' AWS_S3_SIGNATURE_VERSION = 's3v4' -
Read with pandas once and keep many csv files open or read and close each time
I am doing a project with Django in which I generate several graphs with Plotly and do operations with CSV files that I read, write and modify (also download or delete) with pandas. These files depend on the company to which the user belongs, for example, if it belongs to the TOYOTA company, the file is in data / toyota, and if it belongs to Honda, it is in data / honda. My question is which is better, to read the 50 csvs that will be used when the user logs in, or to read and close the csvs as needed. For example, in my url example.com/analysis, these functions are called: @login_required def analysis(request): data_report = pd.read_csv(f'data/{request.user.company}/test/data_report.csv', sep=';', encoding='utf-8') context = {} for column in data_report.columns: context[column] = data_report.loc[0, column] data_roles = pd.read_csv(f'data/{request.user.company}/test/data_roles.csv', sep=';', encoding='utf-8') # Here more code that doesn't matter ... graphs = [] marker = { 'color': 'rgb(0,150,209)', 'opacity': 0.5, } graphs.append( go.Scatter(x=n_users, y=n_perms, mode='markers', name='Line y1', marker=marker) ) layout = { 'xaxis_title': 'Number of users', 'yaxis_title': 'Number of permissions', 'height': 400, } plot_div = plot({'data': graphs, 'layout': layout}, output_type='div') context['plot_div'] = plot_div return render(request, 'analysis.html', context) @method_decorator(csrf_exempt) def update_pie_chart(request): if request.method == 'POST' and request.is_ajax(): selected … -
Appointment slot from uml to django
I would like to know if my django model are correct according to this class diagram : The diagram : The code : class Student(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) class Staff(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) class AppointmentSlot(models.Model): staff = models.ForeignKey('Staff', null = True, on_delete = models.CASCADE) date = models.DateField(null = True) start = models.TimeField(null=True, blank=True) end = models.TimeField(null=True, blank=True) student = models.ForeignKey('Student', null=True, on_delete=models.CASCADE) Do I have made some errors ? -
Python Why Django won't let me load a new product?
I'm in this page: Filling the details The ling is https://upload.wikimedia.org/wikipedia/commons/c/cb/Oranges_white_background.jpg When I'm pressing 'save' it gives me this: Error message Couldn't understand the issues I tried various ways to solve it like take another picture and re-run the server. From Mosh Hamedi tutorial: https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=20225s at 05:42:20 -
rest_framework.permissions.IsAuthenticated is never executed
I am trying to only let execute a method to people who has signed in. I am using JSONWebTokenAuthentication This is the implementation: class vistaUsuarios(APIView): permission_classes = (IsAuthenticated,) def usuario(request): print("USUARIO ",request.user.is_authenticated) if request.method == 'GET': usuario = None id = request.GET.get("id") if id is not None: usuario = Usuario.objects.get(pk=id) usuarios_serializer = UsuarioSerializer(usuario) return JsonResponse(usuarios_serializer.data, safe=False) settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), 'NON_FIELD_ERRORS_KEY': 'global', } # JWT settings JWT_AUTH = { 'JWT_ALLOW_REFRESH': True, 'JWT_EXPIRATION_DELTA': timedelta(days=2), } # allauth SITE_ID = 1 ACCOUNT_EMAIL_VERIFICATION = 'none' # JWT settings REST_USE_JWT = True INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'subroutinesbackapp', 'django.contrib.sites', 'allauth', 'allauth.account', 'rest_auth', 'rest_auth.registration' ] ... The problem is that IsAuthenticated is never executed. I have a print there, and never do. class IsAuthenticated(BasePermission): """ Allows access only to authenticated users. """ def has_permission(self, request, view): print("holaaaaaaa") return bool(request.user and request.user.is_authenticated) The method usuario from vistaUsuarios class, always execute. Even though the print print("USUARIO ",request.user.is_authenticated) shows USUARIO false because I haven't passed a valid token. How can I make the IsAuthenticated method execute? Thanks, in advance -
How to get a button in template to change a model? Django
I am trying to build an app with a like-dislike functionality such that by clicking a like button you get added to a string of users that liked and get removed from the dislike string if you were there. How can i do that? I added some of the relevent code: the button: <button type='submit'> Like </button> And the model im trying to change: title = models.CharField(max_length=30) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) auther = models.ForeignKey(User, on_delete=models.CASCADE) views_number = models.IntegerField(default=0) user_like_id = models.CharField(validators=[int_list_validator], max_length = 10000000, default = "") user_dislike_id = models.CharField(validators=[int_list_validator], max_length = 10000000, default = "") -
I am getting Key error message while trying to save my Django form. I am not able to save data from Django form to the database
I am trying to add client to my client model along with the user model using Django forms. But as of now I am getting a key error. I am not able to figure out what is wrong with this and would appreciate some help on this one. My clients model is this class Clients(models.Model): id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE) primaryphone = models.CharField(max_length=15, unique=True) location = models.CharField(max_length=30, choices=States) project_id = models.ForeignKey(Projects, on_delete=models.DO_NOTHING, default=1) contract_id = models.ForeignKey(Contracts, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() The view for this are def add_client(request): form = AddClientForm() context = { "form": form } return render(request, 'admintemplate/add_client_template.html', context) def add_client_save(request): if request.method != "POST": messages.error(request, "Invalid Method") return redirect('add_client') else: form = AddClientForm(request.POST, request.FILES) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] phone = form.cleaned_data['phone'] location = form.cleaned_data['location'] project_id = form.cleaned_data['project_id'] contract_id = form.cleaned_data['contract_id'] try: user = CustomUser.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name, user_type=3) user.clients.location = location user.client.primaryphone = phone project_obj = Projects.objects.get(id=project_id) user.clients.project_id = project_obj contract_obj = Contracts.objects.get(id=contract_id) user.clients.contract_id = contract_obj user.clients.save() messages.success(request, "Client Added Successfully!") return redirect('add_client') except: messages.error(request, "Failed to Add Client!") return redirect('add_client') else: return redirect('add_client') … -
NuxtJS with NestJS
Im really confused and i wanted soemone to explain this for me, so if im not wrong is NuxtJS just a vue front end framework and NestJS a node based backend framework? if i work with both it shouldnt matter right? it should be like working with some x frontend framework with other y backend framework. I want a good framework to use with my NuxtJS application that has good security implemented, should i work with node? nest? express? django? What u guys recommend me? Sorry for being a newbie haha. -
How to save data from form.ModelForm in database and also show new post in template?
View.py def create_post(request): form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.date_posted = timezone.now() post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm() return render(request, 'post_detail.html', {'form': form}) Forms.py from django import forms from django.forms import ModelForm, fields from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'description', 'date_posted', 'author'] -
Unable to install mod_wsgi with command <pip install -v mod_wsgi>
I am trying to set up a Django-Apache platform to host my Django Application on my local network. I am facing an issue with installing the mod_wsgi module with the command : ''' pip install mod_wsgi ''' The command is actually downloading all the versions of mod_wsgi starting from mod_wsgi-4.1.0 to mod_wsgi-4.9.0 and is ultimately getting terminated while raising the error: ERROR: No matching distribution found for mod_wsgi and ModuleNotFoundError: No module named '_distutils_hack'. Given below is the screenshot of the issue: Please help me resolve this. -
TypeError: 'RelatedManager' object is not iterable - serializers.ListField()
I have this 2 models: Route and Order. Route has a relation oneToMany with Order as you can see: class Order(models.Model): customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='customer') retailer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='retailer') date_publish = models.DateField(default=datetime.date.today) date_available = models.DateField() weight = models.DecimalField(decimal_places=2, max_digits=5) description = models.CharField(max_length=500, null=True) route = models.ForeignKey(Route, related_name='orders', null=True, on_delete=models.CASCADE) class Route(models.Model): day = models.DateField() warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) start_time = models.TimeField() When a order is created it's route should be null. When a route is created I want to associate orders with the route created, so I have the following Route Serializer. class routeSerializer(serializers.ModelSerializer): orders = serializers.ListField() class Meta: model = Route fields = ['day', 'warehouse', 'start_time', 'orders'] def create(self, validated_data): keys_to_extract = ['day', 'warehouse', 'start_time'] route_subset = {key: validated_data[key] for key in keys_to_extract} print(validated_data) route = Route.objects.create(**route_subset) for order_data in validated_data['orders']: Order.objects.filter(id=order_data).update(route=route) return route The body of the request should be like this: { "day" : "2021-12-12", "warehouse": "1", "start_time": "7:00", "orders": [ 1,2,3,4,5,6,7 ] } I was doing this in a different way, but I was told to do this in this way, but with orders = serializers.PrimaryKeyRelatedField(). But in that way I can't get the 'orders' from validated_data since it just come with 'day', 'warehouse' … -
How to merge data from two models
I have a VideoView model which tracks data about a user who watched a video. I am now creating a Todo model which will keep track of what users need to watch. I figured I may as well merge these models into one Todo model and remove the VideoView model. What is a common procedure for moving the data from one model to another? I see a couple different options but maybe there are other options. The models: class VideoView(models.Model): user = models.ForeignKey(Employee, on_delete=models.CASCADE) video = models.ForeignKey(Video, on_delete=models.CASCADE) date_time = models.DateTimeField(auto_now=True) class Todo(models.Model): created_on = models.DateTimeField(auto_now_add=True) completed_on = models.DateTimeField(auto_now=True) user = models.ForeignKey(Employee, on_delete=models.CASCADE) video = models.ForeignKey( Video, on_delete=models.CASCADE, null=True, blank=True, related_name='todos' ) Option 1: Write a view which opens each VideoView then creates new Todo instances with the data of each. Then visit the view in the browser to migrate the data. This option seems to be decent as the code will be readable and I can delete Todos if there are mistakes. Option 2: Same thing but in the shell. Less readable. More prone to errors. Option 3: Is there a way to simply move the field from one model to another? Or maybe doing a multi-stage(?) migration, where … -
How to "create or update" using F object?
I need to create LeaderboardEntry if it is not exists. It should be updated with the new value (current + new) if exists. I want to achieve this with a single query. How can I do that? Current code looking like this: (2 queries) reward_amount = 50 LeaderboardEntry.objects.get_or_create(player=player) LeaderboardEntry.objects.filter(player=player).update(golds=F('golds') + reward_amount) PS: Default value of "golds" is 0. -
NOT NULL constraint failed: plegdetect_fileupload.user_id
I am building a plagiarism detector using Django. Whenever a user upload a file and click on upload , That file goes to my media file . But I got the error that NOT NULL constraint failed: plegdetect_fileupload.user_id . my models.py is : from django.db import models from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class FileUpload(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) file = models.FileField(upload_to='files') def __str__(self): return self.user.username my view.py is: class PostCreateView(CreateView): model = FileUpload fields = ['file'] def form_valid(self, form): form.instance.author = self.request.user return super(PostCreateView, self).form_valid(form) my urls.py is : from django.urls import path from . import views urlpatterns = [ path('',views.home,name='home'), path('post/new/',views.PostCreateView.as_view(),name='post-create'), ] Thanks in advance -
How to Convert MP4 to HLS with Multiple Audio and Multiple Video Quality in Python/Django?
I have tried with ffmpeg library and I can convert videos mp4 to hls with multiple quality but multiple audio is not working. > [Commands Excuting from Terminal] And with subprocess library calling subprocess.call. > [ Want to know is this the right way? to do with Django? ] -
<form method="get"> is send as POST (Django)
I'm trying to make django-filter work, and it have worked, but now it suddenly have stopped. The issue is that the submit button in the filter seems to be sending a POST request and not GET Below is a snippet of the HTML code <div class="form-group"> <form method="POST"> {% csrf_token %} {{form|crispy}} <button class="btn btn-outline-success" type="submit">Add product</button> </div> <div id="filter-menu"> <form method="get"> {{filter.form.nick_name|as_crispy_field}} <br> {{filter.form.domain|as_crispy_field}} <br> <button class="btn btn-outline-success" type="submit">Apply filter</button> </form> </div> I do have a POST-request submit button above as seen, and it seems like it's the one being triggerd, since when I debug the application, request.method == "POST" when pressing the apply filter button. If needed, a snippet of my view is here (omitted messages and stuff) def MyView(request): user = request.user user_products = MyModel.objects.filter(user=user).all() ### Create filters ### filter = get_user_filter_fields_wishlist(user_products) #Helper function for returning filters filter = filter(request.GET,queryset = user_products) if request.method == "POST": post_form = MyForm(request.POST) if post_form.is_valid(): filter = get_user_filter_fields_wishlist(user_products) filter = filter(request.GET,queryset = user_products) form = MyForm() context = { "form":form, "filter":filter } return render(request, "myapp/my_html.html",context=context) else: #invalid post_form context = { "form":post_form, "filter":filter } return render(request, "myapp/my_html.html",context=context) else: #Get request form = MyForm() context = { "form":form, "filter":filter } return render(request, … -
django CSS & Javascript not loading in HTML files?, error 404?
I have put some static files for CSS Javascript and Jquery in my file static. I have put load static in my HTML and it doesn't respond properly to the HTML. Do you have anything else to do with it? output error setting.py file -
RuntimeError: set_wakeup_fd only works in main thread of the main interpreter when adding a proxybroker job in django-apscheduler
I tried to use django-apscheduler to add a proxybroker job. There is no problem to run test_proxybroker.py and got proxies returned. But I got this error when I run the django-apscheduler command. set_wakeup_fd only works in main thread of the main interpreter #test_proxybroker.py import asyncio from proxybroker import Broker # https://proxybroker.readthedocs.io/en/latest/examples.html def broke(): async def show(proxies): while True: proxy = await proxies.get() if proxy is None: break print('Found proxy: %s' % proxy) try: loop = asyncio.get_event_loop() except: new_loop = asyncio.new_event_loop() asyncio.set_event_loop(new_loop) loop = asyncio.get_event_loop() proxies = asyncio.Queue() broker = Broker(proxies) tasks = asyncio.gather( broker.find(types=['HTTP', 'HTTPS'], limit=10), show(proxies)) loop.run_until_complete(tasks) #runapscheduler.py. (the django command file) ... def test_job(): try: broke() except: pass ... -
Recent user visits in Django
I have a visit model on my site that is strong enough to use the page of a product, an object is registered with the product and the user's IP. If anyone knows, thank you -
Django appeared ajax error after uploading the site to heroku
I am making a portfolio site in django and I wanted to upload it to heroku. Everything worked fine on localhost, but after uploading the site to heroku, I started getting errors when using AJAX. Im using ajax for register user and sending email massage Js $.ajax({ type: 'POST', url: "", enctype: 'multipart/form-data', data: fd, success: function(response) { mess = $('.b-popup_message') if (response.status == 'login') { window.location.href = '/'; mess.text('Wait...') } else { mess.text('We have sent the code to you by mail. Enter it') } }, error: function(error) { console.log(error); }, cache: false, contentType: false, processData: false, }) return false view.py def main(request): global code login_form = LoginForm(request.POST or None) data = {} if request.method == 'POST': if login_form.is_valid(): if request.is_ajax(): email = request.POST.get('email') data['email'] = email data['code'] = login_form.cleaned_data['code'] if not code or code != data['code']: sleep(10) code = generate_code(4) send_email_message = EmailMessage('DONUTELA CODE', f'Enter this code on the register form: {code}', to=[email]) send_email_message.send() data['status'] = 'sent_code' elif code == data['code']: if User.objects.filter(email=email).exists(): user = User.objects.get(email=email) else: user = User.objects.create_user(username=generate_code(20), email=email, password=generate_code(20)) login(request, user, backend='MainApp.Backends.PasswordlessAuthBackend') data['status'] = 'login' return JsonResponse(data=data) added_products_cookies = request.COOKIES.get('added_products') added_product_names = [] # все добавленые продукты по названию added_products_dict = {} # вид {название продукты: …