Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is my django core.serializers so slow
I have my a serializer from core.serializers in my django view. It does work, but it sometimes takes over 1 minute to show my results table. Any ideas how to get it faster? # views.py from django.core import serializers def search_institution(request): form = SearchInstitutionsForm() qs = Institution.objects.all() if request.method == "POST": form = SearchInstitutionsForm(request.POST) if form.is_valid(): cd = form.cleaned_data if cd['name']: qs = Institution.objects.filter(name__contains=cd['name']) print(f"Before requesting from db: {datetime.now()}") print(f"After requesting from db, before serializing: {datetime.now()}") context = { "result_data": SafeString(serializers.serialize("json", qs)), 'form': form } print(f"After serializing, before rendering: {datetime.now()}") return render(request, "landing/result_table.html", context) else: context = { "form": SearchInstitutionsForm } return render(request, "stakeholders/institution_form.html", context) -
Unable to implement Azure Adfs authentication in Django
I have been trying to use the authentication system of azure and for that I have followed the below link https://django-auth-adfs.readthedocs.io/en/latest/azure_ad_config_guide.html#step-1-register-a-backend-application but Im kinda of stuck and don't know where the problem lies . I keep getting the below error message. For any more information please ask in comment I will try to provide it. Any help or guidance will be a great help -
Need to Fetch specific foreign key object product from database in Django
Hi everyone I am new at Django and working on e-commerce site. I create a model name category and pass it to model shop by using foreign key. In Category model I have category Sale and i want to fetch all products that have category sale in my landing page and rest of us in shop page. Any one please help me how I do it? My model.py code is: class category(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class shop(models.Model): s_id = models.AutoField(primary_key=True) s_name = models.CharField(max_length=50) s_category = models.ForeignKey(category, on_delete= models.CASCADE) s_artical_no = models.IntegerField(default=0) View.py: def index(request): prod = shop.objects.get(s_category = 4) params = {'prod': prod} return render(request, "main/index.html", params ) -
How Can I get related instance in formfield_for_dbfield method of TabularInline class of django admin?
Is it possible to get inline instance in formfield_for_dbfield method of TabularInline class in django admin? -
Can't use minutes from DateTimeField in django templates
M or m is month. How can i use |date so it gives me minutes. {{ client.time_of_receipt|date:"M, d h" }} -
Unable to get images in list in Django views.py context, Throws List AttributeError
I am using below code to get a list of all image and then display it: def index(request): data = cos.list_objects(Bucket='pixmedia') di = data['Contents'] endpoint="https://s3.us.cloud-object-storage.XXXXX.cloud/XXX/" #print(di) image_list=[] for key in di: print("Key is--->",key['Key']) res=key['Key'] res=endpoint + res print("Res is ---->",res) #context = { # 'image': res, #} image_list=image_list.append(res) print("Image List is",image_list) context = { {'image_list': image_list,} } return render(request, "index.html", context) But, i am getting below error on launching 127.0.0.1:8000: image_list=image_list.append(res) AttributeError: 'NoneType' object has no attribute 'append'. Please Help. -
How should I pass a raw query response to a Serializer class?
I am trying to fetch data using raw sql query but I am facing issues when I am trying to pass the raw sql response to the Serializer class. Serializer class User_Serializer(serializers.ModelSerializer): class Meta: model = Users fields = '__all__' View class UserView(APIView): def get(self, request, emailId, format=None): with connection.cursor() as cursor: cursor.execute("SELECT * FROM users") resRow = cursor.fetchone() serializerResponse = User_Serializer(resRow) return Response(serializerResponse.data) I realise that the Serializer class cannot work with the ModelSerialzier class in this scenerio. How should I build my Serializer considering the fact that I need to post and save data to the concerned model using this Serializer class. -
How to Redirect URLs to a certain URL Django Regex
In my URLs.py, I'm setting my URL like this url(r'^mobile/$', views.mobile, name='mobile') Navigating to localhost:8000/mobile works as expected but if typed in the URL: localhost:8000/mobile/hello/world/234234hjhf8sc3 it should redirect to localhost:8000/mobile however this does not happen because my regex is incorrect (I'm not sure) How could I do this/what is the correct regex to do this? Another example would be localhost:8000/mobile/send/help/as792lp should redirect to localhost:8000/mobile -
How do I prevent Django Channels routing error?
The route for the Django Channels project I'm building isn't working and at this point, I can't tell why. Everything seems fine to me yet I'm getting the same error from the server over and over again. I know there's something I'm missing, but what could that be?. ASG Setting import os from channels.routing import ProtocolTypeRouter from channels.routing import URLRouter from channels.auth import AuthMiddlewareStack from django.core.asgi import get_asgi_application from chat import routing os.environ.setdefault("DJANGO_SETTINGS_MODULE", "base_app.settings") # Handles routing protocols for Django Channels application = ProtocolTypeRouter( { "http": get_asgi_application(), # Points root routing to chat/routing.py "websocket": AuthMiddlewareStack(URLRouter(routing.websocket_urlpatterns)), } ) Channels route # chat/routing.py from django.urls import re_path, path from .consumer import ChatConsumer websocket_urlpatterns = [ re_path(r"ws/chat/(?P<chat_id>\d+)/$", ChatConsumer.as_asgi()), ] Channels consumer # chat/consumer.py import json from django.contrib.auth import get_user_model from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync from chat.models import Message from chat.views import last_10_messages # Instantiate user model User = get_user_model() class ChatConsumer(WebsocketConsumer): """Chat consumer class process data sent from WebSocket routing""" # === Utility === <---------------- Scroll down to see main Channel's methods def fetch_messages(self, data): """Fetch last messages from database""" messages = last_10_messages(data["chatID"]) serialized_messages = { "command": "fetch_messages", "messages": self.messages_to_json(messages), } # Send fetched messages self.send_message(message=serialized_messages) def new_message(self, data): """Stores … -
DRF & React: "login with google" doesn't create any Social Account in database
I don't know what I'm doing. I'm trying to Login with Google from React app. So I've created a project in Google cloud platform, set Authorized JavaScript origins url: http://localhost:3000 and Authorized redirect URIs http://127.0.0.1:8000/accounts/google/login/callback/ and got Clint Id and Secret key. Then I've created a Social application from Django Admin site with these ID and Key. then I write this code: settings.py: INSTALLED_APPS = [ 'myapp', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', #google ] SITE_ID = 1 REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_FILTER_BACKENDS':['django_filters.rest_framework.DjangoFilterBackend'], } urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), path('api/rest-auth/', include('rest_auth.urls')), path('api/rest-auth/registration/', include('rest_auth.registration.urls')), path('accounts/', include('allauth.urls')), in Reactjs: //...code responseGoogle = (response) => { console.log(response); } //..code <GoogleLogin clientId="634453711672-3lf3sk6g4dl74q428n14jc4n6n592d99.apps.googleusercontent.com" buttonText="Login" onSuccess={this.responseGoogle} onFailure={this.responseGoogle} cookiePolicy={'single_host_origin'} /> when i click this Login button, then select my gmail account, it console log an object. kx{Os: mx {$R: "**************", Ne: "Asif Biswas", ET: "Asif", GR: "Biswas",....}...}. but doesn't create any Social Account in database. My goal is: click the Login button > authenticate user > Create Social account and application token (in database). any suggestion? -
How to filter in django using condition
I have 4 file uploading fields (only one file is mandatory for uploading) and 4 status corresponding to each file. There is a filter in front end called 'Completed' to filter the dashboard. How to filter records which are completed (Completed status only if there is a file and its status need to be True, if 4 file are uploaded then all of the corresponding status of each file need to be True to consider as completed.No matter the person uploaded 1 or 4 files based on the files uploaded the corresponding file status need to be true. Table column example file1 | file1_status | file2 | file2_status | file3 | file3_status | file4 | file4_status -
django bulk insert using value from parent table instead of ID
I have 2 models -- AssetType and Asset (both have IDs and Asset has a foreign key point to AssetType) I want to bulk insert rows in the Asset table using Asset Type NAME, instead of ID. I tried to do df.to_sql() but it can't work because my df contains "asset type name" instead of asset type id. Is there a way to convert it easily? Expected Output The asset type table looks like this: id | name | description 1 | at1 | desc1 The Asset table should look like this asset_name | display_name | asset_type_id n1 | d1 | 1 The dataframe I want to insert in the Asset table looks like this (Input): asset_name | display_name | asset_type_name n1 | d1 | at1 So, I am passing in at1 in my dataframe but want to insert it as "id=1" for asset type. Is this possible in django? My models are: class AssetType(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=80, unique=True) description = models.CharField(max_length=80) class Asset(models.Model): asset_type = models.ForeignKey(AssetType, on_delete=models.CASCADE) asset_name = models.CharField(max_length=80) display_name = models.CharField(max_length=80) My serializer looks like this: class AssetTypeSerializer(serializers.ModelSerializer): class Meta: model = AssetType fields = "__all__" class AssetSerializer(serializers.ModelSerializer): asset_type_name = serializers.CharField(source='asset_type.name') class Meta: model … -
how to insert a floating value as binary numbers and retrieve as floating value in MySQL
how to insert a floating value as binary numbers and retrieve as floating value in MySQL, python, Django like I have a floating value 2000.252 I need store it on MySQL column as binary 010101 or string 'sddg121fg' or encryption 'dgdfggdfgttzzd' but when I retrieve this value it will be 2000.252 -
How to Use Django Queryset update() function with foreign key field cited by F()?
I want to make a simple query: with transaction.atomic(): Account.objects.select_for_update().filter(payments__status='PENDING', payments__created_date__lt=timezone.now()-timedelta(days=14)).update(balance=F('balance')+Sum(F('payments__amount') - F('payments__payment_fee__fee_amount')), payments__status='COMPLETED') It turned out it wasn't simple at all. I've tried Subquery but alternatively get "Joined field references are not permitted in this query" or "FOR UPDATE is not allowed with GROUP BY clause" Subquery doesn't work because aggregation doesn't work with select_for_update() locks. F() doesn't work because it is referencing foreign key fields... What's the best way to make this query work? Any idea? I am using postgresql behind the ORM. -
Django/SpaCy: Cannot import module outside of its root directory in Python
I am stumped trying to import and call this NLP package from outside of its root directory https://github.com/msg-systems/coreferee. I doubt it has anything to do with package and probably has everything to do with my not understanding how Python modules work. Here is a scenario: I cloned coreferee into a subdirectory of my Django project (/api/libs/coreferee). If I terminal into the root directory of the package, I can run the following test script fine: test.py in root of coreferee module at ./api/libs/coreferee import spacy import coreferee nlp = spacy.load("en_core_web_trf") nlp.add_pipe('coreferee') # passes the coreferee module as transformer doc = nlp("Although he was very busy with his work, Peter had had enough of it. He and his wife decided they needed a holiday. They travelled to Spain because they loved the country very much.") doc._.coref_chains.print() However, if I try to import coreferee from anywhere else in my application, I get a bad reference and the test script errors out. test.py at ./api/ import spacy from api.libs import coreferee spacy.prefer_gpu() nlp = spacy.load("en_core_web_trf") # en_core_web_lg nlp.add_pipe('coreferee') # this produces an error ValueError: [E002] Can't find factory for 'coreferee' I am stumped. -
How to exclude some data from values_list in Django?
I'm using checkbox filtering to filter the data in Django. While I want to exclude some data from checkbox filtering for example I have 5 brands SAMSUNG NOKIA MI IPHONE LG from the above list, I don't want MI should include in my checkbox list. So, How to exclude such data. forms.py class BrandForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) brand = Brand.objects.filter(category=3).values_list('name', flat=True) for name in brand: self.fields[f'{name}'] = forms.BooleanField(label=f'{name}',widget=forms.CheckboxInput(required=False) -
Follow Button in Django
I'm new to django and creating a follow button where users can follow a certain profile. When I click 'follow' on the profile, currently I don't get any errors at all. Nothing happens. I don't see anything in my console. There's no error. Am I missing something obvious? No matter what I put in views.py nothing happens. So I don't think it's that. Is it my url? urls.py urlpatterns = [ path("", views.index, name="index"), path("fol/<str:username>", views.fol, name="fol"), path("profile/<str:username>", views.profile, name="profile"), ] models.py class User(AbstractUser): pass class Post(models.Model): text = models.TextField(max_length=500, blank=True, null=True) username = models.ForeignKey('User', on_delete=models.CASCADE, related_name='author', null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) like = models.ManyToManyField( User, blank=True, related_name="liked_user") def __str__(self): return self.user.username class Follow(models.Model): target = models.ForeignKey('User', on_delete=models.CASCADE, related_name='followers') follower = models.ForeignKey('User', on_delete=models.CASCADE, related_name='targets') html {% extends "network/layout.html" %} {% load static %} {% block body %} <h3> You are viewing {{ profileuser.username }}'s profile. </h3> <br> <br> <br> <br> {% if user1 != user2 %} <div class="pull-right"> <a href="{% url 'fol' username=profileuser.username %}"></a><input class="btn btn- primary" type="submit" value="Follow"> </div> <br><br> <div class="pull-right"> <input class="btn btn-primary" type="submit" value="Unfollow"> </div> {% endif %} {% for i in page_obj %} <div class='card mb-3' style="max-width: 530px;" id="card-posts"> <div class="row no-gutters"> <div class="col-md-8"> <div … -
Import cannot be resolved pylance error in vscode, have tried a few fixes
I am having trouble using pylint for my Django app. I am receiving a couple of errors and have resolved some using other threads but the main one I am still running into is Import ".forms" could not be resolved. I am hitting this error inside the views.py file when trying to import from forms.py with the following import from .forms import ArtistForm (ArtistForm being a class). I have tried following the below resources but have not been very successful. https://github.com/microsoft/pylance-release/blob/main/TROUBLESHOOTING.md#unresolved-import-warnings This is what I added to my .vscode/settings.json to try and resolve with the above - "python.analysis.extraPaths": ["tunr/", "./tunr/templates/tunr"] I also tried using the .env fix detailed in the below article - https://appdividend.com/2021/03/26/python-unresolved-import/ I am new to coding so I have been having trouble fully understanding how to fix this. Any help is appreciated. Below is my file structure, not the tunr folder is at the root: tunr ├── apps.py ├── models.py ├── templates │ └── tunr │ ├── artist_detail.html │ ├── artist_form.html │ ├── artist_list.html │ ├── base.html │ ├── forms.py │ ├── song_detail.html │ └── song_list.html └── views.py Let me know if any other information will be helpful. -
Django List View Sorting Bulletins
I have a ListView of bulletins I am trying to provide ordering options for. I am using a dropdown to pass a URL parameter called sortBy. I have confirmed via my print statement at the end of def get(self, request): that the order of the queryset changes as expected when different values are passed to sortBy. The problem I am facing is that even though the order of the queryset is changing as expected, this is not being reflected in myTemp.html. The order of the bulletins being displayed are not changing even though the order of the queryset is. What is causing this behavior? Views.py @method_decorator(login_required, name='dispatch') class BulletinList(ListView): model = Bulletin_VW template_name = 'myTemp.html' context_object_name = 'bulletins' additional_context = {} @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get_queryset(self): queryset = Bulletin_VW.objects.filter(store_id=self.additional_context['storeID'], entity_id=self.additional_context['entityID']) ordering = self.get_ordering() queryset = queryset.order_by(ordering) return queryset def get_context_data(self, *args, **kwargs): self.object_list = self.get_queryset() context = super(BulletinList, self).get_context_data(*args, **kwargs) context.update(self.additional_context) return context def get_ordering(self): ordering = self.request.GET.get('sortBy', 'Name') sortDict = {'Name': 'author', 'Date-Newest': '-capture_date', 'Date-Oldest': 'capture_date'} ordering = sortDict.get(ordering) return ordering def get(self, request): if not validate_user_session(request.user.id): return redirect('newSession') currentSession = Current_Session_VW.objects.filter(user_id=request.user.id)[0] storeID = currentSession.store_id entityID = currentSession.entity_id entStore = currentSession.entity_store_name balance = get_balance(storeID, … -
Redirect in Django giving 302 response
What I am trying to do is prevent an authenticated user from accessing the signup page. This is what I have written. def validate_request(request): if request.user.is_authenticated and request.user.is_active: print("Condition approved") return redirect("home:home") def signup_view(request): validate_request(request) if request.method == "POST": form = StudentUserSignupForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect("student:email_confirmation") else: redirect("home:home") else: print("Got some other method: ", request.method) form = StudentUserSignupForm() context = { "form": form, } return render(request, "signup_login_form.html", context=context) When I test and create a new user, it gets created successfully and is redirecting fine. However, the new user created is still able to access the signup page. I added some quick print statements at the redirect function call inside validate_request function and the output was <HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/"> The URL it was trying to check for is already present and is correct. I replaced the redirect to https://google.com instead of home:home and it still gave the same response. The third thing tried was to redirect as soon as the signup_view function is called. That too was failing with the same response with both internal redirect and redirecting to Google. I have been stuck on this problem for a while. I have gone through … -
FCM django installation error python 3.6.9
Installing fcm-Django on my local was fine, but on the server, I am getting errors. File "/opt/pythonprojects/env/lib/python3.6/site-packages/setuptools/command/build_ext.py", line 203, in build_extension if ext._needs_stub: AttributeError: 'Extension' object has no attribute '_needs_stub' File "/tmp/pip-build-re2xfk5h/grpcio/src/python/grpcio/support.py", line 98, in diagnose_attribute_error "We expect a missing `_needs_stub` attribute from older versions of " commands.CommandError: We expect a missing `_needs_stub` attribute from older versions of setuptools. Consider upgrading setuptools. Command "/opt/pythonprojects/env/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-re2xfk5h/grpcio/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-ljbtkbh4-record/install-record.txt --single-version-externally-managed --compile --install-headers /opt/pythonprojects/payrink-env/include/site/python3.6/grpcio" failed with error code 1 in /tmp/pip-build-re2xfk5h/grpcio/ Also setuptools is up-to-date on my server which I updated several times. Also tried to install grpcio manually but had no success. Python 3.6.9 -
Django update rows base on order in queryset
I have a simple django model class Item(Model): name = CharField() rank = PositiveIntegerField() created_at = DateField(auto_now_add=True) I want to update the object rank based on their order when sorted by a field (name or created_at) e.g. when ordering by name [("Pen", 0, "2021-05-04"), ("Ball", 0, "2021-05-04")] => [("Pen", 1, "2021-05-04"), (Ball, 0, "2021-05-04")] I already know I can do this using bulk_update but it means I have to fetch the objects in memory items = Items.objects.order_by("name") for i, item in enumerate(items): item.rank = i Item.objects.bulk_update(items, ["rank"]) I was wondering if there is a way to do it with 1 query directly in the database, without having to fetch the data -
For if Loop ManyToMany Field Django
How can I query a manytomanyfield in a Django template? For example, this if statement doesn't work, but this shows what I'd like to do: Model: class Product(models.Model): Category = models.ManyToManyField(Category) Template: {% for p in Product %} {% if p.Category_id == 6 %} {{p.id}} {% endif %} {% endfor %} -
sys.settrace disabling needed or not
The backend REST service I am working is written in python/django and sometimes the server crashes due to one request without reporting the exception i.e. can't even know which line it was where it last reached. The application does not have any function entry/exit logs which could be enabled by environment config so alternative I have come up with was I will enable sys.settrace based on a custom request header. So, I have written something like this in one of the request middleware: def debug_tracer(frame, event, arg = None): code = frame.f_code func_name = code.co_name line_no = frame.f_lineno print(f"A {event} encountered in \ {func_name}() at line number {line_no} ") return debug_tracer if.requests.headers.get("HTTP_TRACEBACK"): sys.settrace(debug_tracer) It behaves like this for a single server deployment: Request at t=1 without traceback header -> Plain request-response logs Request at t=2 with traceback header -> Every line of execution gets into logs along with request-response logs Request at t=3 without traceback header -> Plain request-response logs This is working fine right now, i.e. whenever I pass a header with traceback key, the logs for that particular request contain the details calls/returns/lines. But I am not able to understand that without doing sys.settrace(None) i.e. actively disabling the … -
How to setup alias in Nginx
I deployed a django application using Digital ocean plateform. When nginx was serving static files through roots everything worked fine. But the moment installed boto3 and Django_storage and turned to alias nginx stopped serving the static files. I saw that similar question was asked but I still don't understand why the static files are not been served. After running python manage.py collectstatic the staticfiles appeared in the folder in digital ocean space but the staticfiles are not being served on the browser. My project structure is as follows: $myprojectdir/ myproject/ settings.py static/ manage.py ... settings.py AWS_ACCESS_KEY_ID = '***' AWS_SECRET_ACCESS_KEY = '***' AWS_STORAGE_BUCKET_NAME = '*** AWS_S3_ENDPOINT_URL = '***' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = '***' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' sudo vim /etc/nginx/sites-available/myproject server { server_name domain; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/sammy/myprojectdir/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/api.flolog.co/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/api.flolog.co/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host …