Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Newbie needs help understanding Docker Postgres django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres"
I am a newbie trying to follow this tutorial. https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/#postgres I succeeded in building the docker containers but got this error django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres". My question is why has authentication failed when the python and postgres containers env shows the correct user and password? And how can I solve the problem? I also tried poking around to find pg_hba.conf (because previous answers suggested editing it) but /etc/postgresql does not seem to exist for me. This is from my python container. # python Python 3.8.2 (default, Apr 23 2020, 14:32:57) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.environ.get("SQL_ENGINE") 'django.db.backends.postgresql' >>> os.environ.get("SQL_DATABASE") 'postgres' >>> os.environ.get("SQL_USER") 'postgres' >>> os.environ.get("SQL_PASSWORD") 'password123' >>> os.environ.get("SQL_HOST") 'db' >>> os.environ.get("SQL_PORT") '5432' This is from my postgres container. / # env HOSTNAME=6715b7624eba SHLVL=1 HOME=/root PG_VERSION=13.2 TERM=xterm POSTGRES_PASSWORD=password123 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin POSTGRES_USER=postgres LANG=en_US.utf8 PG_MAJOR=13 PG_SHA256=5fd7fcd08db86f5b2aed28fcfaf9ae0aca8e9428561ac547764c2a2b0f41adfc PWD=/ POSTGRES_DB=postgres PGDATA=/var/lib/postgresql/data / # ls bin lib root tmp dev media run usr docker-entrypoint-initdb.d mnt sbin var etc opt srv home proc sys / # cd etc /etc # ls alpine-release fstab hosts issue modules-load.d opt periodic resolv.conf shadow- sysctl.d apk group init.d logrotate.d motd os-release profile securetty shells terminfo conf.d … -
Salut j'aimerais savoir comment utiliser ImageField() pour enregistrer une image dans ma base de données. J'utilise Django 3 et python 3
picture = models.ImageField('') -
How did the [login.html] get the [school_name]
C:\Django-School-Management-System\templates\registration\login.html How did school_name get the value?? There no where to import the config. Config is here -
Unable to login via Facebook in live server using django alluth package
I tried to use django allauth package in my production server directly because in my localhost it says its not a secure connection everytime. But in my production server it gives the error saying Social Network Login Failure I have posted the code and screenshots below: My settings: 'allauth', 'allauth.account', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount', ACCOUNT_EMAIL_VERIFICATION = 'none' ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS =10 ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQURIED=True #ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 115 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400 # 1 day in seconds SOCIALACCOUNT_QUERY_EMAIL = ACCOUNT_EMAIL_REQUIRED SOCIALACCOUNT_EMAIL_REQUIRED = ACCOUNT_EMAIL_REQUIRED SOCIALACCOUNT_STORE_TOKENS=True LOGIN_REDIRECT_URL = '/' ACCOUNT_DEFAULT_HTTP_PROTOCOL = "https" SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'METHOD': 'oauth2', 'SCOPE': ['email', 'public_profile', 'user_friends'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'INIT_PARAMS': {'cookie': True}, 'FIELDS': [ 'id', 'email', 'name', # 'first_name', # 'last_name', # 'verified', # 'locale', # 'timezone', # 'link', # 'gender', # 'updated_time', ], 'EXCHANGE_TOKEN': True, 'LOCALE_FUNC': lambda request: 'en_US', 'VERIFIED_EMAIL': False, 'VERSION': 'v2.12', }, 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } } } My urls: path('accounts/',include('allauth.urls')), -
Django Search Functionality gives error Related Field got invalid lookup: icontains
I am getting a strange error in my search functionality: def search(request): query=request.GET['query'] messages = {} if len(query)>78: allPosts=Post.objects.none() else: allPostsTitle= Post.objects.filter(title__icontains=query) allPostsAuthor= Post.objects.filter(author__icontains=query) allPostsContent =Post.objects.filter(content__icontains=query) allPosts= allPostsTitle.union(allPostsContent, allPostsAuthor) if allPosts.count()==0: messages.warning(request, "No search results found. Please refine your query.") params={'allPosts': allPosts, 'query': query} return render(request, 'blog/search.html', params) Where is the problem? -
{user: ["This field is required."]} doesn't even work when hardcoded (DRF)
I've read through lots of similar topics but can't solve my current issue. I am trying to allow a user to update a list name, which is then POSTed via AJAX to a DRF API. However, I keep getting this error returned: {user: ["This field is required."]} I've tried many different things to overcome this including hardcoding a user in but it still doesn't work. Here is my view: class UpdateUserListViewSet(viewsets.ModelViewSet): serializer_class = UserListSerializer queryset = UserList.objects.all() def update(self, instance, validated_data): serializer_class = UserListSerializer if self.request.method == "POST": list_id = request.data.get('id') user = self.request.user.id list_name = request.data.get('list_name') data = {'user': user, 'list_name': list_name} serializer = serializer_class(data=data, partial=True) if serializer.is_valid(): serializer.save() return Response({'status' : 'ok'}, status=200) else: return Response({'error' : serializer.errors}, status=400) Here is the relevant serializer: class UserListSerializer(serializers.ModelSerializer): #this is what we worked on on October 1 class Meta: model = UserList fields = ['id', 'user', 'list_name'] Here is the model: class UserList(models.Model): list_name = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE) #is this okay? def __str__(self): return self.list_name -
docker-compose: can't access Django container from within Nuxt container
Both my backend (localhost:8000) and frontend (locahost:5000) containers spin up and are accessible through the browser, but I can't access the backend container from the frontend container. From within frontend: /usr/src/nuxt-app # curl http://localhost:8000 -v * Trying 127.0.0.1:8000... * TCP_NODELAY set * connect to 127.0.0.1 port 8000 failed: Connection refused * Trying ::1:8000... * TCP_NODELAY set * Immediate connect fail for ::1: Address not available * Trying ::1:8000... * TCP_NODELAY set * Immediate connect fail for ::1: Address not available * Failed to connect to localhost port 8000: Connection refused * Closing connection 0 curl: (7) Failed to connect to localhost port 8000: Connection refused My nuxt app (frontend) is using axios to call http://localhost:8000/preview/api/qc/. When the frontend starts up, I can see axios catching errorError: connect ECONNREFUSED 127.0.0.1:8000. In the console it says [HMR] connected though. If I make a change to index.vue, the frontend reloads and then in the console it displays: access to XMLHttpRequest at 'http://localhost:8000/preview/api/qc/' from origin 'http://localhost:5000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response. VM11:1 GET http://localhost:8000/preview/api/qc/ net::ERR_FAILED I have already setup django-cors-headers (included it in INSTALLED_APPS, and set ALLOWED_HOSTS = ['*'] and CORS_ALLOW_ALL_ORIGINS … -
Test SameSite and Secure cookies in Django Test client response
I have a Django 3.1.7 API. Until now I was adding SameSite and Secure cookies in the responses through a custom middleware before Django 3.1, depending on the user agent, with automated tests. Now that Django 3.1 can add those cookie keys itself, I removed the custom middleware and still want to test the presence of SameSite and Secure cookies in the responses. So I added the following constants in settings.py, as Django doc says: CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SAMESITE = 'None' SESSION_COOKIE_SAMESITE = 'None' But when I look at the content of the responses in my tests, I don't get any SameSite neither Secure cookie keys anymore. I printed the content of the cookies, and it's not there. Why? Here are my tests: agent_string = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.2227.0 Safari/537.36" from django.test import Client test_client = Client() res = test_client.get("/", HTTP_USER_AGENT=agent_string) print(res.cookies.items()) I also tried with the DRF test client just in case, with same result: agent_string = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.2227.0 Safari/537.36" from rest_framework.test import APIClient test_client = APIClient() res = test_client.get("/", HTTP_USER_AGENT=agent_string) print(res.cookies.items()) -
how to iterate over a html tag in jinja templat {django}
I want to iterate over an input tag value! like if the user gives input 6 then 6 input fields will be created! if he gives 10 then 10 input fields should be created! <input type="text" name="sub_count" > {% for x in sub_count %} { <input type="text"> } {% endfor %} What's wrong with it! help -
django.db.utils.DatabaseError: ORA-00933: SQL command not properly ended
I am trying to connect the remote oracle database. I have installed clients and added the path to LD_LIBRARY_PATH. The query and parameters generated are as follows. The query runs in psql, dbeaver. It only fails when running Django. SELECT "AUTHTOKEN_TOKEN"."KEY", "AUTHTOKEN_TOKEN"."USER_ID", "AUTHTOKEN_TOKEN"."CREATED", "AUTH_USER"."ID", "AUTH_USER"."PASSWORD", "AUTH_USER"."LAST_LOGIN", "AUTH_USER"."IS_SUPERUSER", "AUTH_USER"."USERNAME", "AUTH_USER"."FIRST_NAME", "AUTH_USER"."LAST_NAME", "AUTH_USER"."EMAIL", "AUTH_USER"."IS_STAFF", "AUTH_USER"."IS_ACTIVE", "AUTH_USER"."DATE_JOINED" FROM "AUTHTOKEN_TOKEN" INNER JOIN "AUTH_USER" ON ("AUTHTOKEN_TOKEN"."USER_ID" = "AUTH_USER"."ID") WHERE "AUTHTOKEN_TOKEN"."KEY" = :arg0 FETCH FIRST 21 ROWS ONLY {':arg0': <django.db.backends.oracle.base.OracleParam object at 0x10b8497d0>} and the error I am seeing is Traceback (most recent call last): File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/rest_framework/views.py", line 497, in dispatch self.initial(request, *args, **kwargs) File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/rest_framework/views.py", line 414, in initial self.perform_authentication(request) File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/rest_framework/views.py", line 324, in perform_authentication request.user File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/rest_framework/request.py", line 227, in user self._authenticate() File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/rest_framework/request.py", line 380, in _authenticate user_auth_tuple = authenticator.authenticate(self) File "/Users/kishorpawar/.virtualenvs/pl/lib/python3.7/site-packages/rest_framework/authentication.py", line 196, in authenticate return self.authenticate_credentials(token) File … -
How to restrict view in Django based on permission(s) provided to the user?
I have a Django project wherein I want to show the user the data based on the following options. There are three different listings for a user (show_own_data. show_own_users_data, show_all_users_data) Basically the user(s) will have read permission in this view and the data will be shown according to the choices.(the data is for the modules and sub-modules the user has purchased) if choice = show_own_data, the user can only see his data for various modules and sub modules if choice = show_own_users_data, the user can see the data's for the user's created by the user for various modules and sub modules if choice = show_all_users_data, the user can see all user's data for various modules and sub modules #Permissions.py class Permissions(models.Model): perm_show_own_data = models.BooleanField(default=False) perm_show_own_users_data = models.BooleanField(default=False) perm_show_all_data = models.BooleanField(default=False) #check_permissions.py def has_perm_show_own_users_data(self, show_own_users_data: dict): perm_show_own_users_data = False if self.permissions: qs = Permissions.objects.filter(**show_own_users_data, user=self) if qs.exists(): perm_show_own_users_data = True return perm_show_own_users_data i don't know if the steps are correct or even how to proceed further. Can anyone help please. Can anyone also explain what is show_own_users_data: dict in function has_perm_show_own_users_data(self, show_own_users_data: dict) -
When I log in to 'contact-profile.html' it does not show me the data stored in admin do not know where my mistake is?
fjjndjhvs dabjhdnbsaujhdhjs dshgsbdjnmgaB ``` (models.py) from django.db import models # Create your models here. class contact(models.Model): full_name = models.CharField(max_length= 500) relationship = models.CharField(max_length=50) email = models.EmailField(max_length=254) phone_number = models.CharField(max_length=20) address = models.CharField(max_length=100) def __str__(self): return self.full_name ``` bjhfgdfjkmdbskjfmhdsjkmhas ``` (views.py) from django.shortcuts import render, redirect from .models import contact from django.shortcuts import render, redirect from .models import contact # Create your views here. def index(request): contacts = contact.objects.all() return render(request, 'index.html', {'contacts': contacts}) def addContact(request): if request.method == 'POST': new_contact = contact( full_name = request.POST['fullname'], relationship = request.POST['relationship'], email = request.POST['email'], phone_number = request.POST['phone-number'], address = request.POST['address'], ) new_contact.save() return redirect('/') return render(request, 'new.html' ) def ContactProfile(request, pk): Contact = contact.objects.get(id=pk) return render(request, 'contact-profile.html', {'contact': contact}) def EditContact(request, pk): Contact = contact.objects.get(id=pk) return render(request, 'edit.html', {'contact': contact}) ``` bdjhsnbdjhnmgbsahjmdgbsuj ``` (urls.py) from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.index, name ='index'), path('add-contact/', views.addContact, name='add-contact'), path('profile/<str:pk>', views.ContactProfile, name='profile'), path('edit-contact/<str:pk>', views.EditContact, name='edit-contact'), ] ``` (contact-profile.html) {% load static %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static 'style-profile.css' %}"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Inter&display=swap" rel="stylesheet"> <script src="https://kit.fontawesome.com/6b20b1c14d.js" crossorigin="anonymous"></script> <title>Contact Profile</title> </head> <body> <div class="container"> <header class="hero"> … -
Is there any way to retrive choice field text using sql query?
I am writing a script in python to retrieve data from the Postgres database. And, I'm getting data of choice field as an integer value, Is there any way to retrieve text format of choice field using SQL query only. -
Django class-based view to return HttpResponse such as HttpResponseBadRequest
I have a custom Django view class that inherits from the generic DetailView. The generic DetailView class sequentially calls its methods get_queryset, get_object, and others to generate an object to pass for a Django template. Moreover, the generic DetailView class raises Http404 exception within these methods to deal with erroneous situations #. except queryset.model.DoesNotExist: raise Http404(_("No %(verbose_name)s found matching the query") % {'verbose_name': queryset.model._meta.verbose_name}) What I am trying to do is simple: I want to return other HTTP status codes to the client if an error is found within these methods. However, because Http404 is the only Django HttpResponse that has a form of exception, it seems like this cannot be achieved easily. Because HttpResponse is not an exception, I have to return it instead of raising it. Therefore, the customized method becomes the following form. def get_object(self, queryset=None): ... try: # Get the single item from the filtered queryset obj = queryset.get() except queryset.model.DoesNotExist: return HttpResponseBadRequest("Bad request.") However, above code does not send HttpResponseBadRequest to the client. Instead, it returns HttpResponseBadRequest as an object for a Django template. The client gets 200 status code with an invalid object for the template. The only possible solution to think is writing … -
django cors headers giving 'WSGIRequest' object has no attribute 'host' error
Hi I am trying to use the built in signal to check if the host exists in the database but i get this following error 'WSGIRequest' object has no attribute 'host' My code def cors_allow_sites(sender, request, **kwargs): return ConsumerURLModel.objects.filter(url=request.host).exists() check_request_enabled.connect(cors_allow_sites) My middleware MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] -
Error installing libraries on heroku django app
I am trying to deploy django app on heroku and error happends while heroku installs from requirements.txt: requests==2.25.1 asgiref==3.3.4 beautifulsoup4==4.9.3 certifi==2020.12.5 chardet==4.0.0 Django==3.2 djangorestframework==3.12.4 idna==2.10 pytz==2021.1 soupsieve==2.2.1 sqlparse==0.4.1 urllib3==1.26.4 2captcha-python==1.1.0 The last library needs requests to be installed. It works perfectly on local machine if i just put requests before 2captcha, but on heroku it returns erorr ModuleNotFoundError: No module named 'requests' I tried switch places for requests and 2captcha but it didn't help -
Show ISO date values in string form
So I was trying to get what months that an insurer filed a claim. However, the values were in ISO Form. I was trying to show it in string form. Instead of showing 2021-01-01, show January; 2021-01-02, show February Here's the sample get data Data in image form { "Month": [ "2021-04-01T00:00:00+08:00", "2021-02-01T00:00:00+08:00", "2021-03-01T00:00:00+08:00" ], "Claim(s)": { "": 18, "Bank Transfer": 5, "CAR": 1, "home": 5, "Credit": 7, "Energy": 1, "health": 38, "\"health\"": 5 } } I'd like to change the ISO date form into string form instead. Here is my code in Views class GetClaimsCompare_year(APIView): def get_claim_count(self, claims_data, claim_type): claims_count = claims_data.filter(claim_type = claim_type).count() return claims_count def get_claims_type(self, claim_per_month): return claim_per_month.claim_type def get(self, request): today = datetime.now() claims_data = Claims.objects.filter(modified_at__year =today.year) claim_per_month = claims_data.annotate(month = TruncMonth('modified_at')).values('month').annotate(claim_type=Count('id')) labels = [] claims_type = list(set(map(self.get_claims_type, claims_data))) final = {} for claims in claim_per_month: labels.append(claims['month']) for claim_type in claims_type: final[claim_type] = self.get_claim_count(claims_data, claim_type) context = { 'Month':labels, 'Claim(s)':final } return Response(context) -
How to send request with CSRF cookie using fetch in React
I send post request to Django api server but I don't know how to send csrf cookie. sending the post request from React . upload.js import Cookies from 'universal-cookie'; const cookies = new Cookies(); cookies.set('csrftoken', 'sth', { path: '/' }); const fileUpload = (e) =>{ e.preventDefault(); const fileForm = document.getElementById.fileForm; const formData = new FormData(fileForm); fetch('http://192.168.0.1:8000/upload/', { method:'POST', headers: { 'content-type': 'multipart/form-data', 'X-CSRFToken':'sth' }, credentials: 'same-origin', body:formData }) ... } Django Response Reason given for failure: CSRF cookie not set. -
How to solve could not convert string to float error in Django?
I am doing currency conversion in my Django project. Users choose the currency and enter the credit_limit, and I convert the input entered by the user into a float in the backend and convert it according to the entered currency. There is no problem when the user enters numbers such as 10, 20 in the credit limit field, but this error appears when numbers such as 1000000 are entered. how can I solve this? ValueError at /customer could not convert string to float: '1,000,000.00' 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) newCustomer.credit_limit = float_str newCustomer.save() return redirect('user:customer_list') else: form = form_class() return render(request, 'customer.html', {'form': form}) models.py class Customer(models.Model): ... CURRENCIES = [ ('USD', 'USD'), ('EUR', 'EUR'), ('GBP', 'GBP'), ('CAD', 'CAD'), ...] customer_name = models.CharField(max_length=100) ... currency_choice = models.TextField(max_length=50, default='Select', choices=CURRENCIES) credit_limit = models.FloatField(default=0, null=True) usd_credit_limit … -
CharField not holding formatting
I have a form that stores a Field with a Textarea widget to a CharField, I would like for it to not clean out line breaks and other formatting information such as tabs and multiple spaces. Is there a way to go about doing this? special_instructions = forms.CharField( label = "Special Instructions", widget=forms.Textarea( attrs={ 'id': 'textarea-ed95', 'class':'u-border-1 u-border-grey-30 u-input u-input-rectangle', 'placeholder':'Special Instructions' } ) ) -
Kendo UI filter "contains/doesnotcontain" filters working OK but other filters not working with Django objects
Kendo UI filter "contains/doesnotcontain" filters working OK but other filters not working with Django objects Hello, I have a html table declared and populate the cell values() using Django object as mentioned below. <div class=""> {% if object_list %} <table id="gridentries" class="table table-striped table-border"> <thead class="thead-light" role="rowgroup"> <tr role="row"> <th style="width: 19%">{% trans 'Field1_hdr' %}</th> <th style="width: 19%">{% trans 'Field2_hdr' %}</th> </tr> </thead> <tbody role="rowgroup"> {% for entry in object_list %} <tr> <td> {{ entry.field1 }} </td> <td> {{ entry.field2 }} </td> {% endfor %} </tbody> </table> . . Now I have a Kendo grid declared where I am referring above table structure and defined all filters possible. Filters "contains/doesnotcontain" works perfectly OK, but other filters like "startswith"(for eg) is not working OK for the grid. I was thinking django object entries {{ entry.field1 }} is not exactly treated as a string in HTML(might be some unknown characters are prefixed/suffixed and hence "startswith") and hence tried to convert to an HTML var (and HTML strings) but that didn't work either. Can anyone please help? Where am I going wrong? <script> $(document).ready(function () { $("#gridentries").kendoGrid({ height: 1500, sortable: true, pageable: { pageSize: 20 }, filterable: { messages: { and: "{% trans … -
pickle.load() sometimes can't working in my environment(ubuntu16.04,python3.5)
Today I start a Django project which can run properly yesterday. But now, it gets a problem. When I debug with Pycharm, I find that after pickle.loads(a_bytes) a return is still a_bytes. not a string. -
Django channels database access method returns coroutine object
I'm trying to access some data in the database in my consumers.py file like this: @database_sync_to_async async def get_project(self, email): client = await Account.objects.get(email=email) return await Project.objects.filter(client=client).last() And if I print what this method returns I get this: <coroutine object SyncToAsync.__call__ at 0x7fa6129eaf40> So there for when I try to send this object back to the channels_layer group I get this error: TypeError: Object of type coroutine is not JSON serializable Even if I try to access one of the children of this object, for example description I'll get: AttributeError: 'coroutine' object has no attribute 'description' So how can I access this object from database? -
How do I pass an instance to a view?
I'm not able to understand the complaint that the system is returning. Here is the view for the system def AddMarksView(request): class_name = request.session.get('class_name') subject = Subject.objects.filter(name='Maths') exam = Exam.objects.filter(name='Endterm') students = Students.objects.filter(school=request.user.school,klass__name = class_name,stream__name='South') if request.method == 'POST': for student in students: marks = int(request.POST['marks']) marks_object = Marks.objects.create(student=student,marks=marks,subject=subject,exam=exam) else: return render(request,'feed_marks.html') return redirect('search_m') The error returned is Cannot assign "<QuerySet [<Exam: Endterm>]>": "Marks.exam" must be a "Exam" instance. The model for Marks odel is class Marks(models.Model): exam = models.ForeignKey(Exam,on_delete=models.SET_NULL,null=True,blank=True) subject = models.ForeignKey(Subject,on_delete=models.SET_NULL,null=True,blank=True) student = models.ForeignKey(Students,on_delete=models.SET_NULL,null=True,blank=True) marks = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100),] ,null=True,blank=True) How can I format the view so tha it returns no error? -
How to calculate the points based on the price of the total purchase in django models?
I am trying to create points earned by users after buying something and placed an order from the frontend. Also, I need to save the points on the database because users later use that points to buy something. The points system looks like this. Point System for % of the total purchase Upto 10,000 = 1 % 10k to 50k =2.75% 50K plus = 5% I haven't saved the price in DB, I just used it as a property so that it remains safe and cant be changed by anyone. It calculates whenever the get or post API is called. class Order(models.Model): ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) @property def total_price(self): # abc = sum([_.price for _ in self.order_items.all()]) # print(abc) return sum([_.price for _ in self.order_items.all()]) def __str__(self): return self.user.email class Meta: verbose_name_plural = "Orders" ordering = ('-id',) class OrderItem(models.Model): orderItem_ID = models.CharField(max_length=12, editable=False, default=id_generator) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants, on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) order_item_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') @property …