Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
im getting different response in postman and in browser [closed]
im new to django, i tried CRUD operation in django rest-framework while testind in postman im getting 404 not found response. At the same url im getting json response when tried in browser Can anyone help me to get fix with this?[THis is my browser response][1] -
How to develop rest POST API in Django for inserting data into two models at a time when 2nd model is ForeignKey related to first model?
User Model from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import UserManager, Permission, PermissionsMixin from django.db import models from django.utils import timezone #from mptt.models import MPTTModel from apps.base.models import DomainEntityIndexed from apps.base.config import ROLE_CHOICES, ROLE_DICT, VEHICLE_CHOICES, VEHICLE_DICT, SIGNUP_CHOICES, SIGNUP_DICT class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(unique=True) phone = models.CharField(max_length=16) address = models.CharField(max_length=200, null=True, blank=True) date_joined = models.DateTimeField(default=timezone.now) profile_photo = models.ImageField(upload_to=profileImage, null=True, blank=True) date_of_birth = models.DateTimeField(null=True, blank=True) role = models.PositiveSmallIntegerField(default=ROLE_DICT['Traveller'], choices=ROLE_CHOICES) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) email_verified = models.BooleanField(default=False) email_bounced = models.BooleanField(default=False) phone_verified = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = SimpleUserManager() Driver Model class Driver(DomainEntityIndexed): user = models.OneToOneField(User, on_delete=models.CASCADE) nid = models.ImageField(upload_to=nidImage, null=True, blank=True) driving_license_number = models.CharField(max_length=50) driving_license = models.ImageField(upload_to=licenseImage) Serializer from rest_framework import serializers from rest_framework.serializers import ModelSerializer from .models import * from rest_framework_jwt.serializers import jwt_encode_handler, jwt_payload_handler class UserSerializer(ModelSerializer): class Meta: model = User fields = ['id', 'first_name', 'last_name', 'email', 'password', 'phone', 'profile_photo', 'address', 'date_of_birth'] #fields = '__all__' extra_kwargs = { 'password': {'write_only': True, 'required': False} } def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class DriverSerializer(ModelSerializer): class Meta: model = Driver fields = '__all__' api.py from .serializers import … -
Cannot import ThreadSensitiveContext from asgiref.sync, Upgrading django to 4.0
I am currently upgrading a django site from 3.0 to 4.0. I am looking at the error messages and try to fix them. One of the errors I got now was that I cannot import ThreadSensitiveContext from asgiref.sync. This was not an issue in Django 3 and I have not updated the asgiref library. Also since I took over this project, I am not sure what it is used for. Have anyone experienced the same problem? -
how can I extend 'base.html' in Django Python code?
I want to dynamically generate a page using the base template It doesn't work as it should - def index(request): return HttpResponse("{% extends 'base.html' %} {% block content %} Hello {% endblock %}") on html its - {% extends 'base.html' %} {% block content %} Hello {% endblock %} how can I extend 'base.html' in Django Python code ? does it only work in html? -
How do I integrate Elasticsearch DSL Django to make queries from the front end
I'm trying to implement search functionalities in my django project, this is how I am storing data in Elasticsearch, after scraping, it's storing stuff instantaneously to indices. Defined the necessaries in settings.py . es_client = Elasticsearch(['http://127.0.0.1:9200']) doc = { "date": time.strftime("%Y-%m-%d"), "current_url": input_url, "depth": depth, "content": text } res = es_client.index(index=str(cluster_id), doc_type="_doc", body=doc) print(res["result"]) This is my models.py from django.conf.urls import url from django.db import models from django.contrib.auth.models import User from django.template.defaultfilters import slugify from spider.spider.spiders.crawler import begin_crawl ''' Cluster One user can have multiple clusters So an one-to-many relationship has been created ''' class Cluster(models.Model): # Once the user deletes his account, clusters related to his account will be deleted user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='clusters') title = models.CharField(max_length=100) description = models.TextField(null=True, blank=True, default='Creating a Search Cluster for advanced search') date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) slug = models.SlugField(null=True, blank=True) class Meta: # Default ordering is set to date_created ordering = ['date_created'] def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Cluster, self).save(*args, **kwargs) ''' Each Cluster can have multiple urls So an one-to-many-relationship has been created ''' output_preference = ( ('text', 'Textual Data'), ('pdf', 'PDF') ) class Url(models.Model): # Once a Cluster is deleted, all … -
how do I consume django api from react frontend
I'm new to React, I've written a Django API endpoint to perform some kind of sync. I want this API to be called from a React page, on clicking a TextLink - say Sync Now, how I should go about doing it? Based on the response from the API(200 or 400/500), I want to display Sync failed, on successful sync, I want to show Sync Now again, but with another text Last Sync Time: DateTime(for this I've added a key in my Django model), how can I use this as well. Also, I've a followup, say instead of Sync Now and Synced we have another state Syncing, which is there until a success or failure is returned, Is polling from the server is a good option, or is there any other way. I know of websockets but not sure which can be used efficiently. I've been stuck here from 3 days with no real progress. Anything will help. Thanks in advance. -
Design issue in Django
I'm struggling with my HTML design, I have tried but I coudn't find a solution. My HTML Design When I converted into Django, my design looks like below. I have used some JINJA tags which i mentioned below. {% load static %} <link rel="icon" href="{% static 'portalABC/assets/images/ABCD 32x32.png' %}" type="image/png" /> Setings.py import os BASE_DIR2 = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_DIR = os.path.join(BASE_DIR2,'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ STATIC_DIR, ] -
i am facing problem while connecting to azure sql using django, please help me
D:\CDP\Anomaly_Detection_Service\config\server_config.ini System check identified no issues (0 silenced). December 20, 2021 - 07:31:27 Django version 2.1.15, using settings 'core.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. title_name :>> asg file_name :>> 536484573901199.csv file_content :>> b't,a,b,c\n1,Wed Oct 13 15:43:22 GMT 2021,abc,india\n2,Wed Oct 13 15:43:22 GMT 2021,xyz,\n3,Wed Oct 13 15:43:22 GMT 2021,pqr,india\ n4,Wed Oct 13 15:43:22 GMT 2021,efg,japan\n' [20/Dec/2021 07:31:46] "POST / HTTP/1.1" 200 8440 Internal Server Error: /save_filedetails Traceback (most recent call last): File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\engine\base.py", line 3240, in _wrap_pool_connect return fn() File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\pool\base.py", line 310, in connect return _ConnectionFairy._checkout(self) File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\pool\base.py", line 868, in _checkout fairy = _ConnectionRecord.checkout(pool) File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\pool\base.py", line 476, in checkout rec = pool._do_get() File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\pool\impl.py", line 146, in _do_get self._dec_overflow() File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__ compat.raise_( File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_ raise exception File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\pool\impl.py", line 143, in _do_get return self._create_connection() File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\pool\base.py", line 256, in _create_connection return _ConnectionRecord(self) File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\pool\base.py", line 371, in __init__ self.__connect() File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\pool\base.py", line 666, in __connect pool.logger.debug("Error on connect(): %s", e) File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__ compat.raise_( File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_ raise exception File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\pool\base.py", line 661, in __connect self.dbapi_connection = connection = pool._invoke_creator(self) File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\engine\create.py", line 590, in connect return dialect.connect(*cargs, **cparams) … -
How to add Background image in django admin login page
I would like to add django background image in my django admin login page here is my code it is not showing any error but still image is not loading. base_site.html {% extends "admin/base.html" %} {% block title %}{% if subtitle %}{{ subtitle }} | {% endif %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1> {% endblock %} {% block nav-global %}{% endblock %} {% load static %} {% block extrastyle %} {{ block.super }} <link rel="stylesheet" type="text/css" href="{% static 'admin_extra.css' %}" /> {%endblock%} admin_extras.css body { /* The image used */ background-image: url('static\admin\containers.jpg') !important; /* Full height */ height: 100%; /* Center and scale the image nicely */ background-position: center; background-repeat: no-repeat; background-size: cover; } settings.py STATICFILES_DIRS = ( os.path.join(BASE_DIR, "ProjectName", "static"), ) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') my code is running and no error popping up in console but still background image is unable to load -
how to escape ^ in django
Below are my codes. url.py app_name = 'home' urlpatterns = [ ... path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.Certification.as_view(), name='activate'), ] acc_active_emal.html {% autoescape off %} Hi {{ user.username }}, Please click on the link to confirm your registration, {{ domain }}{% url 'home:activate' uidb64=uid token=token %} {% endautoescape %} views.py def post(self, request, pk = None): ... message = render_to_string('registration/acc_active_email.html', { 'user': user, 'domain': 'mydomain', # current_domain 'uid': urlsafe_base64_encode((user.pk).to_bytes(5, 'little')), 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Please confirm your email address to complete the registration') When user sign up my site, I send active_email to confirm registration. But email send url like below. mydomain/%5Eactivate/(%3FPFwAAAAA%5B0-9A-Za-z_%5C-%5D+)/(%3FPaxyoyt-906068a2d7255bc3da520c10c5793d22%5B0-9A-Za-z%5D%7B1,13%7D-%5B0-9A-Za-z%5D%7B1,20%7D)/$ Then my site returns the current path, ^activate/(?PFwAAAAA[0-9A-Za-z_-]+)/(?Paxyoyt-906068a2d7255bc3da520c10c5793d22[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$, didn’t match any of these. How I escape %5E using {% url %} ?? -
Django query to get List of Sums of the Count of different Choices
I am trying to get a list of the sum of the count of different choices. The choices are strings, so I want to count the same strings and get their sum, and then do the same for other choices. I made a query but it does not give me the total count of each choice instead list them all with the count 1. model.py class sublist(models.Model): Music = 'Music' Video = 'Video' Gaming = 'Gaming' News = 'News' Lifestyle = 'Lifestyle' Access = 'Access' SUBTYPE_CHOICES =( (Music , "Music"), (Video , "Video"), (Gaming , "Gaming"), (News , "News"), (Lifestyle , "Lifestyle"), (Access , "Online Access"), ) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) name = models.CharField(max_length=150) cost = models.FloatField(default = 0) subtype = models.CharField(max_length= 50, choices = SUBTYPE_CHOICES, default = Access) This is my query. (i tried coming up with other combinations by looking at the documentation but no luck) expenselist = sublist.objects.filter(author = curruser.id) subtypecount = list((expenselist .annotate(subcount=Count('subtype')) .values('subtype', 'subcount') )) result of query above: [{'subtype': 'Access', 'subcount': 1}, {'subtype': 'Access', 'subcount': 1},{'subtype': 'Video', 'subcount': 1}] Desired result: [{'subtype': 'Access', 'subcount': 2},{'subtype': 'Video', 'subcount': 1}] -
in the command "pip install -r requirements.txt" what does '-r' meant? same as in "python3 -m pip install something" what does '-m' meant?
I searched before asking this question but i did get exact answer. can anyone let me know where to read about these operators and others like same as this? Thanks in advance. -
How to protect your API from abuse - DRF & React
I'm really struggling to wrap my head around the concept of protecting ones API end point. How do you do you protect it from abuse if it's exposed with React? I understand if a user were to login then be issued them with a token etc. I get that. But let's say have a front end that does not require someone to be logged in? They simply filling out a form with their details and it gets passed via you API then gets stored in the DB. Whats stopping someone just abusing your API? They could just write a script and attack you end point with spammy data? I just can't understand how this is protected? -
Django To use two FilterView classes in one template
I am creating a search form using FilterView in the main window. Double-click the input form in the search form in the main window to display the modal. I want to display another FilterView class in modal. The class of these two FilterViews is different in the model, filter, and form that they refer to. How can this be achieved? Views.py class Filter1(FilterView): model = Model1 filterset_class = Filter1 template_name = 'filter.html' class Filter2(FilterView): model = Model2 filterset_class = Filter2 template_name = 'filter.html' HTML(templates) <form action="" method="get"> <div class="row"> {{filter.form|crispy}} <-I want to use class filter 1 </div> <div id="myModal" class="modal fade" tabindex="-1" role="dialog"> ・・・ {{filter.form|crispy}} <- I want to use class filter 2 </div> -
Django - Return a list of months that a query of Post objects spans to front-end in local time
So I have kind of a weird and interesting problem. Lets say I want to be able to group posts on an application like Facebook by months in local time to whoever sent the request. Let's say I have a Post table in Django with the standard created, body and author fields. Where created is the date and time it is created. Let's say I want to find all posts by a user so that query would look like Post.objects.filter(author=<some name>). I want to be able to send back to the requester for these posts the dates they span. The reason this is slightly tricky is because Django stores in UTC and has no notion of user's time zone unless given. My initial idea would be make a url that's something like /post/<str:author>/<str:timezone> then somehow convert created date for all queried Post to that time zone and figure out the months. The timezone is needed to cover the edge case that someone posts on the last day of the month. Depending on the time zone that could be the current month in UTC or the next. How would I find all the months in the requestors timezone that Post span … -
User matching query does not exist. I want to add data if user is first time coming?
Actually I m working on Blood Donation system. I m checking that if user is already exist then I checking that He or She completed 90 days Or not if He or She completed then His or Her request will be accepted. if didn't complete then I will show message U have to Complete 90 days. I add data through data admin side and checked on the base of the CNIC that he or she completed 90 days completed or not and its Working But Now the main problem is that If add New Data from Front End he said User matching query does not exist. Now I have to Add else part But I don't know How? please tell me about that I m stuck from past 4 days. #forms.py from django.core.exceptions import ValidationError from django.forms import ModelForm from django.shortcuts import redirect from .models import User from datetime import datetime,timedelta class UserForm(ModelForm): class Meta: model = User fields = "__all__" def clean_cnic(self): cnic = self.cleaned_data['cnic'] print("This is a cnic",cnic) existuser = User.objects.get(cnic = cnic) if existuser: previous_date = existuser.last_donation current_date = datetime.now().astimezone() print(previous_date,"-----_---",current_date) final = current_date - previous_date print("The final is -> ",final) if final < timedelta(days= 90): raise … -
None data value in nested serializer instance
During the update method I'm getting none as an output of child models. My serializers are as follow - class AddressSerializer(serializers.ModelSerializer): stateName = serializers.SerializerMethodField() class Meta: model = publicAddress fields = "__all__" def get_stateName(self, instance): return instance.state.state_name class customerSerializer(serializers.ModelSerializer): custgroupName = serializers.SerializerMethodField() publicAdd = AddressSerializer(many=True) class Meta: model = customerMaster fields = ['id', 'mobileNumber', 'custGroup', 'custgroupName ','publicAdd'] def get_custgroupName(self, instance): return instance.custGroup.name and the update method od customerSerializer - def update(self, instance, validated_data): pubAdd_data = validated_data.pop('publicAdd') data = instance.publicAdd print(data) return instance Here I'm getting the data in the print statement as None. And I'm sure there are multiple addressess linked to the customer as in get request of customer publicAdd is a list of values. Trying to figure out what have I missed ? -
How To Get Data User Login And Post It In Form Django
Im Confused, To Get Data User Login and post it in forms. My question is how to do that ? 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) dashboard/forms.py class UserProfilForm(ModelForm): class Meta: model = UserProfil fields = '__all__' widgets = { 'user' : forms.TextInput({'class' : 'form-control form-control-user', 'id' : 'namaLengkap', 'placeholder' : 'Nama Lengkap'}), 'nidn' : forms.TextInput({'class' : 'form-control form-control-user', 'id' : 'nidn', 'placeholder' : 'Nomor Induk Dosen Nasional'}), 'nik' : forms.TextInput({'class' : 'form-control form-control-user', 'id' : 'nik', 'placeholder' : 'Nomor Induk Karyawan'}), } dashboard/views.py class UserProfilTemplateView(FormView): template_name = 'dashboard/profil.html' form_class = UserProfilForm def get(self, request, *args, **kwargs): user = self.request.user return self.render_to_response(self.get_context_data()) def form_valid(self, form): messages.success(self.request, 'Data Profil Berhasil Disimpan.') print(form.cleaned_data) return super().form_valid(form) I Want The Name User Is Appear in the Form "Nama Lengkap", How should i do ? -
Can we add any python package to Django?
Below code working fine for Wikipedia site but not with particular WordPress website, I want to get backlinks for this site, or is there any python package for backlink checker or scraper. thanks in advance import requests def get_url_data(link): f = requests.get(link) return f.text, f.status_code if __name__ == "__main__": url = "https://yoblogger.com/" data = get_url_data(url) print("URL data", data[0]) print("URL status code", data[1])