Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle all pip command and ignore pip cache in windows?
Hello developer community how to handle pip cache in windows and Linux.. and how to ignore pip cache installation and what happens when i delete pip directory from windows -
pipenv install django failed on ubuntu
I tried to install django in my vscode, but the output is like this (my ubuntu version is 20.04) pipenv install djangoTraceback (most recent call last):File "/usr/bin/pipenv", line 6, in <module>from pkg_resources import load_entry_pointFile "/usr/lib/python3/dist-packages/pkg_resources/_init_.py", line 3254, in <module>def _initialize_master_working_set():File "/usr/lib/python3/dist-packages/pkg_resources/_init_.py", line 3237, in _call_asidef(*args, **kwargs)File "/usr/lib/python3/dist-packages/pkg_resources/_init_.py", line 3266, in _initialize_master_working_setworking_set = WorkingSet._build_master()File "/usr/lib/python3/dist-packages/pkg_resources/_init_.py", line 584, in _build_masterws.require(_requires_)File "/usr/lib/python3/dist-packages/pkg_resources/_init_.py", line 901, in requireneeded = self.resolve(parse_requirements(requirements))File "/usr/lib/python3/dist-packages/pkg_resources/_init_.py", line 787, in resolveraise DistributionNotFound(req, requirers)pkg_resources.DistributionNotFound: The 'pathlib' distribution was not found and is required by pipenv I tried use this sudo pip install --upgrade pip but i got this Traceback (most recent call last): File "/usr/bin/pip", line 11, in <module> load_entry_point('pip==20.0.2', 'console_scripts', 'pip')() File "/usr/lib/python3/dist-packages/pip/_internal/cli/main.py", line 73, in main command = create_command(cmd_name, isolated=("--isolated" in cmd_args)) File "/usr/lib/python3/dist-packages/pip/_internal/commands/__init__.py", line 96, in create_command module = importlib.import_module(module_path) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/usr/lib/python3/dist-packages/pip/_internal/commands/install.py", line 24, in <module> from pip._internal.cli.req_command import RequirementCommand File "/usr/lib/python3/dist-packages/pip/_internal/cli/req_command.py", line 15, in <module> from … -
Non model Singleton with django? [duplicate]
How can I make a non model singelton with Django? I have seen lots of examples but only for models. I need it for a service thing not really related to the model concept. Something like: class MySingleTonClass: def __init__(self): self.data = ExpensiveOperationOnlyToRunOnce() -
Trouble making queries in ForeignKey and this fields in Django
I am trying to make a query to find the number or Charging lots with a certain Charge Type in a Charging Station. Models -
Django Can I show one value in html without for loop?
I want to show data from view in html. This is views.py views.py def addDeviceForm(request): key=request.GET['key'] device=Device.objects.filter(key=key) data = {'device':device} return render(request,'adddevice_form.html', data) I try to show one data in html file like but it's not display value. <b>{{ device.key }}</b> If I show data with for like this code it have no problem. {% for device in device %} <b>{{ device.key }}</b> {% endfor %} Can I show one value in html without for loop? -
Trouble making queries in ForeignKey fields in Django
I am trying to make a query to find the number or Charging lots with a certain Charge Type in a Charging Station. Models class ChargeType(models.Model): level = models.CharField('Charging speed', max_length=15) current = models.BooleanField('Default AC, Check for DC') def __str__(self): return self.type class ChargeStation(models.Model): name = models.CharField(max_length=80) address = models.TextField()description = models.TextField(blank=True, null=True) def __str__(self): return self.name class ChargeLot(models.Model): charge_type = models.ForeignKey(ChargeType, blank=True, null=True, on_delete=models.SET_NULL, related_name='chargetype') charge_station = models.ForeignKey(ChargeStation, blank=True, null=True, on_delete=models.PROTECT) def __str__(self): return self.charge_type.type I tried from django.contrib.postgres.aggregates import ArrayAgg chargelot=ChargeLot.objects.all() ChargeStation.objects.annotate(level=ArrayAgg('chargelot__charge_type__level')) But it returns a FieldError saying chargelot is not one of the choices available. How can get all the charge levels of ChargeLots in one ChargeStation? Thank you. -
How can i change this query to ORM?
Hi i have two models like this, class Sample(models.Model): processid = models.IntegerField(default=0) # name = models.CharField(max_length=256) ## class Process(models.Model): sample = models.ForeignKey(Sample, blank=False, null=True, on_delete=models.SET_NULL, related_name="process_set") end_at = models.DateTimeField(null=True, blank=True) and I want to join Sample and Process model. Because Sample is related to process and I want to get process information with sample . SELECT sample.id, sample.name, process.endstat FROM sample INNER JOIN process ON sample.processid = process.id AND process.endstat = 1; (i'm using SQLite) I used sample_list = sample_list.filter(process_set__endstat=1)) but it returned SELECT sample.id, sample.name FROM sample INNER JOIN process ON (sample.id = process.sample_id) AND process.endstat = 1) -
Returning queryset.values() from viewset.get_queryset
Good day, I'm having difficulty trying to return queryset.values() from a viewset's get_queryset(). After finding 5 different methods for allegedly dealing with this, I am still left uncertain how to manage it correctly as my only working solution feels hacky. I use values so that I can get the name of the UserAccount through the foreign-key, rather than it's id. I tried using only() (replacing values() with it), but it doesn't seem to do anything. ViewSet class CommentViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated, ) serializer_class = serializers.CommentSerializer queryset = models.Comment.objects.all() lookup_field='comment_id' # A. This works, but I don't want to define extra actions if I don't have to. @action(detail=False, url_path='use-user-name') def use_user_name(self, request, **kwargs): """ Returns the user's name rather than its id. """ return Response(self.queryset.values('comment_id', 'operator_id__name', 'dlc', 'comment')) # B. This doesn't work. def get_queryset(self): return self.queryset.values('comment_id', 'operator_id__name', 'dlc', 'comment') # C. Nor does this. def get_queryset(self): queryset = self.queryset.values('comment_id', 'operator_id__name', 'dlc', 'comment') return json.dumps(list(queryset), cls=DjangoJSONEncoder) # D. Nor this. def get_queryset(self): return serializers.serialize('json', list(self.queryset), fields=('comment_id', 'operator_id__name', 'dlc', 'comment')) # E. Nor this. def get_queryset(self): return list(self.queryset.values('comment_id', 'operator_id__name', 'dlc', 'comment')) Models and Serializers class Comment(models.Model): comment_id = models.AutoField(primary_key=True, db_column='comment_id') operator_id = models.ForeignKey(settings.AUTH_USER_MODEL, models.DO_NOTHING, db_column='operator_id') dlc = models.DateTimeField() comment = models.CharField(max_length=100) class … -
How can I redirect to another server's web socket?
I am currently building a chat server using Rust. I tried to authenticate with the user's digest token that existed in the existing postgresql, but it failed because of the openssl problem. Therefore, I would like to authenticate the user through the existing django authentication authority, and when authentication is successful, I would like to redirect it to the rust chat server to make the service available. async def redirect(websocket: WebSocket, *args, **kwargs): await websocket.accept() return Response(status=HTTP_301_MOVED_PERMANENTLY) I tried redirecting from django to websocket, but failed. How can I authenticate with django and get access to the rust websocket server? I would appreciate it if you could let me know if there is a better way than redirect. If I have to redirect, I would appreciate it if you could tell me how to redirect. I googled hard, but I didn't find anything out. -
django.setup() in single file in 'apps' folder, got 'apps' is not a package
Tried to create projects in apps folder, got error -- 'apps' is not a package. init project django-admin startproject proj cd proj mkdir apps cd apps python ..\manage.py startapp foo apps.py from django.apps import AppConfig class FooConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'apps.foo' models.py from django.db import models class FileModel(models.Model): file = models.FileField(upload_to='static/uploads') settings.py ... INSTALLED_APPS = [ ..., 'apps.foo', ] python ..\manage.py makemigrations python ..\manage.py migrate tests.py import os,sys pwd = os.path.dirname(os.path.relpath(__file__)) sys.path.append(pwd + "../../") os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') import django django.setup() # SomeModel.objects.create(xxxx) $ proj\apps\foo>python tests.py Traceback (most recent call last): File "D:\temp\delweb2\proj\apps\foo\tests.py", line 8, in <module> django.setup() File "C:\Users\wgfabc\.pyenv\pyenv-win\versions\3.10.1\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\wgfabc\.pyenv\pyenv-win\versions\3.10.1\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\wgfabc\.pyenv\pyenv-win\versions\3.10.1\lib\site-packages\django\apps\config.py", line 223, in create import_module(entry) File "C:\Users\wgfabc\.pyenv\pyenv-win\versions\3.10.1\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1001, in _find_and_load_unlocked ModuleNotFoundError: No module named 'apps.foo'; 'apps' is not a package -
modulenotfounderror: no module named 'graphql_jwt'
I'm using django and I'm new in graphql I use graphene*django and graphql_*jwt packages for authentications I put "graphql_jwt.refresh_token.apps.RefreshTokenConfig", in the INSTALLED_APPS in settings.py file and I did everything in the docs and this is my requirements.txt pytz==2021.1 Pillow==8.3.2 argon2-cffi==21.1.0 redis==3.5.3 hiredis==2.0.0 celery==5.1.2 django-celery-beat==2.2.1 flower==1.0.0 uvicorn[standard]==0.15.0 django==3.1.13 django-environ==0.7.0 django-model-utils==4.1.1 django-allauth==0.45.0 django-crispy-forms==1.12.0 django-redis==5.0.0 djangorestframework==3.12.4 django-cors-headers==3.8.0 graphene-django==2.15.0 django-graphql-jwt==0.3.4 django-modeltranslation==0.17.3 drf-yasg2==1.19.4 django-filter==21.1 django-smart-selects==1.5.9 django-nested-inline==0.4.4 django-phonenumber-field==5.2.0 phonenumbers==8.12.33 djoser==2.1.0 dj-rest-auth==2.1.11 django-shortuuidfield==0.1.3 awesome-slugify==1.6.5 django-ckeditor==6.1.0 xlrd==2.0.1 pandas==1.3.5 django-cleanup==5.2.0 django-extensions==3.1.3 when I'm trying to use this package this error appears: modulenotfounderror: no module named 'graphql_jwt' /usr/local/lib/python3.9/site-packages/graphene_django/settings.py, line 89, in import_from_string -
How to access a dict from a PY file in Jinja for Flask Website
Im creating a site on flask, using jinja i want to access a dict from my dict.py file to display a table on my template but I am given a 'coin_dict' is undefined error on when i render. Any help? Template Code to access keys and values from dict: {% for key, value in coin_dict() %} <tr> <td> {{ key }} </td> <td> {{ value }} </td> </tr> {% endfor %} -
DRF Transaction atomic not work when I'm trying to call external def
I have multiple operations that I need to send it to server as single query and for that I'm using transaction atomic but this is not work if I call def post_image. this function is not in the same directory it is inside another file This my ImagesTrip.py: def post_image(trip_id): #lot of operations ... If serializer.valid(): serializer.save() return Response(status = status.HTTP_201_CREATED) this views.py I'm working on it with transaction.atomic(): trip_instance=trip.save() respo_img= post_images(trip_instance.pk) I need to save trip and store it in DataBase only if post image is valid and successfully done -
When loading JSON data into postgresql database, it only loads last object?
I am working on a Django project and I'm trying to load data into my PostgreSQL database through fixtures. I've read the documentation and followed the same format but for some reason, despite having several data, it will only show the last object when I try to view them in my database. I've even tried loading as yaml but still the same result. Here's an example: { "model": "my_app.post", "pk": null, "fields": { "category": 5, "post_title": "Your Next Investment 0.21 Acres of Flat Vacant Land 30 mins", "description": "It’s time to turn up the heat on your next investment. 0.21 acres of flat vacant land in Colorado City, Colorado. Start building your dream home now. This land would be the perfect place to start. Imagine waking up to unobstructed views and enjoying the many benefits of outdoor living.", "date_created": "2022-04-03" } }, { "model": "my_app.post", "pk": null, "fields": { "category": 5, "post_title": "$1,225 / 364ft2 - Patio/Balcony, Central Air, Tennis Court", "description": "Welcome home to Alta Living! Settle into one of our renovated studio, one, or two bedroom homes. If you are searching for a relaxing and inviting space, you're in luck! Every floorplan offers spacious living areas, vinyl plank … -
Celery django and python with ASCII
Using celery with django framework, I get this output: Traceback (most recent call last): File "/usr/local/bin/celery", line 8, in <module> sys.exit(main()) File "/usr/local/lib/python3.6/dist-packages/celery/__main__.py", line 15, in main sys.exit(_main()) File "/usr/local/lib/python3.6/dist-packages/celery/bin/celery.py", line 213, in main return celery(auto_envvar_prefix="CELERY") File "/usr/local/lib/python3.6/dist-packages/click/core.py", line 829, in __call__ return self.main(*args, **kwargs) File "/usr/local/lib/python3.6/dist-packages/click/core.py", line 760, in main _verify_python3_env() File "/usr/local/lib/python3.6/dist-packages/click/_unicodefun.py", line 130, in _verify_python3_env " mitigation steps.{}".format(extra) RuntimeError: Click will abort further execution because Python 3 was configured to use ASCII as encoding for the environment. Consult https://click.palletsprojects.com/python3/ for mitigation steps. This system supports the C.UTF-8 locale which is recommended. You might be able to resolve your issue by exporting the following environment variables: export LC_ALL=C.UTF-8 export LANG=C.UTF-8 Is there a way to set python to work globally with UTF-8? Where I should use this sentences? At command line?: export LC_ALL=C.UTF-8 export LANG=C.UTF-8 But I still have the same problem. I have also tried adding these statements to the top of celery.py import sys reload(sys) sys.setdefaultencoding("utf-8") celery.py from imp import reload import os from celery import Celery import sys reload(sys) sys.setdefaultencoding("utf-8") os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'appName.settings') app = Celery('appName') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() -
how to hit an api gateway endpoint from zappa
I am using django with zappa lambda https: //github.com/zappa/Zappa in production and the web application work fine. The problem i am facing is that in production, when i try to hit a public aws gateway endpoint in the code, the call to the resource timeout. (When i try locally, my codes do hit that endpoint) After reading multiple articles I found out that its because zappa lambda deploy the codes inside a private VPC,which has no access to the internet. If anyone has a quick solution to be able to hit from zappa lambda in production that endpoint that would be very helpful -
Do I need to test an already tested ForeignKey field when unit testing
I am writing unit tests for my Django project and I was wondering if it is actually useful to include assertions about a ForeignKey object that I already created unit tests for. I will use the example from the documentation: from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): return self.headline In this scenario lets say that I already wrote tests for the Reporter model, so I already tested it's fields. Is there any point to include assertions about the reporter field (other than making sure that it's the correct type) when writing tests for the Article model? Like for example checking if the first_name of the article's reporter object is not bigger than 30 characters, etc. It is probably not the smartest question but I didn't find a definite answer so far. -
Python command not found, but found after restarting command prompt
I was working on a python project where I was about to run it, but then the command prompt responded with: "'python' is not a known bash or shell command." I tried closing and opening the command prompt, but this time it worked. I don't really have a problem with it, but just wanted to know why this happened. -
django rest framework method 'DELETE' not allowed because DefaultRouter
This is my first project with Django and I am having a bit of trouble with the URLs. I have a customer model and I created the ModelViewSet for it so I can retrieve, delete and update the models in the database. To get all the basic URLs I used rest_framework.routers.DefaultRouter and registered the CustomerViewSet to it like so: router = routers.DefaultRouter() router.register(r'customers', CustomerViewSet, basename='customers') And then registered the URLs like so: urlpatterns = [ path('', include(router.urls), name="customers"), ] My problem is that I need to add a new URL for deleting all the customers in the database. I tried adding it like so: urlpatterns = [ path('', include(router.urls), name="customers"), path('customers/', deleteAllCustomers, name='deleteAll'), ] Where deleteAllCustomers is a function decorated with api_view(['DELETE']. When I try to call this URL (using Postman), I get 405 error (method 'DELETE' not allowed). From what I understand, it happens because that URL is already assigned by the DefaulteRouter for PUT/POST methods. I tried adding a destroy function to my CustomerViewSet, but it is only called when deleting one instance (with primary key passed in the URL). I haven't found a way to make the URL work and wasn't able to find any similar question. -
The best way to calculate closest distance with Google API and Django
I have a page with a list of people, and I would like the user to click a button to sort this list by closest. The list is of objects with the variables LON and LAT for longitude and latitude. I have made a function that calculates the distance based on Google Distance Matrix API. Here is the function: def calculateDistance(lat1, lon1, lat2, lon2): gmaps = googlemaps.Client(key=config('MATRIX_API')) matrix = gmaps.distance_matrix((lat1,lon1), (lat2,lon2), mode="driving") print(matrix['rows'][0]['elements'][0]['distance']['text']) I would like to know what is the best way to calculate the distance for all people in the list and order it inside the view that renders the page without creating a very heavy workload on the server. I thought of an idea, is to do this in the background (using Django Celery) and store the distances in the database so that the sorting happens by retreiving the distances from the DB instead of making API calls everytime the person refreshes the page, for example: class Distances(models.Model): visitor = models.ForeignKey(Visitor..... # Visitor looking for people person = models.ForeignKey(Person.... # Person on the list dist = models.CharField(....... And the function above, gets executed in the background every time a new person gets added to the database, or … -
Django Template Language: Create conditional for entire Model (not record by record)
Newbie problem. Per the following script in a template ... {% if request.user not in myModel %} <p>You have no account in the system.</p> {% endif %} ... the statement "You have no account in the system." is appearing 100 times on screen---because there are 100 records and therefore the condition is being checked 100 times. Is there a way to modify the script so that the statement appears just once? Meaning, it checks the entire database once for evidence that request.user appears anywhere in the model in aggregrate (and not whether it appears in each of the 100 records in the database)? Maybe there's an easier/better way to do this in views.py vs a template, but that's beyond my knowledge. Thank you. -
How to open a link if a function get called Django
I am trying to verified my user using email. It is all working fine but here I want to open a url when one of my api get called. After register I am sending them an email with link to activate account so link is one of my api which is a function I get the user by id and get save email verified and send a response as verified but rather then sending a response I want to automatically send him to the login page. How can I do it? In my frontend I am using react. this is the activate function or api @api_view(['GET']) def activate_user(request, pk): user = CustomUser.objects.get(id=pk) print(user) user.is_email_verified = True user.save() return Response('Email Verified') -
How to get email from usercusomer for followers
I want to send email for each follower after create item. But I don't know how to get this field from Models, and also I don't know how to send each follower to relate following. models.py class Book(models.Models): title = models.CharField(max_length=255) author = models.ForeignKey( "users.CustomUser", on_delete=models.SET_NULL, null=True ) # This is my try #But it doesn't work @hook(AFTER_CREATE) def send_followers(self): user = Followers.objects.all() followers_email = CustomUser.objects.filter( followers__follower__in=, followers__following=self.author.profile) if CustomUser.objects.filter( followers__follower__in=CustomUser.objects.only( 'followers__follower'), followers__following=self.author.profile ).exists(): send_mail( "Article published", '%s' % ( followers_email ), "nikitaalexnazarov@yandex.ru", [self.author.email], fail_silently=False, ) else: pass class CustomUser(AbstractUser): gender = models.ForeignKey( "Gender", on_delete=models.CASCADE, blank=True, null=True ) class Followers(models.Model): follower = models.ForeignKey( "users.CustomUser", on_delete=models.CASCADE, null=True, blank=True) following = models.ForeignKey( "Profile", on_delete=models.CASCADE, null=True, blank=True) class Profile(models.Model): slug = models.SlugField(unique=True) user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) -
PyTelegramBotAPI NameError: name 'p' is not defined Python(Django)
I am writing a telegram bot using pytelegrambotapi. I created a database using Python (django). The following code describes the calculation of the area of a rectangle. I first wrote the bot using a global variable. I have a problem! If only one user uses the bot, the bot is responding correctly. If the bot is used by many users at the same time, the bot is mixing up the answers and returning the wrong answer. I want to solve this problem using a database. But then I edited the code and made it look like this(BOT.PY) and I had a problem with localvariable. I can't figure out where the error is. Please help me :( BOT.PY ... ...; float_pattern = r'^\d{1,7}\.\d{1,2}$' ... ... def p_first(message): if message.text.isdigit() or re.match(float_pattern, message.text): chat_id = message.chat.id uid, _ = Profile.objects.get_or_create( external_id=message.chat.id, defaults={ 'name': message.chat.username } ) Message( profile=uid, param1=message.text ).save() p = Message.param1 print('Parameter (p) from:', chat_id) bot.send_message(message.chat.id, "Ajoyib, perimetr qabul qilindi!") msg = bot.send_message(message.chat.id, "<b>2. "Now secondside: "</b>", parse_mode="html") bot.register_next_step_handler(msg, height) return p else: msg = bot.send_message(message.chat.id, "Nice!") bot.register_next_step_handler(msg, p_first) def height(message): if message.text.isdigit() or re.match(float_pattern, message.text): chat_id = message.chat.id uid, _ = Profile.objects.get_or_create( external_id=message.chat.id, defaults={ 'name': message.chat.username } ) Message( … -
How to add query parameters to the <a href=
I want to redirect from one page to another (and save the query parameters). So i redirect like base.html <tr> <td> <a href="search/"></a></td> <td>...</td> </tr> urls.py path('main/search/', views.x, name='table_query') views.py @login_required @inject_session_params def table_structure(request, user_data, *args, **kwargs): if request.method=='GET': user_data['table']=kwargs['table'] user_data['structure'] = getTableProps(kwargs['table']) else: return redirect('login') return render(request, 'x.html', user_data) I have got al the needed information which I would like to use for the query, but I am not sure how to use it inside <a>. I have tried to create another function, which would generate the url and then redirect to the needed view, but it gives me an error. This is what I have tried: base_url=reverse('table_query') query = urlencode({'x': x, 'y': y, 'z': z}) url='{}?{}'.format(base_url,query) How to add query parameters (with a function) inside a tag, without writing <a href="search?x=x&y=y&z=z"?