Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to Call the Django Function
def ravi(request): if request.method = "POST": entered_index = request.POST['index'] socket_opened = False def event_handler_quote_update(message): print(f"quote update {message}") def open_callback(): global socket_opened socket_opened = True alice.start_websocket(subscribe_callback=event_handler_quote_update, socket_open_callback=open_callback, run_in_background=True) while(socket_opened==False): pass alice.subscribe(alice.get_instrument_by_symbol('NSE','ONGC'),LiveFeedType.MARKET_DATA) form = trades() return render(request, "blog/box_breakout.html",{'form': form}) "When I call the function, the browser keeps on loading. It neither works nor giving me the error" . -
Using F function into annotate
i have a problem about using f function into annotating i use F function to retreive "user__id" and pass it to get_user_daynum that it should returns a number but it always returns a same number. after that i filter them by creating a lookup_field. i test the get_user_daynum many times and i get correct number but about using it in annotate i'm confused. for date, days in valid_date_days.items(): lookup_field = f'{date}__in' intended_user_workpattern = intended_user_workpattern.annotate( **{date: Value(get_user_daynum(date, F('user__id'), request_user_wp.work_pattern))} ) intended_user_workpattern = intended_user_workpattern.filter( **{lookup_field: list(days)} ) -
Django inlineformset_factory not displaying all initial data
I'm providing a list of dictionaries when instantiating an inlineformset to display some initial data, for example: initial_data = [{'form1': 'foo'}, {'form2': 'foo'}, {'form3': 'foo'}, {'form4': 'foo'}, {'form5': 'foo'}] I then supply this to my formset: MyInlineFormset(initial=initial_data) However it only shows three of the five forms: Displayed forms If I pass extra=5 when constructing the formset, it works no problem: Displayed forms when extra=5 I know the default is extra=3 but I thought it would override this based on the number of initial forms provided. Is that incorrect? -
How can i change this query to ORM? (JOIN without foreign key and order by second table)
Hi i have two models like this, class Sample(models.Model): name = models.CharField(max_length=256) ## processid = models.IntegerField(default=0) # 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, main_process.id, main_process.endstat FROM sample INNER JOIN process ON sample.processid = process.id ORDER BY process.endstat; How can i do with ORM like this SQL? -
i want to make an wallet that is linked with his phone number when a user register with the mobile number a wallet is automatically generated
There's two models in my application one is user which contains the details of user like mobile number and the other one is wallet model which contains the total balance, add amount etc. what i want is when a user register itself a wallet automatically gets generated associated with his phone number. i have done this models.py class User(models.Model): mobile = models.CharField(max_length=20) otp = models.CharField(max_length=6) name = models.CharField(max_length=200) username = models.CharField(max_length=200) #logo_path = models.CharField(max_length=200) logo = models.ImageField(null=True, blank=True) profile_id = models.CharField(max_length=200) class Wallet(models.Model): user = models.ForeignKey(User,null=True,related_name='wallet_mobile',on_delete=models.CASCADE) total_amount = models.DecimalField(_('total'), max_digits=10, decimal_places=2, default=10) add_amount = models.DecimalField(_('amount'), max_digits=10, decimal_places=2, default=0) win_amount = models.DecimalField( max_digits=10, decimal_places=2, default=0) deduct_amount = models.DecimalField( max_digits=10, decimal_places=2, default=0) serilalizers.py class walletserializer(serializers.ModelSerializer): wallet_mobile = serializers.StringRelatedField() class Meta: model = Wallet fields = ['user','total_amount','add_amount','win_amount','deposit_amount'] views.py @api_view(['GET']) def get_wallet(request,pk): snippet = Wallet.objects.get(pk=pk) if request.method == 'GET': serializer = walletserializer(snippet) return Response(serializer.data) i am getting the data base with user id i want the data with with associated phone number -
Navigate me to get set up a third party google login for my webpage using django rest framework and React JS
I was stuck on setting the google login authentication using django rest framework in the backend and react JS in the frontend. We have a email and passowrd custom login for the website and we need to implement the third party google login. I have tried many ways and it didn't worked for me, on one way it is getting username, password, clientID, clientsecret, and the grant type it is taking as password for a post call. Maybe what i need is when a user clicks google sign in the front end generates a access token and id token, and user email from the google and it comes to connect on backend where i need to give him the data of that user by approving the request. How can i able to do that? Please help me with any code or share me with a complete reference of setting up the google login. -
Pycharm cannot suggtest import for django.test
Not suggest any class in django.test, but worked in django.http. How to fix it ? -
Why i am getting Validation error even when input is correct in form
I was learning Django form validation from some online resource , was working on form validation , I created a validation error depicting the condition and passed it in form field , but the validation error is raising even if I am giving correct input. Similar to this happened when i raised a validation error for botcatcher without using validators, the error was not raised even i was giving input through inspect (its code is commented) ,Do help me out! forms.py from django import forms from django.core import validators def check_name(value): if value[0].lower() != 'K': raise forms.ValidationError('Name should start with K') class FormName(forms.Form): name = forms.CharField(validators=[check_name]) email = forms.EmailField() text = forms.CharField(widget=forms.Textarea) botcatcher = forms.CharField(required=False, widget=forms.HiddenInput, validators=[validators.MaxLengthValidator(0)]) # def cleaned_botcatcher(self): # botcatcher = self.cleaned_data['botcatcher'] # if len(botcatcher) > 0: # raise forms.ValidationError('CAUGHT THE BOT') # return botcatcher [webpage for same][1] views.py from django.shortcuts import render from . import forms # we can also use from basicapp import forms . refers to current directory # Create your views here. def index(request): return render(request, 'basicapp/index.html') def form_name_view(request): form = forms.FormName() if request.method == 'POST': form = forms.FormName(request.POST) if form.is_valid(): # DO something print("VALIDATION SUCCESS , POSTED") # Retreiving posted data print("NAME: " … -
Multiple user access to one primary account Django auth
I have already configured custom User authentication for my project, however, I would appreciate some advice on how to implement the following: Overview of requirements: My project requires that a customer be able to setup an account to use our online services. That same customer (as administrator of the account) would then be able to add sub-users to that account and also be able to configure permissions for each of those sub-users with respect to that account. My question: I am not sure how to begin to implement this and I would appreciate some practical guidance on where start. -
How to update and insert records after every 1 minute in sqlite?
I have created a django project which contains one table. I want to automatically update the records in sqlite databse after every minute. How can be this done? I have already used time.sleep(18000) library of python but it didn't worked. In if:else statement insert and update operations are performed. views.py: def index(request): while True: r1 = requests.get("http://127.0.0.1:2000/_nodes") script = r1.json() write = script['nodes']['data'] ts1 = script['nodes']['time'] print("write ",write) print("ts1 ",ts1) r2 = requests.get("http://127.0.0.1:2000/_nodes") script = r2.json() read = script['nodes']['total'] ts2 = script['nodes']['time'] print("read ",read) print("ts2 ",ts2) new_count = write+read new_t = (ts1+ts2)/2 print ("new count", new_count) print("new ts", new_t) q = data.objects.filter() if q.exists(): test1 = data.fetch() for row in test1: test1={ 'id':row.id, 'sum': row.sum, 'ts': row.ts, 'status': row.status } prev_t = test1['ts'] prev_count = test1['sum'] if(test1['id']==1): if(new_count < prev_count): test2 = data.objects.get(id=1) print("TEST2 Type", type(test2)) print(test2) test2 = data(id=1,sum=new_count,ts=new_t,status="restarted") test2.save() print(test2) print(type(test2)) else: test1 = data.fetch() test2 = data.objects.get(id=1) print("TEST2 Type", type(test2)) print(test2) test2 = data(id=1,sum=new_count,ts=new_t,status="updated") test2.save() print(test2) print(type(test2)) else: test2 = data(id=1,sum=new_count,ts=new_t,status="firstQuery") test2.save() print (test2) print("Fresh record created") test2 = data.fetch() for row2 in test2: test2={ 'id':row2.id, 'sum': row2.sum, 'ts': row2.ts, 'status': row2.status } print(test2) print(type(test2)) -
How to assemble a variable name in Django templating language?
I am trying to assemble a variable in Django template in that way: obj.length.forloop.counter where the foorloop.counter should return the number. for example obj.length.1 then obj.length.2 and so on... I tried the add filter: obj.length|add:forloop.counter but that returned nothing at all. Is there any way that I can assemble variable names like that in django templating language? -
Spinning Up a Staging Server for Testing a Django Web-Application
I have been following Harry J.W. Percival's Test-Driven Development with Python. In the chapter of "Testing Deployment Using a Staging Site", I am confused as to the course of action that I should take now to implement this: Spinning Up a Server I’m not going to dictate how you do this—whether you choose Amazon AWS, Rack‐space, Digital Ocean, your own server in your own data centre or a Raspberry Pi in a cupboard behind the stairs, any solution should be fine, as long as: Your server is running Ubuntu (13.04 or later). You have root access to it. It’s on the public Internet. You can SSH into it. I am a beginner with respect to the framework. Hence, the topic of Deployment and Staging is somewhat unnerving for me, owing to my inexperience. The author previously states that we may either run our own (possibly virtual) server or go for PaaS. So, my query is how do I accomplish the process of setting up a staging server for verification and validation testing purposes (links to sources explaining the process shall be greatly acknowledged)? Given the nature of my problem, I could not figure out how to move ahead. Should I … -
Django "fields" attribute of user forms (UserCreationForm and UserChangeForm)
According to Django docs: It is strongly recommended that you explicitly set all fields that should be edited in the form using the fields attribute. I have a custom user model, so I overrode UserCreationForm and UserChangeForm, but I'm not sure about the fields attribute of the Meta class. The admin site will be editing all fields of a user; so in UserChangeForm, do I have to include all fields in this attribute? like this: class Meta: model = User fields = ( "email", "password", "is_active", "is_staff", "is_superuser", "date_joined", "last_login", "groups", "user_permissions", # maybe there are others that I'm missing? ) Or in this case, it's safe to use the '__all__' shortcut? and does this mean I shouldn't use the UserChangeForm anywhere other than the admin site, because of the security issue mentioned in the docs? -
Django how to not comment some lines with makemessages
Problem I translate my group names in my Django application with the default translation tools. Since my group names are not hard-coded in my code, when I run makemessages, the lines corresponding to my group names are commented out. Example I have a group named management_product which is automatically created during migrations. I put these lines in django.po: msgid "management_product" msgstr "Gestion des produits" But if I run django-admin makemessages -l fr, they are commented out: #~ msgid "management_product" #~ msgstr "Gestion des produits" Question How can I disable this behaviour? -
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