Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to call other methods in a class in django when self is not supplied as an argument
I come from PHP/Laravel Background where for calling methods or accessing properties within a class ,use of $this keyword is sufficient.In python3/Django4.0.6 i have to use request as first parameter to capture the request body for eg. class CustomAuth: def verifyToken(token): pass def login(request): data = request.body # how do i call verifyToken? # if i use self as first argument then i am not able to access the request -
Django Makemigrations adds Alter field Alert id on every Model [error]
i use django and a sql server. I changed my database connection from django-pyodbc-azure to mssql: DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': '', 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', 'OPTIONS': {'driver': 'ODBC Driver 17 for SQL Server'}, }, } I have connection to the database and everything works fine. But now i want to make some migrations on my models.I am getting alter filed alert every time when i run the command python manage.py makemigrations on all my models like: [36;1mMigrations for 'processinformation':←[0m [1mprocessinformation\migrations\0008_alter_automatisierungsgrad_id_alter_baugruppe_id_and_more.py←[0m - Alter field id on Prozessmapping -... The model looks like this: class Prozessmapping(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True, blank=True) bezeichnung = models.CharField(max_length=200) projektnr = models.CharField(max_length=200) The migration-file looks like this: migrations.AlterField( model_name='prozessmapping', name='id', field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), ), I tried python manage.py migrate but I get the following error: in _alter_field raise NotImplementedError("the backend doesn't support altering from/to %s." % t.__name__) NotImplementedError: the backend doesn't support altering from/to AutoField. -
FieldDoesNotExist( django.core.exceptions.FieldDoesNotExist: moontag_app.product has no field named 'catagory'
when i do the python manage.py makemigrations in the terminal i get the error: FieldDoesNotExist( django.core.exceptions.FieldDoesNotExist: moontag_app.product has no field named 'catagory', but the filed is exist class Product(models.Model): title = models.CharField(max_length=200) slug = models.CharField(max_length=400) detail = models.TextField() specs = models.TextField() category = models.ForeignKey(Category,on_delete=models.CASCADE) brand = models.ForeignKey(Brand,on_delete=models.CASCADE) color = models.ForeignKey(Color,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) status = models.BooleanField(default=True) is_featured = models.BooleanField(default=False) -
Django field validation on form submit from outside the form
In my Django application I have a button with type submit and form parameter set that is located outside the actual form. When I hit submit frontend validation is just partly working. forms.py: class SubscriptionForm(forms.ModelForm): omitted... http = forms.URLField() form part of html: <button id="btn_submit_1" type="submit" form="f_subscription" title="Save"></button> <form id="f_subscription" method="post" enctype="multipart/form-data" {% if form_submitted %}class="was-validated" {% endif %}> {{ form.http|as_crispy_field }} <button id="btn_submit_2" type="submit" title="Save"></button> </form> When submitting the form with btn_submit_1 invalid field is just focused When submitting the form with btn_submit_2 url validation is working Any ideas how to fix form validation here? -
Passing thru Password field to run( sys.executable) error on run
on command: On conn bind pass true ldap3.extend.microsoft.modifyPassword. ad_modify_password(conn, dn, password, old_password=None) On View.py scriptFile = 'support01\\ldap_cmd.py' base_dir = settings.BASE_DIR config_path = os.path.join(base_dir, scriptFile) run([sys.executable, config_path, current_user.username, var_selfpassword,var_Usernameset,var_Setpassword]) Error when executing. conn = Connection(Server('ldaps://xxxx.xxxx.local', port=636, use_ssl=True), File "C:\perforce_workspace\Python\support01 venv\lib\site-packages\ldap3\core\connection.py", line 363, in __init__self._do_auto_bind() File "C:\perforce_workspace\Python\support01 venv\lib\site-packages\ldap3\core\connection.py", line 389, in _do_auto_bind self.bind(read_server_info=True) File "C:\perforce_workspace\Python\support01 venv\lib\site-packages\ldap3\core\connection.py", line 604, in bind request = bind_operation(self.version, self.authentication, self.user, self.password, auto_encode=self.auto_encode) File "C:\perforce_workspace\Python\support01 \venv\lib\site-packages\ldap3\operation\bind.py", line 57, in bind_operation request['authentication'] = AuthenticationChoice(). setComponentByName('simple', Simple(validate_simple_password(password))) File "C:\perforce_workspace\Python\support01 venv\lib\site-packages\ldap3\protocol\sasl\sasl.py", line 136, in validate_simple_password password = sasl_prep(password) File "C:\perforce_workspace\Python\support01\venv \lib\site-packages\ldap3\protocol\sasl\sasl.py", line 53, in sasl_prep if stringprep.in_table_c12(c): File "C:\Users#######\AppData\Local\Programs\Python\Python39 lib\stringprep.py", line 211, in in_table_c12 return unicodedata.category(code) == "Zs" and code != " " TypeError: category() argument must be a unicode character, not str -
django error. what is this frozen ?? and how to deal with it?
File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 992, in _find_and_load_unlocked File "", line 241, in _call_with_frames_removed File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'house' -
django-filter - 'FormSet' object has no attribute 'model'
I am using django-filter to create search functionality on my page. However, instead of items from the particular model I want to filter values that I am rendering in the initial method in my RequestFormset so once the page is loaded, all values from the Components model are rendered and the user is able to insert a number of units through input field. The problem that I am having is that I don't know how to integrate my formset and django-filter library. Do you have any idea how can I achieve something like this? views.py class CostCalculatorView(TemplateView): template_name = "cost_calculator.html" def get(self, *args, **kwargs): get_components = Components.objects.all() get_datetime = timezone.now().strftime('%Y-%m-%dT%H:%M:%S') formset = RequestFormset(initial=[{ 'author': self.request.user.email, 'related_product': component.related_product, 'related_component': component.id, 'created': get_datetime, 'number_of_units': 0 } for component in get_components]) filterForm = RequestFilter(self.request.GET,queryset=formset) # how to pass values from initial mwthod here? formset = filterForm.qs return self.render_to_response( {'calculator_formset': formset, 'filterForm': filterForm, }) def post(self, *args, **kwargs): formset = RequestFormset(data=self.request.POST) if formset.is_valid(): for form in formset: created = form.cleaned_data.get('created') qs = Requests.objects.filter(author=self.request.user, created=created) form.save() dataset = RequestResource().export(qs) response = HttpResponse(dataset.xlsx, content_type="xlsx") response['Content-Disposition'] = 'attachment; filename=CE_{created}.xlsx'.format(created=created) return response filters.py class RequestFilter(django_filters.FilterSet): class Meta: model = CERequest fields = ('related_product', 'related_component') forms.py class RequestForm(forms.ModelForm): author … -
Replace all spaces to dash in all my "url" object from my article model
I would like to replace all the spaces in my defined url objects from my Article model to "-". However, my code below doesn't seem to work. def index(request): change_urls = Article.objects.all() for i in change_urls: i.url.replace(" ", "-") i.save() -
Looping through object attributes in Django
I'm not sure how to correctly phrase the question but I have a model for a photo gallery: class PhotoGallery(models.Model): title = models.CharField(max_length=200, unique=True) collection = models.CharField(max_length=200) img = models.FileField(upload_to =f'pics/gallery/{collection}') created_on = models.DateTimeField(auto_now_add=True) and I'm trying to figure out a way to get images separately from each collection - views.py: def photo_gallery(request): form = GalleryForm(request.POST) if request.method == "POST": if form.is_valid(): images = request.FILES.getlist('images') collection = form.cleaned_data['collection'] title = form.cleaned_data['title'] for image in images: PhotoGallery.objects.create(img=image, collection=collection, title=title) images = PhotoGallery.objects.all() #not what i think it is - just hoping it could make what i want to do clearer context = [collection.img for collection in images] return render(request, 'photos/photos.html', context) I haven't been able to find much info in the docs or anywhere online about this. I'm wondering if the solution would be to have a separate model for each collection but even then I'd run into issues if I wanted to add a new collection. So any suggestions on how I could do this would be appreciated. Is there perhaps an object method where I could do PhotoGallery.objects.something() -
run external script using subprocess in django and render output in html
im new to django, im trying to call an external python script with a simple sum function, im stuck with this since weeks ago and couldnt find an answer, thanks for help. here's my form: from django import forms class derivForm(forms.Form): a = forms.IntegerField(widget = forms.NumberInput()) b = forms.IntegerField(widget = forms.NumberInput()) my view: from django.shortcuts import render from .forms import derivForm import subprocess from subprocess import PIPE import sys def external(request): if request.method == 'POST': form = derivForm(request.POST or None) if form.is_valid(): a:form.cleaned_data['a'] b:form.cleaned_data['b'] out1=subprocess.run([sys.executable,'C:/dakchidiali/python/options/mysite/polls/essai.py','a','b'],shell=True) print(out1) else: form = derivForm() return render(request,'price-it.html',{'result':out1}) finally my html: <form action="/polls/external/" method=“POST“> {% csrf_token %} {{ form }} <button type="submit" name="run_script">Run script</button </form> {{ result }} -
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