Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to use paypal instead of razorpay - django
how to use paypal instead of razorpay in this code .. my code https://gofile.io/d/wV8btv I want to use paypal and save the rest of the codes -
How to make query to postgresql database from Django
This is my request for postgresql: SELECT date, COUNT(*) FROM main_like GROUP BY date; How can i do this request from Django? -
How to use django-colorfield in a forms.py file in django?
I'm trying to use Django-colorfield to create a drop-down from which a color can be selected. However, the priority section in the output just says <colorfield.fields.ColorField>.I tried this answer but it didn't work. Output, Code: #models.py from django.db import models from colorfield.fields import ColorField class Todo(models.Model): text = models.CharField(max_length=40) complete = models.BooleanField(default=False) COLOR_CHOICES = [ ("#8b0000", "red"), ("#ffff00", "yellow"), ("#006400","green") ] priority = ColorField(choices=COLOR_CHOICES) def __str__(self): return self.text #forms.py from django import forms from colorfield.fields import ColorField from .models import Todo class TodoForm(forms.Form): text = forms.CharField(max_length=40, widget=forms.TextInput( attrs={'class' : 'form-control', 'placeholder' : 'Enter todo here', 'aria-label' : 'Todo', 'aria-describedby' : 'add-btn'})) COLOR_CHOICES = [ ("#8b0000", "red"), ("#ffff00", "yellow"), ("#006400","green") ] priority = ColorField(choices=COLOR_CHOICES) -
Blog: How can I make a blog where I can load what ever JS/CSS file I want and format it to what ever layout I want?
So I want to create a unique type blog using Django but I am confused in how I would go about making it. I want to be able to load any library I want but also make the blog entries have unique layout and have different CSS files for each one if overridden from the default. I want to be able to show off my skills from D3.js to Greensocks, ML models I have trained to different things like data structures, algorithms and libraries/technolgies, I really want to peakcock my range of skills I have collected over the past 20 years but Django seems to be a one style fits solution when it comes to blog entries. I want to include many skills in a blog but how to do it has me confused. So far I have done a few tutorials where I have made a basic blog and the voting tutorial aswell as watched some tutorials on YouTube but I'm stuck on how I would create a page that has custom styling and scripts. I have though about making it so I past a whole bunch of HTML into a textfield which does work but looks absolutly terrible … -
Add a CheckConstraint for a related object field in Django models
I've two Django models: class A(models.Model): is_pure = models.BooleanField() class B(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) class Meta: constraints = [ models.CheckConstraint( check=models.Q(a__is_pure=True), name="a_is_pure" ) ] I want to add a constraint that no B instance can have a reference to an A instance that its is_pure field is False. When I add the above code, make migrations, and try to migrate, I get this error: (models.E041) 'constraints' refers to the joined field 'a__is_pure'. Does Django support such thing currently ? If not, what do you recommend? -
Why is django-money running incorrectly in my view?
I am using django-money to make conversions on my backend of the project but it is converting wrong. For example, I want to convert TRY to USD: I enter 1000000 TRY it returns 480629.66 USD, but it should be: 120055.20 USD. How can I solve it? views.py def customer(request): form_class = NewCustomerForm current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) company = userP[0].company if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): form = NewCustomerForm(request.POST) # Check if the form is valid: if form.is_valid(): newCustomer = form.save() newCustomer.company = company selected_currency = newCustomer.currency_choice selected_limit = newCustomer.credit_limit newCustomer.usd_credit_limit = convert_money(Money(selected_limit, selected_currency), 'USD') cred_limit = newCustomer.usd_credit_limit value = str(cred_limit)[1:] # float_str = float(value) float_str = float(cred_limit.amount) newCustomer.credit_limit = float_str newCustomer.save() return redirect('user:customer_list') else: form = form_class() return render(request, 'customer.html', {'form': form}) forms.py class NewCustomerForm(forms.ModelForm): ... class Meta: model = Customer fields = ('customer_name', 'country', 'address', 'customer_number', 'phone_number', 'email_address', 'credit_limit', 'currency_choice', 'risk_rating', 'parent', 'entity') models.py class Customer(models.Model): ... CURRENCIES = [ ('USD', 'USD'), ('EUR', 'EUR'), ('GBP', 'GBP'), ('CAD', 'CAD'), ('CHF', 'CHF'), ('DKK', 'DKK'), ('PLN', 'PLN'), ('HUF', 'HUF'), ('CZK', 'CZK'), ('RUB', 'RUB'), ('KZT', 'KZT'), ('BGN', 'BGN'), ('RON', 'RON'), ('UAH', 'UAH'), ('TRY', 'TRY'), ('ZAR', 'ZAR'), ] .... currency_choice … -
React is not hiting django apis on kubernetes clustor
I am new to Kubernetes and this is my first time deploying a react-django web app to Kubernetes cluster. I have created: frontend.yaml # to run npm server backend.yaml # to run django server backend-service.yaml # to make django server accessible for react. In my frontend.yaml file I am passing REACT_APP_HOST and REACT_APP_PORT as a env variable and changed URLs in my react app to axios.get('http://'+`${process.env.REACT_APP_HOST}`+':'+`${process.env.REACT_APP_PORT}`+'/todolist/api/bucket/').then(res => { setBuckets(res.data); setReload(false); }).catch(err => { console.log(err); }) and my URL becomes http://backend-service:8000/todolist/api/bucket/ here backend-service is name of backend-service that I am passing using env variable REACT_APP_HOST. I am not getting any errors, but when I used kubectl port-forward <frontend-pod-name> 3000:3000 and accessed localhost:3000 I saw my react app page but it did not hit any django apis. On chrome, I am getting error net::ERR_NAME_NOT_RESOLVED and in Mozilla Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://backend-service:8000/todolist/api/bucket/. (Reason: CORS request did not succeed). Please help on this issue, I have spent 3 days but not getting any ideas. frontend.yaml apiVersion: apps/v1 kind: Deployment metadata: creationTimestamp: null labels: app: frontend name: frontend spec: replicas: 1 selector: matchLabels: app: frontend strategy: {} template: metadata: creationTimestamp: null labels: app: frontend spec: … -
Django ForeignKey field ignored by graphene-django when "to" value is a string
Versions: Python: 3.8 Django: 3.2.2 graphene-django: 2.15.0 I have an issue when using graphene-django with a ForeignKey field is ignored because the value of to is a string. Here's the Django model: class CableTermination(models.Model): cable = models.ForeignKey( to='dcim.Cable', on_delete=models.SET_NULL, related_name='+', blank=True, null=True ) The value of to is a string to avoid a circular import. This is also the only field (apart from pk) on this model. I've created a DjangoObjectType from this class: class CableTerminationNodeType(DjangoObjectType): class Meta: model = CableTermination I also have a type for Cable: class CableNodeType(DjangoObjectType): class Meta: model = Cable But on startup I see this error: env/lib/python3.8/site-packages/graphql/type/definition.py", line 214, in define_field_map assert isinstance(field_map, Mapping) and len(field_map) > 0, ( AssertionError: CableTerminationNodeType fields must be a mapping (dict / OrderedDict) with field names as keys or a function which returns such a mapping. I've tracked this down to field_map having length 0. I have also observed that the converter for the above cable field is called but returns None. This is because field.related_model returns the string dcim.Cable but the registry can only lookup by class. So ultimately, _type is None below: @convert_django_field.register(models.OneToOneField) @convert_django_field.register(models.ForeignKey) def convert_field_to_djangomodel(field, registry=None): model = field.related_model def dynamic_type(): _type = registry.get_type_for_model(model) if … -
access to foreign key fields with fields name
I need access to foreign key fields with string fields name: for example: In a def in Document model , I need access to customer__customer_name [customer model -> customer_name field] Mycode: class Customer(LaundryModel, models.Model): customer_code = models.CharField(max_length=100, unique=True) customer_name = models.CharField(max_length=100) class Document(LaundryModel,models.Model): document_number = models.IntegerField(unique=True) date = models.DateTimeField(auto_now_add=True) customer = models.ForeignKey("customer.customer", on_delete=models.PROTECT, related_name='+') json_fields=["customer__customer_name", "customer__customer_code"] def send_email(self): ###### in this place Need access to customer_name and customer_name from customer foreign key ###### I try to this with getattr or values or another but not working -
I want to list all elements from abstract class Product and its categories (Smartphones, Tv ) etc
class ProductSerizer(serializers.ModelSerializer): category = serializers.PrimaryKeyRelatedField(queryset=Category.objects) title_of_product = serializers.CharField(required=True) slug = serializers.SlugField(required=True) image_of_product = serializers.ImageField(required=True) description_of_product = serializers.CharField(required=True) price_of_product = serializers.DecimalField(max_digits=12, decimal_places=2, required=True) class Product(models.Model): class Meta: abstract = True category = models.ForeignKey(Category, verbose_name="category", on_delete=models.CASCADE) title_of_product = models.CharField(max_length=225,verbose_name="Title",null=True) slug = models.SlugField(unique=True) image_of_product = models.ImageField(verbose_name="Image", null=True) description_of_product = models.TextField(verbose_name = "Descripwtion", null = True) price_of_product = models.DecimalField(max_digits=10,decimal_places=2, verbose_name="Price", null=True) and I want to list all elements from categories, but I cannot serialize this class. How should I do ? -
Sharing the session cookie between same site (using iframe). Django
A quite basic question. Consider this: I want them (only green) to share this sessionid cookie, so they both share request.session. Is it that possible? I log in on the left but then I don't see me logged in in the iframe, so I understand they are not sharing sessionid cookie. Why?? They are the same domain!! Thanks in advance! ;-) Note: I am using Django 1.11 and python 2.7 -
How can I delete an object from a m2m relationship without deleting all of them?
I'm trying to get my user to delete a 'favorite' item. The item is in the model Profile as a 'Favorite', which is a M2M relationship. However, when I try to delete the favorite item, all of them get deleted instead of one. How can I manage to delete only the object I select by its id instead and not all of them? This is the part of the view with the request that deletes all of them instead of one: if request.method=='POST' and 'favorite_id' in request.POST : favorite_id = request.POST.get("favorite_id") favorite = Favorite.objects.get(mal_id = favorite_id) favorite.delete() This is the html part: <div class="row"> {% for favorite in user.profile.favorites.all %} <form method="POST"> {% csrf_token %} <input type="hidden" value="{{ favorite.Id }}" name="favorite_id"> <button type="submit" class="btn btn-outline-danger" style="font-size:8px; border-radius: 50%">x</button> <div class="col-sm-12 col-md-6 col-lg-4 pb-4"> <div class="h-100"> <img src="{{ favorite.image }}" class="card-img-top" alt="{{ favorite.title }}" style="width: auto; height: 225px; object-fit: scale-down;"> <div class="card-body"> <h5 class="card-title">{{ favorite.title }}</h5> <p class="card-text text-muted" style="font-size:12px">Episodes: {{ favorite.episodes }}</p> </div> </div> </div> </form> {% endfor %} </div> The model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) favorites = models.ManyToManyField(Anime, related_name='favorited_by', null=True, blank=True) -
Not able to install "mysqlclient" package in python
(venv) C:\Users\Grv\PycharmProjects\Employee>pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.0.3.tar.gz (88 kB) Using legacy 'setup.py install' for mysqlclient, since package 'wheel' is not installed. Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: 'c:\users\grv\pycharmprojects\employee\venv\scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Grv\\AppData\\Local\\Temp\\pip -install-i_sgg0o6\\mysqlclient_263511bdd06944be9431012ebadf8f3b\\setup.py'"'"'; __file__='"'"'C:\\Users\\Grv\\AppData\\Local\\Temp\\pip-install-i_sgg0o6\\mysqlclient_263511bdd06944be94310 12ebadf8f3b\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.rea d().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\Grv\AppData\Local\Temp\pip-record-rk5je4if\install-record.txt ' --single-version-externally-managed --compile --install-headers 'c:\users\grv\pycharmprojects\employee\venv\include\site\python3.8\mysqlclient' cwd: C:\Users\Grv\AppData\Local\Temp\pip-install-i_sgg0o6\mysqlclient_263511bdd06944be9431012ebadf8f3b\ Complete output (29 lines): running install running build running build_py creating build creating build\lib.win32-3.8 creating build\lib.win32-3.8\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.8\MySQLdb creating build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.8\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension creating build\temp.win32-3.8 creating build\temp.win32-3.8\Release creating build\temp.win32-3.8\Release\MySQLdb C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.28.29910\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(2,0,3,'final',0) -D __version__=2.0.3 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include\mariadb" -Ic:\users\grv\pycharmprojects\employee\venv\include -IC:\Users\Grv\AppData\Local\Programs\Python\ Python38-32\include -IC:\Users\Grv\AppData\Local\Programs\Python\Python38-32\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.28.29910\include" " -IC:\Program Files … -
Displayed Form PointField on my GeoDjango template
I cannot display the PointField map of the widget on my html file. I need help I want to index the position of the different company sites. On the admin page, there is no problem but at the level of the html file this is where there is a problem. Thank you model.py : class position(models.Model): title = models.CharField(blank=True,max_length=150) location = models.PointField(blank=True,geography=True,) address = models.CharField(blank=True,max_length=100) city = models.CharField(blank=True,max_length=50) def __str__(self): return self.title form.py : class PositionForm(forms.Form): title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'title'})) address = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'address'})) city = forms.CharField(widget=forms.Select(attrs={'class': 'form-control', 'placeholder': 'city'},choices=CITY_CHOICES)) location = forms.PointField(widget=forms.OSMWidget( attrs={ 'map_width': 600, 'map_height': 400, 'template_name': 'gis/openlayers-osm.html', })) views.py : def create_position(request): if request.method == 'POST': form = PositionForm(request.POST) if form.is_valid(): data = position() data.title = form.cleaned_data['title'] # get product quantity from form data.location = form.cleaned_data['location'] data.address = form.cleaned_data['address'] data.city = form.cleaned_data['city'] data.save() # Create data in profile table for user messages.success(request, 'Your position has been created!') return redirect('/home/') else: messages.warning(request, form.errors) return redirect('/recognition/create_position/') form = PositionForm() context = { 'form': form, } return render(request, 'recognition/create_position.html', context) -
In Django I cannot retrieve the selected value from database its a dropdown in status field also cant retrieve the selected file in upload cv
this is my edit.html code I want to retrieve the selected value from database in status field its a dropdown also I have Upload cv which is a file field I want to retrieve the selected file too how can I do that I am not getting any solution <section class="site-section"> <div class="container"> <div class="row"> <div class="col-lg-12 mb-5"> <h2 class="mb-4 text-center">Update Candidate Details</h2> <form method="POST" action="/update/ {{i.id}}/" enctype="multipart/form-data" class="p-4 border rounded" onsubmit="myFunction()" > {% csrf_token %} {% comment %} <input type="hidden" name="csrfmiddlewaretoken" value="UabxqpD8HGPOu1ZSFnIHAPbMtRgWBAnVHEs8bLDx0HnxN6uhG3LyYvZShvcx1ekn"> {% endcomment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="full_name">Full Name :</label> <input type="text" class="form-control" value ={{ i.full_name}} name="full_name" id="id_full_name" placeholder="Enter First Name"> </div> </div> <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="recruiter_name">Recruiter Name :</label> <input type="text" class="form-control" value ={{ i.recruiter_name }} name="recruiter_name" id="id_recruiter_name" placeholder="Enter Recruiter Name"> </div> </div> {% comment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="id_last_name">Last Name :</label> <input type="text" class="form-control" name="last_name" id="id_last_name" placeholder="Enter Last Name"> </div> </div> {% endcomment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="email">Email :</label> <input type="email" class="form-control" value ={{i.email }} name="email" id="id_email" placeholder="Enter Email"> </div> </div> <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="noticeperiod">Notice Period (in … -
override django-allauth custom create user
I'm using allauth for social authentication with custom user model where i don't have username field and the email field is also not required.(as I'm using phone as username). process goes fine till allauth want to create the user here i face django.db.utils.IntegrityError: UNIQUE constraint failed: user_user.phone so trying to override the default allauth create user method. I have no idea here all i know is from allauth.account.adapter import DefaultAccountAdapter class MyAccountAdapter(DefaultAccountAdapter): # sticks here any idea ? :( -
Difficulty Customizing the body bgcolor in app template; tried moving app name over django admin app of INSTALLED APPS, overriding bootstrap
Necessary updates in settings.py INSTALLED_APPS = [ 'store.apps.StoreConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] main.html file <!DOCTYPE html> <html lang="en"> {% load static %} <head> <title>Ecom</title> <meta charset="UTF-8"> <!-- CSS only --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'css/main.css' %}"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h2>main</h2> (% block content %} {% endblock %} </body> CSS file main.css body { background: #FF0000; } also tried using !important (despite knowing it isn't a good practice) The template I was trying to render, store.html {% extends 'store/main.html' %} {% load static %} {% block content %} <h1>color</h1> {% endblock %} page preview enter image description here The file directories, src -static -css -main.css -store -templates -store -main.html -store.html The problem is I cannot preview the customized background color of the body. Is the problem due to bootstrap, or my customized css attributes? Or is it the {% extend ...} is not working, or am I missing to add something in the settings.py. Just started learning Django, would be of great help if anyone make me clear the bug. -
Using Django JSONField in model
I am creating REST API's. django==3.2.2 djangorestframework==3.12.4 psycopg2==2.8.6 I am new to Django, python. I looking for a way to use the JSON field in the Django model. My model looks like below - class Question(BaseModel): .... other code... attributes = models.JSONField() Now I want the attributes to be a JSON, like below { "index": 0, "guid": "95161b18-75a8-46bf-bb1f-6d1e16e3d60b", "isActive": false, "latitude": -25.191983, "longitude": -123.930584, "tags": [ "esse", "sunt", "quis" ], "friends": [ { "id": 0, "name": "Contreras Weeks" }, { "id": 1, "name": "Dawn Lott" } ] } Should I create a new model, but creating a new model will make it add to migrations which I do not want. How to create a model for the above? -
Backend developer test
I received a backend developer test and I kind of don't know how to approach it. Can anyone give me some input. Please don't solve it just guide me a little bit. Can be done in any programming language Please implement a basic web server and meet the following requirements: • Each IP can only accept 60 requests per minute. • Display the current request amount on the homepage, and display "Error" if it exceeds the limit, for example, the 30th request in one minute 30 is displayed, and Error is displayed for the 61st request. • You can use any database, or you can design your own in-memory data structure, and explain the reason in the file. • Please attach the test. Thanks -
django rest : @api_view and @classmethod error
🚨 I desperately need @classmethod i am use this code: from rest_framework.response import Response class MyClass(): @classmethod @api_view(['GET', 'POST', 'PUT', 'DELETE']) def CRUD(cls, request, id=0): #..... return Response({}) urlpatterns = [ re_path(r'^user/(?:(?P<id>[1-9]+)/)?$', UserView.CRUD) ] get error: The 'request' argument must be an instance of 'django.http.HttpRequest', not 'builtins.type'. please help ; Thankful🙏🏻🙏🏻 -
How to Specify Django Database Schema?
I have 2 django projects that i want to use the same Postgres database, separated on different schemas. The way I've seen recommended to do this is by setting search_path in options & creating the schema in postgres (CREATE SCHEMA exampleschema). But, it doesn't seem to work. If I specify the search_path as "public" (the default), it can connect to that schema no problem. But when I try exampleschema & run migrate, I get the error: django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (no schema has been selected to create in the database settings look like this - DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS': { 'options': '-c search_path=exampleschema' }, 'NAME': 'example', 'USER': 'postgres', 'PASSWORD': os.environ['DB_PASSWORD'], 'HOST': 'db', 'PORT': '5432', }, } is there a permissions setting that I need to set for the schema in Postgres or something? -
DRF API schema TypeError: view() missing 1 required positional argument: 'request'
I was going through the docs on DRF schema and installed the packages pyyaml and uritemplate. I added the urls to my urls.py file. Later I pip installed coreapi following this tutorial url = [ ... path('docs/', include_docs_urls(title='BlogAPI')), path('openapi', get_schema_view( title="Your Project", description="API for all things …", version="1.0.0" ), name='openapi-schema'), I shows me the following error on login to the url Environment: Request Method: GET Request URL: http://127.0.0.1:8000/docs/ Django Version: 3.1.6 Python Version: 3.9.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'GisApplication.apps.GisapplicationConfig', 'users.apps.UsersConfig', 'crispy_forms', 'rest_framework', 'storages', 'django.contrib.gis'] Installed Middleware: ['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'] Traceback (most recent call last): File "D:\anaconda\envs\djangoEnv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\anaconda\envs\djangoEnv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\anaconda\envs\djangoEnv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "D:\anaconda\envs\djangoEnv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "D:\anaconda\envs\djangoEnv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "D:\anaconda\envs\djangoEnv\lib\site-packages\rest_framework\schemas\views.py", line 48, in handle_exception return super().handle_exception(exc) File "D:\anaconda\envs\djangoEnv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "D:\anaconda\envs\djangoEnv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "D:\anaconda\envs\djangoEnv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "D:\anaconda\envs\djangoEnv\lib\site-packages\rest_framework\schemas\views.py", line 37, in get schema = self.schema_generator.get_schema(request, self.public) File "D:\anaconda\envs\djangoEnv\lib\site-packages\rest_framework\schemas\coreapi.py", line 156, in get_schema … -
when passed a dictionary into jinja2 template single apostrophe(') is converted into "'"
JavaScript is throwing an error 'Uncaught Syntax Error: Unexpected token '&'' when debugged in Views.py I got he data with proper Apostrophes. def newEntry(request): assert isinstance(request, HttpRequest) i = 1 for x in lines: for line in x: cursor.execute("select distinct regionn FROM [XYZ].[dbo].[Errors] where [Linne] like '%" +line+ "%'") region[i] = cursor.fetchall() i = i+1 return render( request, 'app/newEntry.html', { 'title': 'New Entry', 'year':datetime.now().year, 'lines': lines, 'regions': region, } ) and here is my JS code var Regions= {{regions}} function changecat(value) { if (value.length == 0) document.getElementById("category").innerHTML = "<option>default option here</option>"; else { var catOptions = ""; for (categoryId in Regions[value]) { catOptions += "<option>" + categoryId+ "</option>"; } document.getElementById("category").innerHTML = catOptions; } } Thanks in advance, if this is not a best practice to carry data, suggest me some best process which fills my requirement -
Showing all the users who have set their country same as request.user
I am building a BlogApp and I am trying to show all the users which set their Countries similar to request.user. For Example : If user_1 is request.user and selected state choice Victoria and country Australia and then user_2 registered and set the same state Victoria and country Australia. So i want to show all the users that have set their Country and state same to request.user BUT When i access these types of users then It is just showing all users of same country BUT it is not showing of same state. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) country = models.CharField(max_length=30,null=True,blank=True) state = models.CharField(max_length=30,null=True,blank=True) views.py def show_user(request.user): show = Profile.objects.filter(country=request.user.profile) show_state = Profile.objects.filter(state=request.user.profile) context = {'show':show,'show_state':show_state} return render(request, 'show_user.html', context) When i try to access {{ show }} in template then it shows two user have set their country same to request.user BUT When i try to access {{ show_state }} in template it shows nothing. I have no idea, what am i doing wrong in accessing. Any help would be Appreciated. Thank You in Advance. Note :- I am using external library to show country and state choices in html. -
Celery task is not getting updated db records from Django-Channels
In my celery task I want to send an event to a Django-Channels group. The event should save the all the results to the database. The task has a success signal that gets the results and sends it to the group. This does not seem to work though... Why? #consumers.py @database_sync_to_async def save_to_db(game) Result.objects.create(game=game) class GameConsumer(AsyncWebsocketConsumer): ... async def save_result(self, event): await save_to_db(self.game) #tasks.py @shared_task(name="run_game") def run_game(): ... async_to_sync(channel_layer.group_send)( 'game', { 'type': 'save.result' } ) return(game) @task_success.connect def task_success_handler(sender=run_game, result=None, **kwargs): game_results = Game.objects.get(id=result.id).results.all() async_to_sync(channel_layer.group_send)( 'game', { 'type': 'end.game', 'data': game_results }