Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
validate user shift and then show data in Django
I have developed two API "ShiftstartAPI" and "tickettableAPI" when user start the shift only he can able to view the tables in Django. I have tried below approach but its not working as expected all it hides the table even after shiftstart views.py: shift start API # startshift @api_view(['POST', 'GET']) def UserStartShift(request): if request.method == 'GET': users = tblUserShiftDetails.objects.all() serializer = UserShiftStartSerializers(users, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = UserShiftStartSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) once user click on the shift start the ticket tables needs to populate. Here,I have tried checking the requested user in the "shiftstartAPI" # tickets table @api_view(['GET', 'POST']) def ClaimReferenceView(request, userid): try: userID = Tblclaimreference.objects.filter(userid=userid) except Tblclaimreference.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': if request.user in UserStartShift(): cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetClaims] @UserId= {}'.format(userid,)) result_set = cursor.fetchall() print(type(result_set)) response_data = [] for row in result_set: response_data.append( { "Number": row[0], "Opened": row[1], "Contacttype": row[2], "Category1": row[3], "State": row[4], "Assignmentgroup": row[5], "Country_Location": row[6], "Openedfor": row[7], "Employeenumber": row[8], "Shortdescription": row[9], "AllocatedDate": row[10] } ) return Response(response_data, status=status.HTTP_200_OK) elif request.method == 'POST': serializer = ClaimReferenceSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django - Product Details in XML file
I have a task to export all product details such as name, price etc. from db to XML file. Since now i'm exporting most of the fields and save them to an XML file. However i'm a bit confused on how to export images. I have 2 models one for Product and one for ProductImages, see below: models.py class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=50) slug = models.SlugField(max_length=500, null=True, unique=True) sku = models.CharField(max_length=100, unique=True) image = models.ImageField(upload_to='photos/%Y/%m/%d/') created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) class ProductImage(models.Model): product = models.ForeignKey(Product, related_name='images', on_delete=models.CASCADE) title = models.CharField(max_length=50, blank=True) image = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, null=True) Also according to requirements there are two fields where images should be exported. If there is one image (product table) should be exported to item_image_link which i exporting it with no problem. And if there are more than one (ProductImage table) to item_additional_image_link and here is where i have issue. I iterate over products table like below and then trying to find all images for specific product id like: products = Product.objects.filter(product_status=True) images = ProductImage.objects.filter(product__id__in=products) for products in products: item = ET.SubElement(channel, "item") g_item_id = ET.SubElement(item, ("{http://base.google.com/ns/1.0}id")).text = products.sku g_item_image_link = ET.SubElement(item, ("{http://base.google.com/ns/1.0}image_link")).text = 'http://127.0.0.1:8000'+products.image.url for image in … -
Django admin create new entry in a different table from an existing entry
New to Django, and I am creating an API using the Django rest_framework. Mainly because I need the preconfigured admin panel. My problem is as follows. I have products and some are active on a site. Those products get inserted into a second table when they are rendered to the final user. So as soon as a product is available the admin inserts that new row to products_live table. My questions is as follows. Is it possible using the admin panel to tick a box in the products admin view and trigger the insert of the product from the product table to the products_live table while keeping the instance of the product in the product table? Hope I made my query clear. -
How to use your own domain www.youddomain.com to serve Google Cloud Storage content
I have been using Google Cloud Storage succesfully to serve the videos and images for the webservice. However, the links for the images must include the following prefix : GS_HTTPS_URL = 'https://storage.googleapis.com/' + GS_BUCKET_NAME + "/" How can I serve the content directy from my service name ? ( for instance "www.mydomain.com/content/" rather than "https://storage.googleapis.com/". -
Hello ! how can i do about solving this problem?
?: (mysql.W002) MariaDB Strict Mode is not set for database connection 'default' HINT: MariaDB's Strict Mode fixes many data integrity problems in MariaDB, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/3.2/ref/databases/#mysql-sql-mode -
Upload to S3 closes server with no error ( after changing external IP or hostname in Ubuntu)
I'm facing error while uploading image to S3 bucket. Actually, Earlier it was working fine but I'm facing this issue after one developer (now, I'm not in contact with him) changed the external IP or hostname. Same Code working fine in Localhost and Production server but facing issue in staging server. I not able to found any specific issue. Its crashing on this storage.save(file_path, case_study_img) line. I have mentioned code and screenshot for same thing File01.py from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings class PublicMediaStorage(S3Boto3Storage): file_overwrite = False default_acl = 'public-read' File02.py from File01 import PublicMediaStorage #its dummy according to mention file name here. Import is working fine in code # save thumbnail image print(" LINE 01 WORKS") file_name = "case-study-image-" + str(case_study_id) + case_study_img.name print(" LINE 02 WORKS") file_path = os.path.join(file_directory, file_name) print(" LINE 03 WORKS") storage.save(file_path, case_study_img) print(" LINE 04 WORKS") case_study_img_url = storage.url(file_path) print(" LINE 05 WORKS") CaseStudy.objects.filter(id=case_study_id).update( image=case_study_img_url ) DJANGO TERMINAL Last Few Lines of boto3 logger ( boto3.set_stream_logger('') ): 2021-12-20 11:28:56,830 DEBUG [urllib3.connectionpool:396] connectionpool 15908 140026478388992 https://server-name.s3.ap-south-1.amazonaws.com:443 "PUT /Server-Images-Images/case-study-image-34zomoto%20transparent%2002.png HTTP/1.1" 200 0 2021-12-20 11:28:56,830 urllib3.connectionpool [DEBUG] https://server-name.s3.ap-south-1.amazonaws.com:443 "PUT /Server-Images-Images/case-study-image-34zomoto%20transparent%2002.png HTTP/1.1" 200 0 2021-12-20 11:28:56,831 DEBUG [botocore.parsers:234] parsers 15908 140026478388992 Response headers: {'x-amz-id-2': '0+VU+4OgOlPa8E+nD93kTWkp2wqqn1W0YYim4dy72ZWRQBtCM4fpWr7ywPF+Hb4uPYd/BbMGV3k=', 'x-amz-request-id': … -
Project in Django: I can't create superuser in terminal to manipulate data in Postgresql
I am doing a project with Django in which I try to change the database from SQLITE to Postqresql. When I try to create the super user I get this error. Traceback File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\models.py", line 163, in create_superuser return self._create_user(username, email, password, **extra_fields) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\models.py", line 146, in _create_user user.save(using=self._db) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save super().save(*args, **kwargs) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\base.py", line 774, in save_base post_save.send( File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\dispatch\dispatcher.py", line 180, in send return [ File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\dispatch\dispatcher.py", line 181, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "C:\Users\l\Desktop\django-course\Django(02-09-21)\crm1\accounts\signals.py", line 7, in customer_profile group = Group.objects.get(name='customer') File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\query.py", line 435, in get raise self.model.DoesNotExist( django.contrib.auth.models.DoesNotExist: Group matching query does not exist. Settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'DEMO_TEST', 'USER' : 'postgres', … -
Django Rest Framework, How to update nested values in serializer
In DRF, I would like to post bulk transactions to my rest endpoint. On the following Serializer what would be the correct way to create a nested field of values for transactions in DFR? Do you call create for each transaction on TransactionItemSerializer OR Call save() on the Transaction model inside MasterSerializer create myself> For example: class MasterSerializer(serializers.Serializer): transactions = TransactionItemSerializer(many=True) # A nested list of 'transaction' items. 1 . Update transactions on MasterSerializer. def create(self, validated_data): transactions = validated_data.pop('transactions') # for each transaction do Transaction Save() 2 . Somehow call the create mthoud of the TransactionItemSerializer within MasterSerializer create mthoud for each transaction i.e class TransactionsSerializer(serializers.Serializer): transactions = TransactionItemSerializer(many=True) class Meta: fields = ['transactions'] def create(self, validated_data): transactions = validated_data.pop('transactions') # call create on for each transaction TransactionItemSerializer.create() here -
Cannot resolve keyword 'user' into field. Choices are: create_account, email, full_name
Im Created 2 Models. Account UserProfil First Of All, User Register email, fullname, password1, password2. The data Sending To Database in table Account. Second, User Will Login, if success, he will go to dashboard. in dashboard have a profil Form. In The Profil Form, He Will input data profil, likes number phone, birth date. etc. and will store in table UserProfil All of data in UserProfil relationship with Account. Im Try to create 'Profil Form'. Like This. my Question is How To Put the data Full_Name in this form ? i got Error Cannot resolve keyword 'user' into field. Choices are: create_account, email, full_name ... authentication/models.py class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) full_name = models.CharField(max_length=150) create_account = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_reviewer = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['full_name'] def __str__(self): return self.full_name dashboard/models.py class UserProfil(models.Model): jenis_kelamin_choice = ( ('Pria', 'Pria'), ('Wanita', 'Wanita' ), ) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) nik = models.CharField(max_length=11, null=True, unique=True) nidn = models.CharField(max_length=11, null=True, unique=True) def __str__(self): return str(self.user) dashboard/views.py class UserProfilFormView(CreateView): template_name = 'dashboard/profil.html' form_class = UserProfilForm def form_valid(self, form): userPofil = form.save(commit=False) userPofil.user = Account.objects.get(user__full_name=self.request.user) userPofil.save() messages.success(self.request, 'Data Profil Berhasil Disimpan.') print(self.request.user) … -
addChild() missing 1 required positional argument: 'pk
I have to two models, namely Parent and Child. I have managed to make a model form for registering a Parent. Now I want to be able to add a child to the parent. Expected Outcome: Each parent should have a link that will pull up a child registration form. The Parent Name Field should have initial value of the parent. I'm currently getting this error, addChild() missing 1 required positional argument: 'pk models.py class Parent(models.Model): surname = models.CharField(max_length=150, null=False, blank=False) first_name = models.CharField(max_length=150, null=False, blank=False) class Child(models.Model): parent = models.ForeignKey(Parent, null=True, blank=True, on_delete=SET_NULL) first_name = models.CharField(max_length=50, null=False, blank=False) last_name = models.CharField(max_length=50, null=False, blank=False) views.py (What am I missing on my addChild view?) def addParent(request): form = ParentForm() if request.method == 'POST': form = ParentForm(request.POST, request.FILES) if form.is_valid(): form.save() def addChild(request, pk): parent = Parent.objects.get(id=pk) form = ChildForm(initial={'parent' :parent}) if request.method == 'POST': form = ChildForm(request.POST) if form.is_valid(): form.save() -
How to store data on database after user login using social API, like facebook
I'm working on a react-native app using django as backend. The backend has a User table that extends AbstractBaseUser, and I want to store the data of social logged users inside this table. Now let's say I'm using facebook and google as social-auth API, when I get the data on the fronted, profile_id and email (for instance in the facebook case), what field do I have to use as password? I mean you'll say it's not necessary because the authentication occurs through the facebook server, but the "social_login/" endpoint is accessible without any permissions so anyone can make a request using facebook user email and its profile_id, as I saw it's possible to get it thought html inspector. So what do I have to use as unique and secure identifier when the user login-in using social API for the second time? Do I have to create a token/hash based on profile_id and email? Please don't suggest me django-social-auth or something similar, they don't fit my needs because of the high levels of customization I need. Thank you -
How can i open file with ogr from bytes or url
I'm trying to open .gml file with ogt.Open(path, False) but on production project hosted on Heroku i can read/write from filesystem. gml_parser.py: from osgeo import ogr reader = ogr.Open(file, False) Could i will open it from bytes or url ? Thanks in advance. -
Broken pipe while parsing CSV file multiple times using pandas
I have a search bar which takes city name as input. A GET API is build on django, which takes the user input and search for the input in the CSV file. For example: If user types "mum". The API takes this "mum" as input and searches for all city names starting with "mum" in the available CSV file. The search is performed everytime user enters a character. But after some time I get an error, as the API is called on every character input by the user: Broken pipe from ('127.0.0.1', 63842) I am using pandas for performing city search ### check for cities list from csv file def checkForCities(request): cities_list = [] cnt = 0 for index, row in city_dataFrame.iterrows(): if cnt >= 6: break if row["cityName"].startswith(request): print(row["cityName"]) cities_list.append({"city_name":row["cityName"], "city_code":row["id"]}) cnt += 1 return cities_list -
Django Rest Framework, nested serializers, inner serializer not visible in outer serializer
I am trying to use nested serializers in my app. I followed documentation seen on DRF website but it seems there is a problem with inner serializer visibility. The error message: Exception Type: AttributeError Exception Value: Got AttributeError when attempting to get a value for field `produkty` on serializer `ZamowieniaSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Zamowienie` instance. Original exception text was: 'Zamowienie' object has no attribute 'produkty'. models.py class Zamowienie(models.Model): kontrahent = models.ForeignKey(Kontrahent, on_delete=models.PROTECT) my_id = models.CharField(max_length=60, unique=True) data_zal = models.DateTimeField() data_realizacji = models.DateField() timestamp = models.DateTimeField(auto_now=True) status = models.CharField(max_length=50, choices=STATUS_CHOICES, default="0") komentarz = models.CharField(max_length=100, unique=False, default="") uwagi = models.CharField(max_length=150, unique=False, default="") zam_knt_id = models.CharField(max_length=50, unique=False) class Meta: ordering = ['-data_zal'] verbose_name_plural = 'Zamowienia' objects = models.Manager() def __str__(self): return str(self.my_id) def save(self, *args, **kwargs): licznik = Zamowienie.objects.filter(Q(kontrahent=self.kontrahent) & Q(timestamp__year=timezone.now().year)).count() + 1 self.my_id = str(licznik) + "/" + self.kontrahent.nazwa + "/" + str(timezone.now().year) self.zam_knt_id = self.kontrahent.zam_knt_id super(Zamowienie, self).save(*args, **kwargs) class Produkt(models.Model): zamowienie = models.ForeignKey(Zamowienie, on_delete=models.CASCADE) ean = models.CharField(max_length=13, unique=False, blank=True) model = models.CharField(max_length=50, unique=False) kolor_frontu = models.CharField(max_length=50, unique=False, blank=True) kolor_korpusu = models.CharField(max_length=50, unique=False, blank=True) kolor_blatu = models.CharField(max_length=50, unique=False, blank=True) symbol = models.CharField(max_length=50, unique=False) zam_twrid = models.CharField(max_length=10, unique=False, blank=True) ilosc … -
how can call function inside class view in django
i have function that return some information about user device and i have one class for show my html and form_class how can i use function in class this is my views.py : from django.http import request from django.shortcuts import render, redirect from .forms import CustomUserCreationForm from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy from django.views import generic def a(request): device= request.META['HTTP_USER_AGENT'] return device class RegisterView(generic.CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy("register") template_name = "man/man.html" this is my urls.py : from django.urls import path from . import views urlpatterns = [ path('',views.RegisterView.as_view(), name="register"), ] -
Django: How to extract text from doc and docx files and then pass it to template to display it in a separate div that can be later on styled?
I am working on a Final Project for CS50W and I want a small app that allows users to upload their 'scripts' - files that are either .doc or .docx. These files are then saved in a separate folder and its url is saved in a models field. I want to create a separate view for displaying the contents of these files, that I can then later on style separately (changing background and text colors, size, etc.), so I want to extract the text from these files and pass it on to my template. But when I do that with open file function, I get FileNotFoundError - which I presume is because this file is not .txt file. What would be the best way to achieve this? Here's the relevant part of my code: class Script(models.Model): ... upload = models.FileField("Select your script", upload_to="scripts/%Y/%m/%D/", validators=[FileExtensionValidator(allowed_extensions=['doc', 'docx'])]) ... def read(request, script_id): script = Script.objects.get(pk=script_id) file = open(script.upload.url, 'r') content = file.read() file.close() return render(request, 'astator/read.html', { 'script':script, 'content':content, }) Maybe there's also a better way to achieve this with JS? Anyhow, thanks in advance for your help! -
Django Test key association
I am new to Django and Unit Testing. I'm writing tests for my app which is a learning platform consisting of several labs that include a lesson and questions (of 3 different types), the relationship between questions and labs is done via foreign key. I am trying to write tests in which I add a lab to the database and a multiple choice question. The problem is that the tests always end with the same error: DETAIL: Key (lab_id)=(1) is not present in table "labs_lab". I understand the meaning of the sentence, but how come this happens if I provide an id to the questions to link them to the respective test-lab? Thank you Models.py class Lab(models.Model): lab_name = models.CharField(max_length=200) category = models.ForeignKey(Category, unique=True, null=True, on_delete=models.PROTECT) pub_date = models.DateTimeField('date published') lab_theory = models.TextField() def __str__(self): return self.lab_name class QuestionMultipleChoice(models.Model): lab = models.ForeignKey(Lab, on_delete=models.CASCADE) type = QuestionType.multiplechoice question = models.CharField(max_length=200,null=True) option1 = models.CharField(max_length=200,null=True) option2 = models.CharField(max_length=200,null=True) option3 = models.CharField(max_length=200,null=True) option4 = models.CharField(max_length=200,null=True) answer = models.IntegerField(max_length=200,null=True) def __str__(self): return self.question @property def html_name(self): return "q_mc_{}".format(self.pk) @property def correct_answer(self): correct_answer_number = int(self.answer) correct_answer = getattr(self, "option{}".format(correct_answer_number)) return correct_answer def check_answer(self, given): return self.correct_answer == given test.py class TestData(TestCase): @classmethod def setUpTestData(cls): past_date = … -
How to return multiple value from a pytest fixture with scope = session
I have created pytest fixture in conftest.py for creating user and auto login @pytest.fixture(scope="session") def api_client(): from rest_framework.test import APIClient return APIClient() @pytest.fixture(scope="session") @pytest.mark.django_db def create_user(): def make_user(**kwargs): # employee = e_ge_employee.objects.create() kwargs['password'] = 'strong-test-pass' if 'username' not in kwargs: kwargs['username'] = 'test-user' # if 'employee' not in kwargs: # kwargs['employee'] = employee return e_ge_user.objects.create_user(**kwargs) return make_user @pytest.fixture(scope="session") @pytest.mark.django_db def auto_login_user(api_client, create_user): def make_auto_login(): print("_+==--=-=-=-===--=-=-==----=-=-=-=") user = create_user() api_client.login(username=user.username, password='strong-test-pass') return api_client, user return make_auto_login Now how to call the get, post method using API client and how to access user in multiple test cases written in test_views.p @pytest.mark.django_db class TestViews: def test_generate_token_views_post(self,auto_login_user): **"To be Answered"** assert True == True def test_generate_token_views_post2(self,auto_login_user): **"To be Answered"** assert True == True -
How to list all objects from particular model in django rest framework?
I have two models: class Product(models.Model): name = models.CharField(max_length=200) price = models.DecimalField(default=0, decimal_places=2, max_digits=10) def __str__(self): return self.name class Receipt(models.Model): purchase_date = models.DateTimeField(auto_now=True, null=False) shop = models.ForeignKey(Shop, on_delete=models.SET_NULL, null=True) products = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) def __str__(self): return super().__str__() My receipt url looks like this: And i would like it to show list of all products, instead of a number of them. How to do this? My viewsets: class ReceiptViewSet(viewsets.ModelViewSet): queryset = Receipt.objects.all() serializer_class = ReceiptSerializer permission_classes = [AllowAny] class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = [AllowAny] enter code here -
Error connecting installing mysqlclient to my django project
please help, when i try to run pipenv install mysqlclient it gives me an error indicating that visual c++ 14 or greater is needed and now i have gotten 14.29 but still not working.I also tried usimg Unofficial Windows Binaries for Python Extension Packages and this showed that mysqlclient installed successfully but when i tried to run mysqlclient it gave an error saying do you have mysqlclient installed? please help. -
How do I solve this ModuleNotFoundError: No module named 'django_mfa' error?
*I want to implement MFA in my python project but I get this error message: Error running WSGI application 2021-12-19 19:49:30,255: ModuleNotFoundError: No module named 'django_mfa' 2021-12-19 19:49:30,255: File "/var/www/XXX_pythonanywhere_com_wsgi.py", line 18, in <module> 2021-12-19 19:49:30,256: application = get_wsgi_application() 2021-12-19 19:49:30,256: 2021-12-19 19:49:30,256: File "/home/XXX/.virtualenvs/groupx-virtualenv/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2021-12-19 19:49:30,256: django.setup(set_prefix=False) 2021-12-19 19:49:30,256: 2021-12-19 19:49:30,256: File "/home/XXX/.virtualenvs/groupx-virtualenv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup 2021-12-19 19:49:30,256: apps.populate(settings.INSTALLED_APPS) 2021-12-19 19:49:30,257: 2021-12-19 19:49:30,257: File "/home/XXX/.virtualenvs/groupx-virtualenv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate 2021-12-19 19:49:30,257: app_config = AppConfig.create(entry) 2021-12-19 19:49:30,257: 2021-12-19 19:49:30,257: File "/home/XXX/.virtualenvs/groupx-virtualenv/lib/python3.8/site-packages/django/apps/config.py", line 223, in create 2021-12-19 19:49:30,257: import_module(entry) django_project- - my_site/urls.py - django-mfa/django_mfa/urls.py` 1: django_project/my_site/urls.py from django.urls import path,include from django.urls import url from django.conf import settings urlpatterns = [ ..... url(r'^settings/', include('django_mfa.urls', namespace="mfa")), .....` ] 2. django_project/django-mfa/django_mfa/urls.py` from .views import * from django.urls import path, include from django.conf.urls import url from . import views security_patterns = ([ path('verify-second-factor-options/', verify_second_factor, name='verify_second_factor'), path('verify/token/u2f/', views.verify_second_factor_u2f, name='verify_second_factor_u2f'), path('verify/token/totp/', verify_second_factor_totp, name='verify_second_factor_totp'), path('keys/', views.keys, name='u2f_keys'), path('add-key/', views.add_key, name='add_u2f_key'), path('security/', security_settings, name='security_settings'), path('mfa/configure/', configure_mfa, name='configure_mfa'), path('mfa/enable/', enable_mfa, name='enable_mfa'), path('mfa/disable/', disable_mfa, name='disable_mfa'), path('recovery/codes/', recovery_codes, name='recovery_codes'), path('recovery/codes/downloads/', recovery_codes_download, name='recovery_codes_download'), ], 'mfa') urlpatterns = [ path("", include(security_patterns)), ] NB: I installed the MFA in the virual environment: groupx-virtualenv in Python Anywere PAAS* -
Run functions on loading page but it doesn't work
`let db = new sqlite3.Database('mcm'); db.exec('CREATE TABLE IF NOT EXISTS workers(id INTEGER PRIMARY KEY,names VARCHAR(30) NOT NULL,position VARCHAR(30) NOT NULL,date VARCHAR(10) NOT NULL,salary INTEGER)'); function insertValues() { const name = document.getElementById('addName'); const Nposition = document.getElementById('addPosition'); const startDate = document.getElementById('addStartDate'); const Nsalary = document.getElementById('addSalary'); db.exec('CREATE TABLE IF NOT EXISTS workers(id INTEGER PRIMARY KEY,names VARCHAR(30) NOT NULL,position VARCHAR(30) NOT NULL,date VARCHAR(10) NOT NULL,salary INTEGER)'); db.exec('INSERT INTO workers (id,names,position,date,salary) VALUES (NULL,?,?,?,?)', [name,Nposition,startDate,Nsalary]); } function myFunction2(num) { var fName = db.exec("SELECT names FROM workers WHERE id = num"); var fPosition = db.exec("SELECT position FROM workers WHERE id = num"); var fStartDate = db.exec("SELECT date FROM workers WHERE id = num"); var fSalary = db.exec("SELECT salary FROM workers WHERE id = num"); var inputF1 = document.getElementById("addName"); var inputF2 = document.getElementById("addPosition"); var inputF3 = document.getElementById("addStartDate"); var inputF4 = document.getElementById("addSalary"); function gfg_Run(Gname,Gposition,Gdate,Gsalary) { inputF1.value = Gname; inputF2.value = Gposition; inputF3.value = Gdate; inputF4.value = Gsalary; window.onload = function() { var button = document.getElementById('addRowButton'); button.form.submit(); } } function called() { alert('ok'); var number = db.exec("SELECT COUNT(DISTINCT c) FROM workers"); for (i = 0; number; i++){ myFunction2(i+1); } } db.close(); window.onload = called;` -
AttributeError: 'WSGIRequest' object has no attribute 'is_ajax'
im trying to learn ajax in django but when i running this simple test i got this error and i cant find the reason, my django version is 4.0 AttributeError: 'WSGIRequest' object has no attribute 'is_ajax' view.py from django.shortcuts import render, HttpResponse def home(request): return render(request,'myapp/index.html') def ajax_test(request): if request.is_ajax(): message = "This is ajax" else: message = "Not ajax" return HttpResponse(message) urls.py urlpatterns = [ path('',views.home,name='home'), path('ajax_test/', views.ajax_test, name='ajax_test') ] index.html <button id="btn">click me!</button> <script> $("#btn").click(function () { $.ajax({ type: "GET", url: "{% url 'ajax_test' %}", success: function () { console.log("done"); }, error: function () { console.log("error"); }, }); }); </script> -
when i set worker time out in gunicorn for Django Application, other users are not able to access the application
I have a django application running on Gunicorn and Nginx. There is one request in application which takes 10 min to load the page [There is lot of data to process], i have increased the worker time to 1200 sec for Gunicorn to make it take sufficient time to load the page. it works fine but until that request is getting processed other users are not able to access the application gives : 504 Gateway Time-out nginx/1.21.4 This is my DOCKER version: '3.8' services: web: volumes: - static:/static command: python manage.py makemigrations / && python manage.py migrate && python manage.py collectstatic --noinput/ && python manage.py crontab add / && exec gunicorn DrDNAC.wsgi:application --bind 0.0.0.0:8000 --timeout 1200" build: context: . ports: - "8000:8000" depends_on: - db db: image: postgres:13.0-alpine nginx: build: ./nginx volumes: - static:/static ports: - "80:80" depends_on: - web volumes: postgres_data: static: This is nginx: upstream app { server web:8000; } server { listen 80; location / { proxy_pass https://app; proxy_connect_timeout 75s; proxy_read_timeout 300s; } location /static/ { alias /static/; } } -
How to solve list complex issue in python?
Have the function testfunction(num) take the num parameter being passed and perform the following steps. First take all the single digits of the input number (which will always be a positive integer greater than 1) and add each of them into a list. Then take the input number and multiply it by any one of its own integers, then take this new number and append each of the digits onto the original list. Continue this process until an adjacent pair of the same number appears in the list. Your program should return the least number of multiplications it took to find an adjacent pair of duplicate numbers. For example: if num is 134 then first append each of the integers into a list: [1, 3, 4]. Now if we take 134 and multiply it by 3 (which is one of its own integers), we get 402. Now if we append each of these new integers to the list, we get: [1, 3, 4, 4, 0, 2]. We found an adjacent pair of duplicate numbers, namely 4 and 4. So for this input your program should return 1 because it only took 1 multiplication to find this pair. Another example: if …