Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to read coordinate from the DB and map a pointer on the map using django
As a newbie with python, I am thinking of doing a project, where I have a table of e.g shops, with their names, longitude, latitude, and shop manager. I want to design a django project where the coordinates (longitude, latitude) will be used to place a pointer on the map to indicate the location on the map, and if hovered, it will show the shop details. I can go as far as if clicked on, the will display the shop page with details, etc. -
Django restframework search function doesn't return the desired output?
I want to use Django search feature while trying to implement it. The implemented code doesn't work View.py file class SearchView(generics.ListAPIView): permission_classes = [IsAuthenticated] queryset = BlogDetails.objects.all() search_fields = ["blog_title"] filter_backend = [filters.SearchFilter] serializer_class = SearchSerializer Serializer.py class SearchSerializer(serializers.ModelSerializer): class Meta: model = BlogDetails fields = ("blog_title","blog_author") So I made a request like this localhost:8000/search/search-blog/?search=jane But it displays all the blogs that are in database and not the result which has jane in its title and I have added django-filters in INSTALLED_APPS But still it doesn't work! -
django csrf authentication error when trying to connect react
I am trying to build the backend with django and frontend with react. I stumbled accross a 403 error when I try to login an existing user. Everything compiles but login always results in fail. When I inspect the network tab I see there is a 403 error. when I access correct auth info In the error page it says that I should add the csrf template tag before my input tags but I can't add them because react doesn't recognize it. The error is gone if I don't use react but I have to use it. What are my options if I want to implement this in react? App.js: import { BrowserRouter as Router, Switch } from "react-router-dom" import Auth, { useAuthActions } from "use-eazy-auth" import { AuthRoute, GuestRoute } from "use-eazy-auth/routes" import { ConfigureRj } from "react-rocketjump" import { map } from "rxjs/operators" import { ajax } from "rxjs/ajax" import Login from "./pages/Login" import AddressBook from "./pages/AddressBook" const login = (credentials = {}) => ajax({ url: "/core/token/", method: "POST", headers: { "Content-Type": "application/json", }, body: credentials, }).pipe( map(({ response }) => ({ accessToken: response.access, refreshToken: response.refresh, })) ) const me = token => ajax.getJSON("/core/me/", { Authorization: `Bearer ${token}`, … -
Is there a way to add django models dynamically?
I am creating models in Django using an array of strings. E.g. let there be an array of strings named arr arr = ['one','two','three','four'] Then I have to create four models in django named FooOne, FooTwo, FooThree, FooFour. All of them have the same fields. Is there any way where I wont have to create these models manually, i.e., I just update the array of strings and run a script and the models will be created for me automatically ? I am using MySQL as the database. -
Django Rest Framework and the Frontend
I want to use Django Rest Framework as an API and am looking for a way to "couple" the frontend / HTML/CSS/JS to it. To put it in perspective, I am used to the way Django "usually" does it, by naming HTML templates and 'rendering' them when going to a particular URL. Now, with DRF, it appears that this functionality has fallen away and everywhere I look it's just "react.js or vue.js" as the answers to consume the API. What are my options for the front end? Can I not just do it all within the 'usual' Django framework, simply, as it was done before. And why do no resources talk about this? Thanks, let me know if you require further info. -
i am gettin an error "[Errno 5] Input/output error" while running an api on django
Django API Code: def post(self,request)-> JsonResponse: try: self.email = request.data['email'] self.mobile = request.data['mobile'] self.password = request.data['password'] except Exception as e: return JsonResponse(create_failure('400',f"invalid payload {e}","fail")) try: res = {} jwt_token = '' if self.email: password = Customer.objects.get(email=self.email).password username = Customer.objects.get(email=self.email).username print(password) if check_password(self.password,password) : jwt_token = make_jwt_token({'username':username}) else: return JsonResponse(create_failure('500',f"Invalid password","fail")) elif self.mobile: password = Customer.objects.get(mobile=self.mobile).password username = Customer.objects.get(mobile=self.mobile).username if check_password( password,self.password) : jwt_token = make_jwt_token({'username':username}) else: return JsonResponse(create_failure('500',f"Invalid password","fail")) res['token'] = jwt_token except Exception as e: return JsonResponse(create_failure('400',f"error in verifying the password {e}","fail")) return JsonResponse(create_success('User Verified',res)) Error while running it on the postman { "StatusCode": "400", "Message": "error in verifying the password [Errno 5] Input/output error", "ReplyCode": "fail", "Data": [] } Above code is working fine on the local machine, but it creates this error when I deploy it to the server. I am using cpanel for the hosting which uses CentOS -
How to replace the in-built Django admin side pages with your own template pages?
enter image description here Thanks -
ASCII codec can't encode character and can only concat str
I'm trying to send a request in Django: res = self.client.get("/test/", {"var":"test"+u"\u200B".encode('utf-8')}) However, I keep getting the error message: can only concatenate str (not "bytes") to str When I remove .encode('utf-8') I get: UnicodeEncodeError: 'ascii' codec can't encode character '\u200b' in position 3: ordinal not in range(128) Any ideas? -
Django values function rename key of dict
In my databases design id | key | value 1 | ABC | 123 and what i trying to do data.objects.filter(id__in=list).values('key', 'value') and it return [{'key': 'ABC', 'value': '123'}, ... ] but instead of that, i want to do [{'ABC': '123', ... ] Noted: The result list will be 800k rows, because of the performance issues, i try to avoid using loop and want to use django feature to make it like this. -
Infinite scroll not re-rendering with cache after removing updateQuery
Frameworks: Apollo / GraphQL / Django Scenario: I am using useQuery from apollo/client to fetch data. I have an infinite scroll created to listen for the scroll after which fetchMore is called. I can update the cache properly with updateQuery, but this is going to be deprecated as I get this error: react_devtools_backend.js:2560 The updateQuery callback for fetchMore is deprecated, and will be removed in the next major version of Apollo Client. Here is the working code to fetch and update the cache on each scroll: const handleGetMore = async () => { console.log("fetch"); if (!pending) { try { pending = true; await fetchMore({ variables: { isGm: true, offset: data?.getUsers?.length, limit: 12, }, updateQuery: (prev, { fetchMoreResult }) => { if (!fetchMoreResult) return prev; return Object.assign({}, prev, { getUsers: [...prev.getUsers, ...fetchMoreResult.getUsers], }); }, }); pending = false; } catch (error) { console.log("handleGetMore Error:", error); } } }; So, I updated my cache, as that seems to be the method going forward, to look like this: import { InMemoryCache } from "@apollo/client"; import { offsetLimitPagination } from "@apollo/client/utilities"; export const cache = new InMemoryCache({ typePolicies: { getUsers: { fields: { getUsers: offsetLimitPagination(), }, }, }, }); Problem: The UI does not … -
Can django authentication work with horizontal scaling?
I heard that session based authentication are not horizontally scalable. You somehow need a central system which saves the session. Is this same with django's default authentication system? There are other authentication methods too, like JWT (Which can easily scale horizontally). The problem with JWT is that they have more security risk than a standard authentication system. Can django's default authentication work without any problem in a multi server setup which has a load balancer distributing the load? -
How to handle error exception in serializer create()?
This question is duplicate from this DRF - How to handle exception on serializer create()? but the difference is, I add another task inside create, here is what I mean class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) def create(self, validated_data): user = UserModel.objects.create_user( username=validated_data['username'], password=validated_data['password'], ) data = {"success": False} try: cursor = connection.cursor() cursor.execute("INSERT INTO data_register (name, telp,username) VALUES ('" + self.initial_data["name"]+"','" + self.initial_data["telp"]+"','" + self.initial_data["username"]+"')") return user except Exception as e: data.update({"Error": str(e), "success": False}) return JsonResponse(data) class Meta: model = UserModel fields = ("username", "password") is there a way to catch the error when inserting data in data_register table ? I have tried the code above but I still get this result instead of json <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"> <title>TypeError at /create/user/</title> <style type="text/css"> html * { padding: 0; margin: 0; ..... -
Django Channels: group_send() getting delayed while sending to active window when handling multiple websocket consumers
Background: I'm working on a chat application on my local (development) server. Python 3.9.5, Django 3.2, Channels 3.0.3. Each user can see an "all messages" section on the page, containing messages from all users, and a "my messages" section, containing only his own messages. Goal: All messages should be sent to all users, and each user's messages should be separately sent only to him/her. If the user is logged in via multiple browser tabs/ devices (this scenario is supposed to be handled by Channels as per the docs here), and the user sends a message from one window, it needs to immediately send back (echo) the message to all his windows, including the window where the message was sent from. For this, I'm adding each connection to a group when it is first opened. Consumers.py async def websocket_connect(self, event): await self.send({ "type": "websocket.accept" }) await self.channel_layer.group_add("master", self.channel_name) user = self.scope['user'] user_group = "user_" + str(user.id) if user.is_authenticated: await self.channel_layer.group_add(user_group, self.channel_name) As you can see, the master group is for all users, and the user_group is for all connections of this particular user. Further: async def websocket_receive(self, event): user = self.scope['user'] user_group = "user_" + str(user.id) ....some code... await self.channel_layer.group_send( "master",{ … -
Querying related models that has foreign key to model in question (in one optimized query)
I got the following models. class Person(models.Model): name = models.CharField(max_length=200) class PhoneNumber(models.Model): person = models.ForeignKey(Person) number = models.CharField(max_length=200) class Email(models.Model): person = models.ForeignKey(Person) email = models.CharField(max_length=200) class WebSite(models.Model): person = models.ForeignKey(Person) url = models. URLField(max_length=200) I want to query all the models from already obtained Person model since this should be my start point. I can do something like; person = Person.objects.get(id=1) phones = PhoneNumber.objects.filter(person=person) emails = Email.objects.filter(person=person) website = WebSite.objects.filter(person=person) # ... However, the snippet above would hit the DB four times and I don't want that at all. Is there any way to make a query like the one below to hit the DB once (after person is already queried, which would be two in total at most)? query = Person.objects.get(id=1).getPhoneNumber(filters).getEmails(filters).getWebSites(filters) As you know prefetch_related also results in hitting DB more than once. I don't wanna use select_related since I would need to use other models to get to Person model, which actually will have no difference when it comes to how many times it would hit to the DB since I got multiple models. I am struggling to make a very performant query with the task above. Any help is much appreciated! -
Json data to CSV format using Python
I have JSON data I want to convert to a CSV file. How can I do this with Python? Below, is the json structure. { "data": [ { "matter_id": 1, "billing_clientId": 1, "billing_contactID": 1, "branch_code": "8032FHDSL", "category": "sadsaddda", } ] } what i tried below, but it's throw me ValueError: "Invalid file path or buffer object type: <class 'collections.OrderedDict'> " for record in serializer.data: import pandas as pd import json df = pd.read_json(record) print('df----->', df) df.to_csv("/home/satyajitbarik/test.csv", index = None) -
`coreapi` must be installed for schema support
I am trying to generate swagger docs using the drf_yasg and it was working fine but now its not. It's giving me error and I can not find solution for it. Any idea why am I getting this error ? Request Method: GET Request URL: http://0.0.0.0:8007/doc/ Django Version: 3.2.4 Python Version: 3.9.5 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.staticfiles', 'rest_framework', 'drf_yasg', 'promotions', 'vendor', 'settings'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'includes.common.middlewares.identity.IdentityMiddleware', 'includes.common.middlewares.timezone.TimezoneMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/usr/local/lib/python3.9/site-packages/drf_yasg/views.py", line 92, in get generator = self.generator_class(info, version, url, patterns=[]) File "/usr/local/lib/python3.9/site-packages/drf_yasg/generators.py", line 183, in __init__ self._gen = SchemaGenerator(info.title, url, info.get('description', ''), patterns, urlconf) File "/usr/local/lib/python3.9/site-packages/rest_framework/schemas/coreapi.py", line 120, in __init__ assert coreapi, '`coreapi` must be installed for schema support.' Exception Type: AssertionError at /doc/ Exception Value: `coreapi` must … -
Getting errors when launching Elastic Beanstalk instance in AWS for Django app
I'm using Python 3.9.5 for my Django app and I am trying to deploy it on AWS in Elastic Beanstalk. The platform I chose was AWS Linux 2 with Python 3.8. When I try to do an eb create, I get this stacktrace error: ---------------------------------------- /var/log/eb-engine.log ---------------------------------------- cmd_obj.run() File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/setuptools/command/build_ext.py", line 79, in run _build_ext.run(self) File "/usr/lib64/python3.8/distutils/command/build_ext.py", line 340, in run self.build_extensions() File "/usr/lib64/python3.8/distutils/command/build_ext.py", line 449, in build_extensions self._build_extensions_serial() File "/usr/lib64/python3.8/distutils/command/build_ext.py", line 474, in _build_extensions_serial self.build_extension(ext) File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/setuptools/command/build_ext.py", line 196, in build_extension _build_ext.build_extension(self, ext) File "/usr/lib64/python3.8/distutils/command/build_ext.py", line 528, in build_extension objects = self.compiler.compile(sources, File "/usr/lib64/python3.8/distutils/ccompiler.py", line 574, in compile self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) File "/usr/lib64/python3.8/distutils/unixccompiler.py", line 129, in _compile raise CompileError(msg) distutils.errors.CompileError: command 'gcc' failed with exit status 1 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-v7gtd0uf/cld2-cffi_20eacbc571034a60bc5a47d71b1737a7/setup.py", line 154, in <module> setup( File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/setuptools/__init__.py", line 153, in setup return distutils.core.setup(**attrs) File "/usr/lib64/python3.8/distutils/core.py", line 148, in setup dist.run_commands() File "/usr/lib64/python3.8/distutils/dist.py", line 966, in run_commands self.run_command(cmd) File "/usr/lib64/python3.8/distutils/dist.py", line 985, in run_command cmd_obj.run() File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/setuptools/command/egg_info.py", line 299, in run self.find_sources() File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/setuptools/command/egg_info.py", line 306, in find_sources mm.run() File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/setuptools/command/egg_info.py", line 541, in run self.add_defaults() File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/setuptools/command/egg_info.py", … -
awsebcli 'SyntaxError- no encoding declared' in terminal upon executing any eb command
I finished django project and during deployment run into error- after installing awsebcli package I try to run eb commands in terminal but get this error: File "C:\Users\Bartski\AppData\Local\Programs\Python\Python37\Scripts\eb.exe", line 1 SyntaxError: Non-UTF-8 code starting with '\x90' in file C:\Users\Bartski\AppData\Local\Programs\Python\Python37\Scripts\eb.exe on line 1, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details It shows the same error no matter what eb command I try to run. awsebcli installs only exe version so I am not able to change the encoding manually. I tried many solutions given to similar problems but none of them worked so far. Any ideas how can I make it work? -
django.db.utils.IntegrityError: (1062, "Duplicate entry '1' for key 'user profile.PRIMARY'")
I am very new to Django, creating rest API for my android application In my signup form I am taking parameter like email, password, firstname, lastname, contact etc... Every time new user signup, user profile data will also created based on that specific user id and those user id will should be unique in both the tables. When I am trying to signup, facing the below issue : django.db.utils.IntegrityError: (1062, "Duplicate entry '1' for key 'user profile.PRIMARY'") models.py from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_delete, post_save from django.dispatch import receiver from django.utils.timezone import now from django.conf import settings import uuid class UserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError('User must have an email address') user = self.model( email = self.email, ) user.set_password(password) user.save() return user class User(AbstractBaseUser): objects = UserManager() email = models.EmailField(unique=True, db_index=True) is_active = models.BooleanField('active', default=True) is_admin = models.BooleanField('admin', default=False) USERNAME_FIELD = 'email' ordering = ('id',) def is_staff(self): return self.is_admin def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True def get_short_name(self): return self.email def get_full_name(self): return self.email def __unicode__(self): return self.email class Meta: db_table = 'user' class UserProfile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, … -
Trying to learn javascript integration in Django
I am trying to learn javascript so that I can improve my Django application. I'm trying to vary images with a javascript function based on whether the URL link exists or not, but it's not working: Here's my javascript function: // Creates an object which can read files from the server var reader = new XMLHttpRequest(); var checkFor = "https://res.cloudinary.com/.../{{ object.id }}.png"; // Opens the file and specifies the method (get) // Asynchronous is true reader.open('get', checkFor, true); //check each time the ready state changes //to see if the object is ready reader.onreadystatechange = checkReadyState; function checkReadyState() { if (reader.readyState === 4) { //check to see whether request for the file failed or succeeded if ((reader.status == 200) || (reader.status == 0)) { //page exists -- redirect to the checked //checked for page document.location.href = checkFor; } else { var checkFor = "https://res.cloudinary.com/.../{{ object.system }}.png" return checkFor } }//end of if (reader.readyState === 4) }// end of checkReadyState() // Sends the request for the file data to the server // Use null for "get" mode reader.send(null); Then I try to call 'checkFor in my HTML template: <img src="checkFor"class="mx-auto" width="250px" onerror='this.onerror = null; this.src="https://res.cloudinary.com/.../image.svg"'/> I just get the default image, when … -
Blending image with background in HTML
In the following HTML document, the Microsoft logo does not blend with the background image. Does anyone know how you can blend the logo with the background image or remove the logo's background colour? I have tried using the command mix-media-mode: multiply but the image still did not blend properly. Thank you for your help. <!DOCTYPE html> <html lang="en"> <head> <style> body { background-image: url('https://i.pinimg.com/564x/09/01/f0/0901f088d78988a5b6bc66af7cfbfec8.jpg'); background-repeat: no-repeat; background-attachment: fixed; background-size: cover; } </style> </head> <body> <img src= "https://i.pinimg.com/564x/09/05/85/090585401505f54e69a1a5e218759171.jpg" height="35px" alt=""> </body> </html> -
(Stuck!) Django operational error: table "accounts_profile" already exists
Long story short. I tried to add a custom user model to my existing project and realized too late that it wouldn't work well as I already started my project. Then I deleted the migrations, all the customusermodel related codes and re ran makemigrations and migrate. Nothing wrong showed up at this point. Then I started following a tutorial to create a profile model to link to the default User model and everything was fine until I wanted to create a new superuser and django showed this error: django.db.utils.OperationalError: no such table: auth_user. Then, I saw similar errors online and and followed one of the solutions which was to fake migrate the app (accounts for me) and then re run migrations. So I did that but then this error shows up when I try to run Python manage.py migrate: django.db.utils.OperationalError: table "accounts_profile" already exists. Today, I have ventured into far too much unknown territory of django and now I am in a mess which I have no idea how to solve and so I need help. I would not like to delete my database as it contains existing data and the website is also live. What do you guys recommend … -
how to print content inside UserSerializer type - django rest framework
Hi I am trying to create user register using django rest frame work. So far I have been following this link https://stackoverflow.com/a/29391122/13240914, and I am still new in django, the thing that I would like to ask is.. is there a way to print content inside UserSerializer type.. here is part of the code class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) def create(self, validated_data): print(self) print(self.data) user = UserModel.objects.create_user( username=validated_data['username'], password=validated_data['password'], ) return user Here is the result when I print self: UserSerializer(context={'request': <rest_framework.request.Request: POST '/create/user/'>, 'format': None, 'view': <face_detector.views.CreateUserView object>}, data={'username': 'hello', 'password': 'hello123456'}): username = CharField(help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, validators=[<django.contrib.auth.validators.UnicodeUsernameValidator object>, <UniqueValidator(queryset=User.objects.all())>]) password = CharField(write_only=True) and when I print print(self.data) I only get {'username': 'hello'} so, what I would like to print is data={'username': 'hello', 'password': 'hello123456'} -
How to show a form when you click a button in django
I am creating a blog website using django. I am implementing the feature to comment on blogs with a form, and it works. The only thing is that, I want there to be a button Add a comment, and only when the user clicks on the button it will show the comment form. The best example I can give is StackOverflow and how it's commenting works. Thank You! -
The view soldagem.views.update_ieis didn't return an HttpResponse object. It returned None instead
I am getting this error when I try to instantiate an object. I use redirect and I don't understand why this one is not returning. view.py This method works in other views. from django.shortcuts import render, redirect def create_ieis(request): form_ieis = IEISForm(request.POST or None) if form_ieis.is_valid(): form_ieis.save() return redirect('soldagem:ieis') def form_ieis(request, pk): data = {} data['db'] = IEIS.objects.get(pk=pk) data['form_ieis'] = IEISForm(instance=data['db']) return render(request, 'soldagem/form.html', data) models.py Here I have FK for other apps. I don't think this is why. class IEIS (models.Model): nome = models.CharField (max_length=25,null=False, blank=False) especificacao = models.CharField (max_length=20,null=True, blank=True, unique=False) espec_material = models.ForeignKey (EspecMaterial, on_delete=models.CASCADE) diametro1 = models.ForeignKey (Diametros,related_name='diametro_nps1', on_delete=models.CASCADE) FNUMBER_CHOICES = ( (1, '1 a 5'), (2, '1 e 4 '), (11, '11') ) fnumber = models.CharField(max_length=10, choices=FNUMBER_CHOICES) us_tp = models.PositiveIntegerField (null=True, blank=True) rx_tp = models.PositiveIntegerField (null=True, blank=True) dz_tp = models.PositiveIntegerField (null=True, blank=True) class Meta: ordering = ['nome'] verbose_name = 'IEIS' verbose_name_plural = 'IEISs' def __str__(self): return str (self.nome)``` **form.html** <form name="form_ieis" id="form_ieis" action="{% if db %}/update_ieis/{{db.id}}/{%else%}/create_ieis/{% endif %}" method="post"> {% csrf_token %} {{form_ieis.as_p}} <input type="submit" class="btn btn-success" value="Salvar"> </form> Thank you for any attention.