Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why my data isnt updating itself ?- django
class Weight(models.Model): weight = models.DecimalField(max_digits=100,decimal_places=1) def __str__(self): return str(self.weight) items = [ str(Weight.objects.all()[0]), str(Weight.objects.all()[1]), str(Weight.objects.all()[2]), str(Weight.objects.all()[3]), str(Weight.objects.all()[4]), ] and i have formula like this self.index = round((float(frac) * (float(self.digital.coff.__str__())*float(items[0])) * ((float(self.complexity.__str__())*float(items[1])) + (float(self.implem.imp.__str__())*float(items[2])))*((float(1*float(items[3])))+(float(self.conn.conn.__str__())*float(items[4]))))) but when i update the data of any weight object result from self.index formula stays the same how can i solve this problem -
how to make serializer for two models that dont have relation with each other
i am working on ecommerce shop and in my home page i want to return all the products and 7 images for the icons for the categories , my models.py is class Product(models.Model): pub_date = models.DateTimeField(default=datetime.now) price = models.DecimalField(max_digits=100,decimal_places=2,null=False,blank=False) category = models.CharField(max_length=20 ,blank=False, null=False ,default='none', choices=cat) product_name = models.CharField(max_length = 50, null=True) photo = models.ImageField(upload_to = 'product_photos/%y/%m/%d',null=True) class Category(models.Model): icon = models.ImageField(upload_to = 'icon',null=True) and my serializers.py is class ProductSerializer (serializers.ModelSerializer): class Meta : model = Product fields = '__all__' class CategorySerializer (serializers.ModelSerializer): class Meta : model = Category fields = '__all__' and my views.py @api_view(['GET']) @permission_classes ([AllowAny] , ) def home (request): p = Product.objects.filter(is_discount= 1).order_by('-pub_date') serializer = ProductSerializer(p,many=True) return Response (serializer.data) how to return both the category and product in the same view , NOTE : my views.py is function based view -
How to specify properties of certain objects via typing?
I have a certain database model in my Django app that has a nullable FK field that is strictly related to its other field, like so: class ModelType(models.TextChoices): non_empty = "non-empty" empty = "empty" class SomeModel(models.Model): model_type = models.CharField(choices=ModelType.choices) related_item = models.ForeignKey(to=[...], null=True) class Meta: constraints = [ models.CheckConstraint( check=( Q(model_type="empty", related_item__isnull=True) | Q(model_type="non-empty", related_item__isnull=False) ), name="related_item_required_only_when_non_empty", ] I would like to be able to write a function that returns queryset of SomeModel objects with certain properties (for typing purposes): def get_non_empty_models() -> QuerySet[NonEmptySomeModel]: return SomeModel.objects.filter(model_type=ModelType.non_empty) >>> print([ ... some_model.related_item.func() ... for some_model in get_non_empty_models() ... ]) # MyPy complains about related_item being None Is there a way of annotating such qualities of objects for MyPy? -
SLack Interactive Button with django
I am trying to use interactive buttons from my django app to slack but i am facing Invalid_block error like this {'ok': False, 'error': 'invalid_blocks_format'} i am not geting why i am geting this error.i am sending the data as json but still it raising error here is my python code msg_to_other_channel = "<@%s> is on a short break and will be back in %s minutes "%(user,break_duration_admin) msg_to_bot_channel = "Your short break started" blocks = json.dumps( """ { "text": "Would you like to play a game?", "attachments": [ { "text": "Choose a game to play", "fallback": "You are unable to choose a game", "callback_id": "wopr_game", "color": "#3AA3E3", "attachment_type": "default", "actions": [ { "name": "game", "text": "Chess", "type": "button", "value": "chess" }, { "name": "game", "text": "Falken's Maze", "type": "button", "value": "maze" }, { "name": "game", "text": "Thermonuclear War", "style": "danger", "type": "button", "value": "war", "confirm": { "title": "Are you sure?", "text": "Wouldn't you prefer a good game of chess?", "ok_text": "Yes", "dismiss_text": "No" } } ] } ] } """ ) print(blocks) # bot channel Client.chat_postMessage(channel=channel, text=msg_to_bot_channel) # other channel Client.chat_postMessage(channel=other_channel, text=msg_to_other_channel) # sending the button as well to this other channel Client.chat_postMessage(channel=other_channel,text='test',blocks=blocks) <====== -
Which is the best solution in DRF sending an ID of primary key of documents or sending ID with the name of document containing the URL?
i hope everyone is doing good. So, there is an article api containing different parameters including documents model parameter. Documents model is connected to article model using many to many field. The current data that is coming is this [ { "id": 2, "headline": "Article 2", "abstract": "Abstract 2", "content": "Content 2", "published": "2022-08-10T11:28:04.351030Z", "status": true, "get_tags": [ { "id": 1, "tag": "Python" }, { "id": 2, "tag": "Django Rest Framework" } ], "file_documents": [ { "id": 2, "document": "http://127.0.0.1:8000/images/tags-Many_RMVHBid.png" } ], "created_by": "dummyTest" } ] Now here what i want to ask is "file_documents": [ { 1 } If send instead a primarykey instead of whole documents like above. will the data can still be fetched at the frontend and also which one is better this method or the one above this? -
Django test with multiple databases without a default connection
I've created a cut down scenario from scratch to hopefully find a solution to what I have witnessed in some production code - which has stopped me dead in my tracks. The code is here: https://github.com/andez2000/issue-django-multi-db The problem is that I have a Django project - which will support multiple databases. So for this scenario: acmeapp targets acmeapp_db. auth targets auth_db. There is no default connection - all connections are aliased. This is not a direct result from watching the following: https://www.youtube.com/watch?v=GBgRMdjAx_c https://www.youtube.com/watch?v=GBgRMdjAx_c Routers have been setup and configured to direct the models to connections. When running py manage.py test the following errors are evident. AssertionError: Database queries to 'acmeapp_db' are not allowed in this test. Add 'acmeapp_db' to acmeapp.tests.model.TestModels.databases to ensure proper test isolation and silence this failure. Fixing this as suggested yields an additional error: ImproperlyConfigured("Circular dependency in TEST[DEPENDENCIES]") django.core.exceptions.ImproperlyConfigured: Circular dependency in TEST[DEPENDENCIES] core/settings.py DATABASES = { 'default': {}, 'auth_db': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'auth_db.sqlite3', "TEST": {"NAME": "auth_db"}, #'SUPPORTS_TRANSACTIONS': True, }, 'acmeapp_db': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'acmeapp_db.sqlite3', "TEST": {"NAME": "acmeapp_db"}, #'SUPPORTS_TRANSACTIONS': True, } } DATABASE_ROUTERS = [ 'core.db_routers.AuthRouter', 'core.db_routers.AcmeAppRouter' ] tests/model.py from django.test import TestCase from acmeapp.models import Post class TestModels(TestCase): def setUp(self): … -
sqliteDB on Django server is locked after python script INSERT command
I have a Django sqliteDB that is served for two purposes- The Django website is based on it A python script that adds records to that DB When I run the website and the python script everything works fine, UNTILL I try to modify the website info after the python script has run. I can't seem to figure out what process still locks the DB because I'm using commands that are supposed to close it... Sorry in advance for the screenshots. I'm running the code on a different PC and I'm connected to it using AnyDesk... This is the code I'm using in the python script: Maybe I'm just asking too much from the SQLite DB? Or am I not closing still open connections? I didn't encounter these problems when I ran it back on my PC, So I don't seem to understand what changed. -
DRF Serializer `source` in extra_kwargs
I'm getting a weird exception while trying to save the data via DRF using source key in extra_kwargs. Basically, I want to accept the request data using a different key from the model field. My Models.py class UserWishlist(models.Model): wishlist_id = models.UUIDField( primary_key=True, default=uuid.uuid4 ) name = models.CharField(max_length=255, db_index=True) user = models.ForeignKey( User, db_index=True, related_name='user_wishlist', on_delete=models.CASCADE ) class WishlistProducts(models.Model): wishlist = models.ForeignKey( UserWishlist, db_index=True, on_delete=models.CASCADE ) ######## this is the model field that I want to `source` in `extra_kwargs`. product_id = models.UUIDField(blank=True, null=True) product_url = models.URLField() shop = models.ForeignKey( Shops, db_index=True, on_delete=models.CASCADE ) #### This also. But this works fine. My Serializer.py class WishlistProductSerializer(serializers.ModelSerializer): class Meta(object): """Meta.""" model = WishlistProducts fields = ('wishlist_id', 'product_id', 'product_url', 'shop_id', 'created_at', 'updated_at') read_only_fields = ('created_at', 'updated_at') extra_kwargs = { 'shop_id': {'source': 'shop'}, ###### NOT AN ISSUE 'wishlist_id': {'source': 'wishlist'}, ####### ISSUE } My action method in views.py @action(methods=['post'], detail=False) def add_products(self, request): serializer = WishlistProductSerializer( data=request.data, context={'request': request} ) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=201) POST API call on the above view/serializer with below data: { "wishlist_id": "51bb119e-b30a-42e6-ac5b-2608a96aafec", "product_id": "3fa85f61-5717-4562-b3fc-2c963f66afa6", "product_url": "https://googl1e.com", "shop_id": "ffa34976-b82a-469e-b077-83f8962ed34f" } When the POST request is fired, I get a KeyError at /wishlist/add_products/ 'wishlist'. If I remove the source from extra_kwargs for … -
Stripe checkout unable to access my django apps success page on heroku
I am a relatively inexperienced python/django programmer and have run into a issue that i am unable to resolve on my own, inspite of searching around for help. English is not my first language so please do not mind language related errors in my attempt to explain my problem. My django 3.2 App uses stripe checkout for payment. While in development on my local machine, i could process payment and return to my apps success page, but after i deployed it to heroku, it processes the payment but wont return to my apps success page. I have installed the corsheaders package and have tried all the possible settings suggested here on stackoverflow and elsewhere. I am stating my settings below and also the stripe checkout views code. Any help will be highly appreciated. all the relevant settings are as under BASE_DIR = Path(__file__).resolve().parent.parent ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 3rd party 'rest_framework', 'corsheaders', 'crispy_forms', 'sorl.thumbnail', 'cloudinary', 'storages', # local 'accounts.apps.AccountsConfig', 'main.apps.MainConfig', 'api.apps.ApiConfig', 'cart.apps.CartConfig', 'payment.apps.PaymentConfig', 'order.apps.OrderConfig', 'setmenu.apps.SetmenuConfig', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND': … -
object of type 'NoneType' has no len() error, cant seem to solve it
So, I have created an api that does some functionality on a post request and sends a response back. I've tested it in my local machine and it works perfectly as intended. But on the server, it shows this error. [Wed Aug 10 16:11:08.124324 2022] File "/var/www/html/caremigration/careapi/views.py", line 3767, in createSalesOrder [Wed Aug 10 16:11:08.124324 2022] for i in range(len(request.data.get('materials'))): [Wed Aug 10 16:11:08.124328 2022] TypeError: object of type 'NoneType' has no len() I've provided all the details needed and also proof that it works fine in my local machine. Please help me out. Views.py @api_view(['GET','POST']) def createSalesOrder(request): ASHOST='*' CLIENT='*' SYSNR='*' USER='*' PASSWD='*' IT_ITEMS = [] IT_ITEMS_DESC = [] if request.method == 'POST': try: # print(len(request.data.get('materials'))) for i in range(len(request.data.get('materials'))): IT_ITEMS.append({ "MATNR": request.data.get('materials')[i]['MAT_desc']['mat_id'], "QUANTITY":float(request.data.get('materials')[i]['quantity']), "UOM":"cm", "RATE":float(request.data.get('materials')[i]['price']), "VALUE":float(request.data.get('materials')[i]['total']), "CURRENCY":"INR" }) IT_ITEMS_DESC.append({ "DESC":request.data.get('materials')[i]['MAT_desc']['item'] }) # print(IT_ITEMS) I_HEADER = { "PLANT":request.data.get('plant'), "ORD_DATE": datetime.date.today(), "SORG":request.data.get('sorg'), "DIS_CHNL":request.data.get('distribution_channel'), "DIVISION":request.data.get('division'), "CUSTOMER":request.data.get('customer_no'), "TRANSPORTER":request.data.get('trasnporter'), "TRUCK_NUMBER":request.data.get('truck_no'), "LR_NUMBER":request.data.get('lr_no'), "TRUCK_TYPE":request.data.get('truck_type'), "MILK_RUN":request.data.get('milk_run'), "PERMIT_NO":request.data.get('permit_no'), "PERMIT_DATE":"" } with connx(ashost=ASHOST, sysnr=SYSNR, client=CLIENT, user=USER, passwd=PASSWD) as conn: result = conn.call("ZSS_SALES_ORDER_CREATE",I_HEADER=I_HEADER, IT_ITEMS=IT_ITEMS) # print(result) command1 = 'INSERT INTO `scrap_master` (`id`, `scrapid`, `internal_order_no`, `plant`, `cust_no`, `cust_name`, `gp_no_permit_no`, `truck_no`, `truck_type`, `gate_pass_no`, `milk_run`, `status`, `message`, `creation_date`, `created_by`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);' values1 = (None, result['E_INVOICE'], request.data.get('internal_sale_order'), I_HEADER['PLANT'], I_HEADER['CUSTOMER'], request.data.get('customer_name'), I_HEADER['PERMIT_NO'], I_HEADER['TRUCK_NUMBER'], I_HEADER['TRUCK_TYPE'], 'None', … -
RecursionError: maximum recursion depth exceeded in comparison with djongo.exceptions.SQLDecodeError:
I am trying to make an app with django using djongo and mongodb. The connectivity for tables with no foreign key is working fine but where there is a Foreign Key involved, it is throwing this error. I will be greatful if anyone could help. Here are the screenshots. Error image Admin error User is the Foreign Key referencing to id field of accounts -
Django Channels with react not sending data to other clients
Cheers everyone! I have this little problem where everything works fine with websocket except that if I open other client, the data on the other client is not being changed I will post my code and explain more import React, { Component, useEffect, useState } from 'react' import { client, w3cwebsocket } from 'websocket' import { Form, Button, Row, Col, Container } from 'react-bootstrap' function RoomScreen() { const [value, setValue] = useState('initialTest') const [room, setRoom] = useState('new_room') client = new w3cwebsocket( 'ws://' + '127.0.0.1:8000' + '/ws/' + room + '/' ) const testHandler = (e) => { client.send(JSON.stringify({ "click": "Someone Clicked", })) e.preventDefault() } client.onmessage = (e) => { const dataTest = JSON.parse(e.data) if(Object.keys(dataTest)[0] == "sent"){ console.log(dataTest) setValue(dataTest["sent"]) document.querySelector(".test-form").innerHTML = value } } return ( <Container> <Form onSubmit={testHandler}> <Form.Group controlId='test'> <Form.Label className='test-form'>Dumb Test</Form.Label> </Form.Group> <Button type='submit' variant='primary'> Click Test </Button> </Form> </Container> ) } What should happen is when I receive a message from the backend i use query selector to change form.label to that message It is working on one client but if I open another client the form.Label is not changing I hope I was clear enough -
DJango Post csrf_token invalid and /favicon.ico not found
I got a problem with DJango. Im trying to send data to a SQL Database in DJango. So I need my token, which I get with {{ csrf_token }}. But when I send the data on the HTML Website, it tells me POST 403 Forbidden and the DJango Terminal says NotFound: /favicon.ico, as well as Forbidden (CSRF token from POST has incorrect length.): /ausgeben/ Does anyone have a solution for this. Down below is the code I`m using for the token request. Thanks! let formData = new FormData(); formData.append("name", name); formData.append("gewinde", gewinde); formData.append("laenge", laenge); formData.append("durchmesser", durchmesser); //formData.append("containerNR", containerNR); formData.append('csrfmiddlewaretoken', token); fetch('/ausgeben/',{ method: 'POST', body: formData }); -
"Got KeyError when attempting to get a value for field `pet_name` on serializer `PatientSerializer`
I am trying to get the most popular pet type with viewsets in django, but when i write this code class PopularPetTypeViewSet(viewsets.ModelViewSet): queryset = models.Patient.objects.all() serializer_class = serializers.PatientSerializer def get_queryset(self): try: return models.Patient.objects.values('pet_type').annotate(count=Count('pet_type')).order_by('-count') except Exception as e: return Response({'error':str(e)}) i get this error "Got KeyError when attempting to get a value for field `pet_name` on serializer `PatientSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'pet_name'." my models.py from django.db import models from django.utils.translation import gettext_lazy as _ # Create your models here. class Patient(models.Model): pet_name = models.CharField(max_length=255) cat = 'cat' dog = 'dog' bird = 'bird' PET_TYPE_CHOICES = [ (cat, cat), (dog, dog), (bird, bird), ] pet_type = models.CharField("Select Pet Type", choices=PET_TYPE_CHOICES, null=False, max_length=15) owner_name = models.CharField("Owner Name",max_length=255) owner_address = models.CharField("Owner Address", max_length=255, null=True, blank=True) owner_phone_number = models.CharField("phone", max_length=11, blank=False, default='') def __str__(self): return str(self.id) class PatientAppointment(models.Model): patient_id = models.ForeignKey(Patient, on_delete=models.DO_NOTHING, null=True) #, null=TrueSS) appointment_start_time = models.DateTimeField(_("Appointment start time"), auto_now=False, auto_now_add=False) appointment_end_time = models.DateTimeField(_("Appointment end time"), auto_now=False, auto_now_add=False) description = models.CharField(_("Enter description"), max_length=1024) USD = 'USD' EUR = 'EUR' BITCOIN = 'BITCOIN' PAYMENT_TYPE_CHOICES = [ (USD, USD), (EUR, EUR), (BITCOIN, BITCOIN), ] payment_type = models.CharField("Select payment Type", … -
Django template dispalys wrong/bad data
I am making a CRM system in which there are quite a lot of ordinary things But I stumbled upon a rather non-standard problem The template engine returns incorrect data, although when I display them in the console, everything is in order Screenshots will be below. "Experienced" models got calculated everything properly,but "New" models displaying wrong data Look at the console: It must be None everywhere,but instead im getting data just like I didnt refresh page,but i really did P.S. Im making database queries inseparate functions to which I pass GET parameters What could be the reason of this issue ? Thanks in advance -
How to get data from two different models in Django?
So, I have these two models in my Django application. class Persons(models.Model): name = models.CharField(max_length=254) def __str__(self): return self.name class PersonsImage(models.Model): person = models.ForeignKey(Persons, on_delete=models.CASCADE) image = models.ImageField(upload_to='static/images/', default="") So my question is, how can I query or connect these two models where I can get all the images of a particular person? Thanks in advance. -
Django project cloned form github
mainly please tell the meaning of this code literally confused with it {% encore_entrypoint_js 'page_index' %} {% block title %}{% translate 'AlmaLinux OS - Forever-Free Enterprise-Grade Operating System' %}{% endblock %} 7 {% block description %} 8 {% translate 'An Open Source, community owned and governed, forever-free enterprise Linux distribution.' %}{% endblock %} 9 10 {% block head_end %} 11 <link rel="stylesheet" href="/static/css/second.css"><link rel="stylesheet" href="/static/css/main.css"> 12 13 <link rel="stylesheet" href="/static/css/first.css"> 14 {% endblock %} 15 {% block body_end %} 16 {% encore_entrypoint_js 'page_index' %} *************Check this line it shows an error 17 {% endblock %} 18 19 {% block body %} 20 <section class="al-page-index"> 21 <!-- HERO --> 22 <div class="container al-py-lg"> 23 <div class="row flex-lg-row-reverse align-items-center py-2 py-md-5"> 24 <div class="d-none d-lg-block col-10 col-sm-8 col-lg-6"> 25 {# TODO #} 26 {# <a href="{% url 'showcase_index' %}">#} -
HOW To Filter within a Filter Django
I'm trying to filter category with age range , i want to see people in cirtian gender and then their age range my models from django.db import models # Create your models here. class catagory(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class Age(models.Model): range = models.CharField(max_length=150) def __str__(self): return self.range class person(models.Model): name = models.CharField(max_length=100) gender = models.ForeignKey(catagory, on_delete=models.CASCADE) age_range = models.ForeignKey(Age, on_delete=models.CASCADE) @staticmethod def get_person_by_cataegoryID(categoryID): if categoryID: return person.objects.filter(gender=categoryID) else: return person.objects.all() @staticmethod def get_person_by_age_range(AGE_RANGE): if AGE_RANGE: return person.objects.filter(age_range=AGE_RANGE) else: return person.objects.all() def __str__(self): return self.name My views from django.shortcuts import render from .models import catagory,person,Age # Create your views here. def index(request): c = catagory.objects.all() categoryID = request.GET.get('category') AGE_RANGE = request.GET.get('age_range') p= person.objects.all() a = Age.objects.all() if categoryID: persons = person.get_person_by_cataegoryID(categoryID) elif AGE_RANGE: persons = person.get_person_by_age_range(AGE_RANGE) else: persons = person.objects.all() context = { "person": p, "catagory": c, "age": a } context["person"] = persons return render(request, "index.html", context) **My Template ** <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>hello</h2> <div style="display:flex;height:100vh;width:100vw;align-items:center;justify-content:space-around;"> <div style="display:flex;flex-direction:column;"> {% for a in age %} <a href="/?age_range={{a.id}}">{{a.range}}</a> {% endfor %} </div> <div style="display:flex;flex-direction:column;"> <a href="/">All</a> {% for c in catagory %} <a href="/?category={{c.id}}">{{c.name}}</a> {% endfor %} </div> <br> <div style="display:flex;flex-direction:column;"> {% … -
Django: URL path is not working / 404 Page not found
I'm trying to build an API with Django for the first time. To see if everything works, I tried to implement a get method at a "try/" endpoint and return a simple json containing "name":"myname". The django app is running succesfully and the admin page works as intended. The endpoint "admin/try" is not reachable though and returns a 404. I have all the files related to the api in a seperate folder, not in the folder of the actual app. This should, according to some tutorials, not be a problem. This is the GET method I am trying to call at the "try/" endpoint. Its located in views.py in the api folder. from rest_framework.response import Response from rest_framework.decorators import api_view @api_view(['GET']) def tryMethod(request): something = {'name':'myname'} return Response(something) This is the urls.py file in the api folder: from django.urls import path from . import views urlpatterns = [ path('try/', views.tryMethod)] This is the urls.py file in the folder of the actual app from django.urls import path, include from django.contrib import admin from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView from . import views urlpatterns = [ path('admin/', admin.site.urls), path('health/', views.health, name='health'), path('schema/', SpectacularAPIView.as_view(), name='schema'), path('docs/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'), path('404', views.handler404, name='404'), path('500', views.handler500, name='500'), … -
django permissions for block ip addresses import Blocklist
In django custom permissions for blocking ip addresses it seems its using some sort of model named Blocklist but I don't know how to import this model? from rest_framework import permissions class BlocklistPermission(permissions.BasePermission): """ Global permission check for blocked IPs. """ def has_permission(self, request, view): ip_addr = request.META['REMOTE_ADDR'] blocked = Blocklist.objects.filter(ip_addr=ip_addr).exists() return not blocked -
Django models choices - allow only specific transitions on the admin interface
for a models.IntegerField I can define easily choices with sth = models.IntegerField(choices=( (1, 'sth1'), (2, 'sth2'), (3, 'sth3'), )) . Is there any way where I can restrict the transitions from one value to another one? For instance if the current value is '1', it can go only to '2', but if the current value is '3', it can go to '1' and '2', etc. I need this restriction only on the admin interface. Is there anything built in for that? Thanks. -
How to make requests faster in Django
I have this code which parse a json file which has around 400 URL's and send request to each one based on the search term and retrieve it's status code. When I run this it take's lots of time(more than 10 minutes), I am wondering if there any way I can make this code fetch these URL's and it's status code in less than 10 seconds. views.py def get_sites(request): all_sites = {} if 'name' in request.GET: name = request.GET['name'] with open('sites-data.json') as f: data = json.load(f) mod_data = json.loads(json.dumps(data).replace("{}",name)) for item in mod_data: if mod_data[item]['errorType'] == "status_code": url = mod_data[item]['url'] response = requests.head(url, allow_redirects=False) status_code = response.status_code if status_code == 200: site_data = Search( term = name, sitename = item, is_available = True, ) site_data.save() else: site_data = Search( term = name, sitename = item, is_available = False, ) site_data.save() all_sites = Search.objects.all().order_by('-id') return render(request, 'main/search.html',{"all_sites":all_sites} ) search.html <div class = "container"> <br> <h2 class = "text-center">SEARCH SITES</h2> <br> <form method="GET"> <input type = "text" name = "name" placeholder="Search..." class = "text-center"> <button type = "submit" class = "btn-danger btn-sm">Search</button> </form> </div> -
Django clean method cause is_valid() false
here is my model: class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=200) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) stock = models.PositiveIntegerField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = models.Manager() available = ProductStockManager() and I have a form like this: class ProductForm(ModelForm): name = forms.CharField(max_length=200) price = forms.DecimalField(decimal_places=2) description = forms.Textarea() class Meta: model = Product fields = ['category', 'name', 'description', 'price', 'stock'] def clean_description(self): pass def clean_price(self): pass def clean_name(self): pass in my form when I use clean_field() for each field it makes is_valid() False except clean_description() what is this for ? why when I use clean_price(), clean_name() my is_valid() returns False? and why it doesn't when I use clean_description() ? -
The django rest framework is not able to recognize the User defined as foreign key
I'm trying to save a user profile information in a django model. The model is defined as follows class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) reg_date = models.DateTimeField(auto_now_add=True, blank=True) name = models.CharField(max_length=30, blank=True) family = models.CharField(max_length=30, blank=True) phoneNumber = models.CharField(max_length=20, blank=True) def __str__(self) : return self.name + self.family The serializer for the model is defined as: class UserProfileSerializer(serializers.ModelSerializer): class Meta: model= UserProfile fields = ['user', 'reg_date', 'name', 'family', 'phoneNumber'] and the view is as follows: class UserProfileView(viewsets.ViewSet): def create(self, request): UserProfile.objects.create(user = request.user) I'm sending a post request using axios as follows: const a = await ProfileAPI.post('', { headers: { 'Authorization': mytoken } }) in which mytoken is a logged in user token provided by dj-rest-auth API. Although the token is OK and the UserProfileView is executed by the request, I got the following error by the django rest: ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x000001F069C59190>": "UserProfile.user" must be a "User" instance. Am I missed something? Is there any problem with my request or view? Please help me to fix this problem -
How to get real time stock price and plot chart
I'm working on a project in which I have to get the stock price in real time and plot the chart (like tradingview, yahoo etc) in react js. I have found a few APIs on RapidAPI but they allow to limited API call per minute. Tech stack: python, django for back-end and react js for front-end