Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
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) …