Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'ImageField' object has no attribute 'value_from_datadict'
I'm trying to poplulate the fields in my "CreateDealerForm" for when I choose to edit. So far I can only populate the featured_image field and if I add featured_image to the widgets dictionary I get: 'ImageField' object has no attribute 'value_from_datadict' forms.py class CreateDealerForm(forms.ModelForm): class Meta: model = Dealer fields = ('name', 'phone','website', 'address', 'featured_image',) widgets = { 'name': forms.TextInput(attrs={'class': 'dealer-name-field', 'placeholder': 'Dealer name'}), 'phone': forms.TextInput(attrs={'class': 'dealer-phone-field', 'placeholder': 'Dealer phone'}), 'website': forms.TextInput(attrs={'class': 'dealer-website-field', 'placeholder': 'Dealer website'}), 'address': forms.TextInput(attrs={'class': 'dealer-address-field', 'placeholder': 'Dealer address'}), "featured_image": forms.ImageField(), } views.py def update_dealer_view(request, slug): instance = get_object_or_404(Dealer, slug=slug) form = CreateDealerForm(request.POST, request.FILES, instance=instance) if form.is_valid(): dealer = form.save(commit=False) dealer.save() return redirect('main:homepage_view') context = { "title": "Update - Dealer", "form": form, "instance": instance, } return render(request=request, template_name="main/create/create_dealer.html", context=context) -
TypeError: create_superuser() missing 2 required positional arguments: 'first_name' and 'last_name'
I've checked other questions with same problem and tried solving with the solutions but none helped. I neither see 'First Name' nor 'Last Name' input while creating a super user in the terminal I've been following this tutorial 'https://www.youtube.com/watch?v=HshbjK1vDtY&t=3422s' but the tutor doesn't face any problem while doing the exactly same thing I'm doing so there's nowhere I could find solution This is my models.py from django.db import models from django.contrib.auth.models import( AbstractBaseUser, BaseUserManager ) class UserManager(BaseUserManager): def create_user(self, first_name, last_name, email, password=None, is_active=True, is_staff=False, is_admin=False): if not first_name: raise ValueError("Users must have an first name") if not last_name: raise ValueError("Users must have an last name") if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have a password") user = self.model( email=self.normalize_email(email) ) user.first_name = first_name user.last_name = last_name user.set_password(password) user.staff = is_staff user.admin = is_admin user.active = is_active user.save(using=self._db) return user def create_staffuser(self, email, first_name, last_name, password=None): user = self.create_user( email, first_name, last_name, password=password, is_staff=True ) return user def create_superuser(self, email, first_name, last_name, password=None): user = self.create_user( email, first_name, last_name, password=password, is_admin=True, is_staff=True ) return user class User(AbstractBaseUser): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) email = models.EmailField(max_length=254, unique=True) … -
Django INSTALLED_APPS can't get apps with underscores right - why?
I've got a Django project, in there two apps, let's say cheese and mouse_and_cat. While adding both to INSTALLED_APPS, I first wrote there INSTALLED_APPS = [ 'cheese.apps.CheeseConfig', 'mouse_and_cat.apps.Mouse_and_catConfig', ] but it resulted only in error that "mouse_and_cat.app is not a package". I tried to change it to 'mouse_and_cat.apps.MouseandcatConfig', but it didn't help - somehow I thought that would be the case. I searched in Google and kept the first "cheese line", but changed second to only 'mouse_and_cat' - and it works now. But... what's the case with underscores, why does Django act so weird, when an app is named this way? Is there something I'm missing here? Now I know underscores aren't preferred naming pattern and so I will avoid it, but it still bothers me, because I believe this error was somehow more my fault than Django's. -
Django form init override 'Select a valid choice' form validation error
I am trying to override the __init__ method to update the queryset on the roles field of my form. This is throwing a validation error which says: Select a valid choice. That choice is not one of the available choices. ..then returns the form with no options in this roles field. forms.py class UserRegisterForm(UserCreationForm): role = forms.ModelChoiceField( queryset=EmployeeType.objects.all(), empty_label=None, required=False) supervisor = forms.ModelChoiceField( queryset=Employee.objects.all(), required=False) def __init__(self, *args, **kwargs): self.company = (kwargs.pop('company', None)) super(UserRegisterForm, self).__init__(*args, **kwargs) self.fields['role'].queryset = EmployeeType.objects.filter(company=self.company) self.fields['supervisor'].queryset = Employee.objects.filter(company=self.company, supervisor=None) views.py def register(request): """ Employee registration. **Context** ``Employee`` An instance of :model:`employees.Employee` **Template:** :template:`employees/register.html` """ if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() employee = Employee.objects.get(username=form.instance) user_count = request.tenant.employee_set.count() if user_count > 1: form.instance.is_active = False if form.instance.role: group_obj = form.instance.role.group group = Group.objects.get(name=group_obj) employee.groups.add(group) company = request.tenant form.instance.company = company phone_verify = PhoneVerify.objects.create(employee=form.instance) phone_verify.save() form.save() messages.success(request, f'Your account has been created! Users must' f' be approved by a supervisor before you can login!') return redirect('verify-redirect') else: form = UserRegisterForm(company=request.tenant) return render(request, 'employees/register.html', {'form': form}) How do I fix the form validation error? -
What Is The Best Way To Create A Front-End For A Client's Customer Database?
I plan to use Django to make a simple website/mobile application for a client who wishes to have a front-end for a customer database. Frankly, all I need to do is provide a form for him to create, update and delete a customer entry. I also need to list all the entries on a different page (basically a table) and have a link to a page for each individual customer so he can view the customer's details and write notes in a textarea that will be saved for future reference. Is using ModelForm the best way to go about this? Also, I am very new to Django so I'm not sure if there are easier ways of doing this. -
How to insert scraper result to database in Django
I'm building a scraper that get product information from e-commerce websites. When I run python scraper.py and pass "iPhone" as argument the scrapper will return a JSON object containing products from 20 online shopping websites. I want these products to be added to the database every time I run the scrapper. Here's a portion of my code scraper.py class Scraper: def __init__(self): pass def amazon(self, keyword): try: output_list = [] """ More code Here """ for deal in amazon_json: output_dict = {} output_dict['seller'] = 'amazon' output_dict['asin'] = deal.get('ASIN','') deal["detailPageURL"] += aff_tag output_dict['advertiser_url'] = deal.get('detailPageURL','') output_dict['main_image'] = deal.get('imageUrl','') output_dict['is_prime'] = deal.get('isPrimeEligible','') output_dict['old_price'] = deal.get('listPrice','') output_dict['price'] = deal.get('price','') output_dict['rating'] = deal.get('rating','') output_dict['description'] = deal.get('subtitle','') output_dict['title'] = deal.get('title','') output_dict['reviews_count'] = deal.get('totalReviews','') output_list.append(output_dict) return output_list except: return None except Exception as e: return e def finalRun(self, keyword): pondeals = {} pondeals['amazon'] = self.amazon(keyword) """ More code. """ return pondeals obj = Scraper() search_term = input("> ") pondeals_results = obj.finalRun(search_term) pp.pprint(pondeals_results) models.py class ProductManager(models.Manager): def search(self, query=None): """ Some search code here """ ) qs = qs.filter(or_lookup).distinct() # distinct() is often necessary with Q lookups return qs # This admin model contains all the products in the database class Product(models.Model): similarity_id = models.CharField(max_length=255, blank=True, null=True) … -
How to secure AJAX call with Django backend?
I want to secure my django view from responding to someone who isn't logged in to my app. I use AJAX to get data, but I can also get that for example by Postman what is unwanted. I'm doing POST request and I'm checking if CSRF token is set, but it isn't good enough secure. What can I do and how? PS. I read some articles before, but every where I looked was too complex. If I can, please explain that in the easiest way possible. Thank you! -
The password of User models is encrypted?
In my model i extend User model, so the password is from User model. But when acess the objects from manage.py shell i can see all password from my users. from django.contrib.auth.models import User class User(User, UGCModel): pass from user.models import User user = User.objects.all()[0] print(user.password) Then the print: 12345 that i saved using serializer: views.py class UserViewSet(viewsets.ModelViewSet): lookup_field = 'pk' model = User queryset = User.objects.all() serializer_class = UserCreateSerializer Is the password encrypted? -
django, what problem ? TypeError Comment() got an unexpected keyword argument 'comment_text'
TypeError at /articles/1/leave_comment/ Comment() got an unexpected keyword argument 'comment_text' Request Method: POST Request URL: http://127.0.0.1:8000/articles/1/leave_comment/ Django Version: 3.0.1 Exception Type: TypeError Exception Value: Comment() got an unexpected keyword argument 'comment_text' Exception Location: C:\Users\Dima\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py in __init__, line 500 Python Executable: C:\Users\Dima\AppData\Local\Programs\Python\Python38\python.exe views from django.shortcuts import render from .models import Article, Comment from django.http import HttpResponseRedirect, Http404 from django.urls import reverse def index(request): latest_articles_list = Article.objects.order_by('-pub_date')[:5] return render(request, 'articles/list.html', {'latest_articles_list': latest_articles_list}) def detail(request, article_id): try: a = Article.objects.get(id = article_id) except: raise Http404('Статья не найдена') return render(request, 'articles/detail.html', {'article': a}) def leave_comment(request, article_id): try: a = Article.objects.get(id = article_id) except: raise Http404('Статья не найдена') a.comment_set.create(author_name = request.POST['name'], comment_text = request.POST['text']) return HttpResponseRedirect( reverse('articles:detail', args(a.id,)) ) detail.html {% extends 'base.html' %} {% block title %}{{article.article_title}}{% endblock %} {% block content %} <h2>{{article.article_title}}</h2> <p>{{article.article_text}}</p> <em>{{article.pub_date}}</em> <hr> <form action="{% url 'articles:leave_comment' article.id %}" method="POST"> {% csrf_token %} <input type="text" required placeholder="Ваше имя" name="name"><br> <textarea name="text" required="" placeholder="Текст комментария" cols="30" rows="10"></textarea></br> <button type="submit">Оставить комментарий</button> </form> {% endblock %} -
Why is related create() checking for id using Django ORM?
I'm getting this error: DETAIL: Key (user_id)=(1) already exists. when I run: from records.models import Profile from django.contrib.auth.models import User users = User.objects.all() for user in users: p = Profile.objects.create(user=user) I trying to create a profile for each of the existing users. Profile looks like this: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) auto_complete_look_up_field = models.CharField(max_length=200,db_column='AutoCompleteLookUpField', blank=True, null=True) What's happening here? I would expect that user_id to exist; that is the user I want to assign to Profile. Why is this even an error? -
How to access html element id, in django backend?
I'm learning Django and currently building blog app. I have a problem. I built functionalities to adding new posts and comments to them. Now I am struggle with posibility to delete comments by users. I assigned id (primary key) of given comment to button "delete" which is present in all comments fields in purpose to know which comment I want to delete. But now I don't know how to access to this HTML elements in backend and fetch this id's. Part of my html file: {% for comment in comments %} {% if comment.post == object %} <div class="article-metadata"> <small>{{ comment.add_date|date:"M/d/Y" }} <b>{{ comment.author }}</b></small> {% if comment.author == user %} <a href="#" class="btn btn-danger btn-sm mt-1 mb-1" id="{{ comment.id }}">Delete</a> {% endif %} <p>{{ comment.comm_content }}</p> </div> {% endif %} {% endfor %} My class based view in views.py where I want to touch this id: class PostDetailView(DetailView): model = Post def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = Comment.objects.all()[::-1] return context # In this function I want to access my comment id and remove this comment from database def delete_comment(self): post_to_delete = Post.objects.all(id=my_comment_id) del post_to_delete I know this can be solved somehow using jquery but I don't know … -
Razorpay Script throws "Refused to Display" error on Google Chrome Browser
I was trying to integrate razorpay with my django website. It was working fine in previous versions of Google chrome before some time, but now google chrome is giving the following error: Refused to display 'https://api.razorpay.com/v1/checkout/public' in a frame because it set 'X-Frame-Options' to 'sameorigin' I tried to use @xframe_options_exempt in django view, but it did not help. I also tried to load the same script without serving it through the django server, but it resulted in the same error. Is that an issue on razorpay's end? Is anyone else experiencing the same issue? -
Django ORM saving uploaded file without modelform
This is my model: class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, ) certificate = models.FileField(null=True, blank=True, unique=False) I am trying to update the certificate when user upload the file in frontend. doing it like this below: def update(request): if request.user.is_authenticated: if request.method == 'POST': profile = Profile.objects.get(user__id=request.user.id) profile.certificate = request.POST['certificate'] profile.save() return render(request, 'dashboard/update.html') else: return redirect('user.login') I see the field is populated but when I click on the file name on Django template, this is not showing, says page not found but I have another file field in the same model, which is not updated, it is working fine. Can anyone help me to get it done? I am trying to uploaded file saved without modelfrom, not getting how to achieve this. -
Get concrete profile from request.user in Django
I have abstract profile linked to the User: class Account(SharedModel): class Meta: abstract = True user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True) patronic_name = models.CharField(max_length=255, default="") # additional fields and methods def foo(self): print('account') And I have multiple different roles and implementations - student, tutors, admins, etc. I created a class for each of them, derived from the Account class. class Teacher(Account): def foo(self): print('teacher') # ...additional fields and methods class Student(Account): def foo(self): print('student') # ...additional fields and methods Now I want to call foo method on the class object, like this: @login_required def index(request): request.user.account.foo() But since Account class is abstract, there is no request.user.account M2M relationship. I have request.user.student, request.user.teacher relationships, but I do not know the type of relationship. Is there any way to get the concrete account of request.user User object? -
Django/Python - upload custom scripts - how to run them?
I have a Django project which parses XML feeds. The thing is that I often need to write a custom script to parse or download a new feed/s for a new client. I don't think the best way is to modify Django code every time I need a custom parsing/downloading pipeline. My idea is to create a standard. For example, I upload myscript.py through Admin, which must have the class class Downloader() with function download(self) and this function will be called every time that source has to be downloaded. So what is the most common way to do that? The only thing which comes to my mind is to upload myscript.py which has if __name__ == '__main__' function and call it by for example Popen('python filename.py') or from subprocess import call call(["python", "filename.py"]) model: class Source(..): custom_downloader = FileField(... # if needed ... -
AttributeError: '***' object has no attribute '***_set'
Would be so happy if anyone could help me. What I want to do: change all "votes" to zero, after Author has been deleted. class Author(models.Model): """Model representing an author.""" first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField(null=True, blank=True) date_of_death = models.DateField('died', null=True, blank=True) class Meta: ordering = ['last_name', 'first_name'] def get_absolute_url(self): """Returns the url to access a particular author instance.""" return reverse('catalog:author-detail', args=[str(self.id)]) def __str__(self): """String for representing the Model object.""" return '{0}, {1}'.format(self.last_name, self.first_name) class Option(models.Model): def default_votes(): d=Author.objects.all().first() print(dir(d)) for a in d.option_set.all(): a.votes=0 author = models.ForeignKey(Author, on_delete=models.SET_DEFAULT, default=default_votes()) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text But I get: AttributeError: 'Author' object has no attribute 'option_set' But in the shell there is this attribute. And I can change it. What I am doing wrong? -
How to create and save data using ORM within views.py in Django?
I have a template that consists of a button. If a logged-in user clicks on it, it should generate a time and save it within the model and retrieve that time within the template. However, this does not get executed as expected. This is what I had done: models.py: class Mytime(models.Model): pid= models.ForeignKey(User, on_delete = models.CASCADE) time = models.DateTimeField() views.py: def generate_time(request): if request.is_ajax(): if request.method == 'GET': current_time = timezone.now() user_id = User.objects.get(username=request.GET.get('username')).pk if (Mytime.objects.filter(id__exact=user_id, time=current_time) in (None, '')): time = Mytime.objects.create(time=current_time) else: pass data = Mytime.objects.values_list('time', flat=True) return HttpResponse(data) #return time to the template. interface.html: {% block content %} <div class="content-section"> <button type="button" class="btn btn-outline-info" id ='get_time'> Click me </button> <h4 id='insert_time'></h4> //should display the time here from model </div> {% endblock content %} JS AJAX code within the interface template: <script type="text/javascript"> $('#punchin').click(function () { username = localStorage.getItem('username'); console.log(username) $.ajax({ cache: false, url: {% url 'generate_time' %}, type: 'GET', data: {username: username}, success: function(data) { $("#insert_time").html(data.value); } }); }); </script> However, during execution, the time does not get generated. The AJAX call works but the if/else conditional doesn't get executed. How should I do this? Anything wrong within my views.py function? -
Django Filters with Rest Framework Authentication strategy/issue in a Chat application
I have a Django DRF backend, with token user authentication implemented. The application itself is a chat which consists of public Lobbies and private Threads (Threads between particular users). Currently my models file includes Message model which has foreign key relation to the Lobby and Thread models and keeps one of those fields as Null, to determine wheter the particular message concerns private Thread or public Lobby. So far I have been focusing on developing the public Lobbies, where the user was querying the messages based on the Lobby he was currently in. After i finished the development of Lobbies and enabled the authentication, the frontend stopped filtering the messages by the Lobby title and just kept simply returning me all messages relevant to the current authenticated user - obviously disregarding any disctinction between Lobbies the messages are related to. After inspecting the actual API, i found out that when i enable authentication, the Filtering option completely disappears from the page. how can I combat this issue? I would rather keep one Message model rather creating separate Message models for Lobby and Thread. -
I want to develop a smart chatbot in python but really don't from where to start
Chatbot I want to develop is in Python language and can be easily deployed on websites. I tried googling but it created more confusion due to multiple answers. Please help me guys. Online course websites also have different courses :( -
Got KeyError when attempting to get a value for field
views class PhoneCounselingCreate(APIView): def post(self, request, *args, **kwargs): serializer = serializers.PhoneCounselingCreateSerializer( data=request.data) if serializer.is_valid(raise_exception=True): validated_data = serializer.validated_data package = validated_data.pop('package_purchases') ap_data = validated_data.pop('available_periods') file_exist = False if validated_data.get('files'): file_data = validated_data.pop('files') file_exist = True phone_counseling = PhoneCounseling.objects.create(**validated_data) phone_counseling.user = self.request.user phone_counseling.save() for ap in ap_data: phone_counseling.available_periods.get_or_create( day_of_week=ap['day_of_week'], period=ap['period']) req = phone_counseling.counseling_requests.create( expert=validated_data.pop('expert')) phone_counseling.package_purchases.create( phone_call_package=PhoneCallPackage.objects.get(pk=package), ) if file_exist: for f in file_data: phone_counseling.files.create(file=f['file']) return Response({ 'res': serializer.data }) serializers class PhoneCounselingCreateSerializer(serializers.ModelSerializer): available_periods = AvailablePeriodSerializer(many=True) id = serializers.CharField(read_only=True) package_purchases = serializers.CharField() files = FileSerializer(many=True, required=False) class Meta: model = PhoneCounseling fields = [ 'id', 'title', 'user', 'expert', 'native_expert', 'available_periods', 'tag', 'description', 'package_purchases', 'files', ] read_only_fields = ['id'] These codes work correctly and the data is stored correctly. But I get this error: "Got KeyError when attempting to get a value for field available_periods on serializer PhoneCounselingCreateSerializer.\nThe serializer field might be named incorrectly and not match any attribute or key on the OrderedDict instance.\nOriginal exception text was: 'available_periods'." Note: I don't get any errors when writing these codes in the serializer create method -
TemplateSyntaxError in Django View
I use polls app on my project. URLs on Polls App app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.results, name='results'), path('<int:question_id>/results/', views.detail, name='detail'), path('<int:question_id>/vote/', views.vote, name='vote') ] In the detail template file, I create a form and when I click the submit button I want to go to the vote page. so I make the form element like this <form action="{% url polls:vote question.id %}" method="post"> {$ csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}" >{{ choice.choice_text }}</label> {% endfor %} <input type="submit" value="Vote"> </form> But when I build the project, I can see the Error during template rendering error in this form. The error is: Could not parse the remainder: ':vote' from 'polls:vote' Please help me to check this -
Context for product search in django
I want to search for products in my app by their categories, retrieving data from firebase database. The search works but doesn't display the products and I can't figure out what other context is to be passed. I'm new to Django so any help would be appreciated. here's my Welcome.html: <form class="form-inline my-2 my-lg-0" method="get" action="/postsign" id="s"> {% csrf_token %} <input class="form-control mr-sm-2" type="search" value="{{ category }}" placeholder="Search by category" aria-label="Search" name="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit" onclick="location.href='/postsign/?category={{ category }}'" form="s">Search</button> </form> </div> </nav> <div class="container"> <div class="col-md-4"> <div class="cards"> {% for product in data %} <div class="card" style="width: 18rem;"> <img class="card-img-top" src="{{ product.image }}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ product.pname }}</h5> <p class="price">{{ product.price }}</p> <p class="card-text">{{ product.description }}</p> <button class="btn btn-primary cart">Add to cart</button> <button class="btn btn-primary" onclick="location.href='{% url 'productView' %}'">View product</button> </div> </div> {% endfor %} </div> </div> </div> Here's the views: def postsign(request): if request.method == 'GET' and 'csrfmiddlewaretoken' in request.GET: search = request.GET.get('Search') search = search.lower() timestamps = database.child("Products").shallow().get().val() pcategory = [] for i in timestamps: category = database.child("Products").child(i).child("category").get().val() category = str(category)+"$"+str(i) pcategory.append(category) matching =[str(string) for string in pcategory if search in string.lower()] s_category = [] s_id = [] for i in … -
Django Admin error using inline, please correct the errors below
I'm relatively new to Django and I'm currently leveraging the built in admin app. I am receiving the following error whenever I try to add/save an inline child group and whenever I do a simple edit to the parent: please correct the errors below If I don't include the inline...adds, edits and deletes work fine. I'm not too sure how to resolve this. I've tried a few things based on what is available via google search, but still have not come to a resolution. Here is a snippet of my model: class Group(models.Model): # Parent groupid = models.CharField('Group ID',db_column='groupId', primary_key=True, auto_created=True, default=uuid.uuid4, max_length=36) # Field name made lowercase. groupabbr = models.CharField('Group Abbr',db_column='groupAbbr', max_length=30) # Field name made lowercase. groupname = models.CharField('Group Name',db_column='groupName', max_length=100) # Field name made lowercase. groupemail = models.EmailField('Group Email',db_column='groupEmail', max_length=200, blank=True, null=True) # Field name made lowercase. # description = models.TextField(db_column='description', max_length=255, blank=True, null=True) description = models.CharField(db_column='description', max_length=255, blank=True, null=True) fkpripocpersonid = models.ForeignKey(Person,db_column='fkPriPocPersonId', related_name='priPocForGroups', on_delete=models.SET_NULL, max_length=36, blank=True, null=True, verbose_name='Primary POC') # Field name made lowercase. fksecpocpersonid = models.ForeignKey(Person,db_column='fkSecPocPersonId', related_name='secPocForGroups', on_delete=models.SET_NULL, max_length=36, blank=True, null=True, verbose_name='Secondary POC') # Field name made lowercase. primaryfieldtitle = models.CharField('Primary Field Title',db_column='primaryFieldTitle', max_length=100, blank=True, null=True) # Field name made lowercase. primaryfieldcontent = models.TextField('Primary Field … -
djnago channel 2 sessions is not persisting
I am using django 3.0 , channel 2. I am trying to authenticate through websocket if success then it will redirect to dashboard and show my username. if not it will redirect to login page. But After login , when I goto dashboard it redirect me to login page. My HTML code: <!--Login_websocket.htm--> {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script type="text/javascript" src=" {% static 'js/jquery.js' %}"></script> <script type="text/javascript" src="{% static 'js/popper.js' %}"></script> <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}"> <script type="text/javascript" src="{% static 'js/bootstrap.min.js' %} "></script> <title>Login</title> </head> <body> <form class="w-25 m-auto pt-5"> {% csrf_token %} <div class="form-group"> <label for="Username">Username</label> <input class="form-control" type="text" name="username" id="Username" /> </div> <div class="form-group"> <label for="Username">Password</label> <input class="form-control" type="password" name="password" id="Password"/> </div> <hr> <button type="button" class="btn btn-primary" value="Login" disabled id='submit_button'>Login </button> </form> <script> var button = document.getElementById("submit_button"); const socket = new WebSocket("ws://localhost:8000/ws/login/"); socket.addEventListener("close",function(event) { socket.close(); console.log("Webscoket closed"); }); socket.addEventListener("open",function(event) { button.disabled = false; }); socket.addEventListener('message', function (event) { console.log('Message from server ', event.data); data = JSON.parse(event.data); console.log(data) if (data.success == 1) { window.location.replace(data.redirect); //button.disabled = true; } else { alert("Invalid Username or Password"); } }); button.addEventListener('click', function () { username = document.getElementById("Username").value; password … -
Django Bulk_create for inserting Excel into the postgresql database
Im using pandas in django app to read and process 3 excel files with about 1000 rows in each file . Also I have 3 models with 10-15 fields. so i decided to make 3 arrays of objects and use bulk_create to insert them into the database . The problem is it takes too long to process and most times nginx raises 504 timeout error . Is this the correct way to insert excel to database ? isn't it better to broke data in some parts then use bulk_create to insert them ? for example 10 parts with 100 data in each one . Now server cpu is used 80-95 percent while processing and database engine is busy & engaged !!