Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django Cannot go the wanted link within another page
I am currently working on a website and I have a navigation bar in it. When I click the "about" button I need website to open localhost:8000/about/ link. But when I'm in a different page like localhost:8000/chapter/3/ It directs me to localhost:8000/chapter/3/about/ (The website is about a web novel thats why there is chapters) How can I make it so that wherever I click that "about" button from I want it to direct me to localhost:8000/about/. How can I make it happen? Note: I tried using ../ but didn't work for me Assume that urls and views are properly set up -
How do I create custom type for graphql using django?
class PostsType(DjangoObjectType): class Meta: model = models.Post fields = "__all__" I am using graphene for graphql with django. I have three model entities named Post, Comment, and Like. Whenever I query posts, I would like to return all posts with their respective likes and comments. How do I create a custom PostsType to achieve that? -
Django call a Model method inside another method of the same Model (in models.py)?
I want to call a model method inside another model method in models.py but i receive the error AttributeError: module 'my_website.models' has no attribute 'my_model_method' Here is my model: class SaleCode(models.Model): #my fields and methods... #the method I want to call def generate_token(self, apply=True, length=5): # stuff return { "token": token, "self-applyed": apply } #save() method override def save(self, *args, **kwargs): if not self.pk: #self.code is one of my fields self.code = self.generate_token()["token"] #the line that generates the error super(SaleCode, self).save(*args, **kwargs) What I have tried: I tried to place @classmethod (and @staticmethod) over the generate_token(...) declaration and then to call it as SaleCode.generate_token(): @classmethod def generate_token(self, apply=True, length=5): ... self.code = SaleCode.generate_token()["token"] #the line that generates the error I wrote the function outside the method and then called it as a normal function (it worked but it does not seem to be a "clear" way to do that.) -
Django - Why user did not pass IsAdminUser, but django does not throw exception of unauth?
Here is my sample code of using Token Authen: class test_api(generics.GenericAPIView): permission_classes = (IsAdminUser, IsAuthenticated) def get(self,request): return HttpResponse("You call random test api") I am using Token Authen, with my header of request like this, this is a Token of NOT AdminUser Authorization : Token fc823d7a1d8973056e11e9c8b974f17e351c4263 When I call the api, It print out of terminal these lines False [23/Aug/2021 10:39:20] "GET /user/get-user HTTP/1.1" 200 13 I suppose the False got print out from IsAdminUser permission. However, the code still reponse 200 and give me response of You call random test api. Only when I give the wrong Token, I receive 403 Unauth response. -
How to extend access token validity days of ConvertTokenView of Django rest framework social oauth2
I use Django rest framework social oauth2 ConvertTokenView to return access token. It seems by default tokens are valid for a day. How to extend token validity days? -
Django Herkou deployment retuning Not Found Error
I'm stuck in a loop of problems with running my Django app on Heroku. I'm facing with an Not Found Error and a Server Error (500) when i check the admin site don't seem to understand why? From my understanding, it seems like the Heroku build was successful, however it seems to be throwing an error with the static files that it is searching for? How can i resolve this issue? My project structure is built as : |-frontend(vuejs) |-server |-mysite |-settings |-__init__.py |-base.PY |-local.py |-production.py |-urls.py |-wsgi.py |-db.sqlite3 |-asgi.py |-__init__.py |-manage.py |-Procfile |-requirements.text The following is the Heroku logs: 2021-08-23T02:10:06.042544+00:00 app[web.1]: [2021-08-23 02:10:06 +0000] [7] [INFO] Worker exiting (pid: 7) 2021-08-23T02:10:06.042595+00:00 app[web.1]: [2021-08-23 02:10:06 +0000] [4] [INFO] Handling signal: term 2021-08-23T02:10:06.243215+00:00 app[web.1]: [2021-08-23 02:10:06 +0000] [4] [INFO] Shutting down: Master 2021-08-23T02:10:06.334633+00:00 heroku[web.1]: Process exited with status 0 2021-08-23T02:10:09.033247+00:00 heroku[web.1]: Starting process with command `gunicorn --pythonpath server plur.wsgi` 2021-08-23T02:10:11.272467+00:00 app[web.1]: [2021-08-23 02:10:11 +0000] [4] [INFO] Starting gunicorn 20.1.0 2021-08-23T02:10:11.273980+00:00 app[web.1]: [2021-08-23 02:10:11 +0000] [4] [INFO] Listening at: http://0.0.0.0:38843 (4) 2021-08-23T02:10:11.274025+00:00 app[web.1]: [2021-08-23 02:10:11 +0000] [4] [INFO] Using worker: sync 2021-08-23T02:10:11.276846+00:00 app[web.1]: [2021-08-23 02:10:11 +0000] [7] [INFO] Booting worker with pid: 7 2021-08-23T02:10:11.305556+00:00 heroku[web.1]: State changed from starting to up 2021-08-23T02:10:11.368570+00:00 … -
__init__() got an unexpected keyword argument 'request'
A silly question: why do we get TypeError on the super's __init__ only? Aren't they supposed to take the same arguments? class MyModelForm(forms.ModelForm): class Meta: model = MyModel def __init__(self, *args, **kwargs): # self.request = kwargs.pop('request') super().__init__(*args, **kwargs) If it's the same method of the same forms.ModelForm class, why does the first one accept request and the second doesn't? -
Django views not returning a value from a multiple parameter request?
I've been using vanilla Django as a backend to my React frontend. I'm trying to make a POST request using axios that passes a dictionary of 2 values to my django view, and so far on my front end the values are valid, the connection to the django url is made, but the only issue is the actual data being processed in the view. If I try to print the value, it returns as None. Heres what I have so far: Relevant Code views.py def render_data(request): reddit_url = request.POST.get('reddit_url') sort = request.POST.get('sort') print(reddit_url, sort) users_data, count = run_data(reddit_url, sort) data = { 'users_data': users_data, 'count': count, } return JsonResponse(data) component.jsx const APIcall = () => { axios .post( `http://127.0.0.1:8000/reddit_data/`, { reddit_url: location.state.link, sort: location.state.sort, }, { headers: { "Content-Type": "application/json", "X-CSRFToken": location.state.token, }, withCredentials: true, //cors requests } ) .then((res) => { console.log("YESSIR"); setLoading(false); }); }; Expected/actual output Ideally, the output would print the values from the request, but the actual result is just None, None. What I tried I tried using request.POST['reddit_url'] with no different results Double checking the frontend values to make sure the POST call is going through with the correct values I'll be honest I havent … -
Cannot import Django modules
Hello, the image is from my visual studio. I installed Django and tried to look at it. However, it seems like I cannot import Django modules. What is the problem? -
How can i get the SUBSCRIPTION values from this QUERYSET in Django
i want to access to all value of 'SUBSCRIPTION', but nothing work' i'm using for loop and more, but this send some responses like this. AttributeError: 'dict' object has no attribute 'SUBSCRIPTION' or TypeError: QuerySet indices must be integers or slices, not str. AttributeError: 'QuerySet' object has no attribute 'objects' so, how can i loop this querySet.. ??? -
Do queries involving tables with geometry that don't query the geometry itself take longer to query than a table without geometry?
I have a postgis table in a geodjango application that contains around 45,000 rows with a multipolygon geometry type. I would like to know if querying this table is slowed by the presence of the geometry when the geometry is not involved in the query, or in other words, if I related the geometry field with a one-to-one relationship would this boost performance? -
CSRF-cookie not set when sending a Delete request
I'm using django rest fro backend and reactnative for front, on my backend i have two models one for image and one for files, i can delete the files with a delete request but when i try to delete an image i get 403 forbidden crf cookie not set. Image view: def UploadsDetails(request,pk): try: image=Uploads.objects.get(pk=pk) except Uploads.DoesNotExist: return HttpResponse(status=404) if request.method =='DELETE': image.delete() return HttpResponse(status=204) urls: from django.urls import path from .views import Upload_list,login from .views import UploadsDetails urlpatterns=[ path('Uploads/',Upload_list), path('Uploads/<uuid:pk>/',UploadsDetails), path('login/', login) ] the files view : def FileDetails(request,pk): try: file=File.objects.get(pk=pk) except File.DoesNotExist: return HttpResponse(status=404) if request.method =='GET': serializers=Fileserializers(file) return JsonResponse(serializers) elif request.method =='PUT': serializer=Fileserializers(data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors,status=404) elif request.method =='DELETE': file.delete() return HttpResponse(status=204) -
django pagination very slow because of count how i can pass objects count
django pagination very slow because of count it is any way make me pass the number of object -
Passing instance method result to class attribute
Let's say I have two models, the first referencing a third User model: class Parent(models.Model): user = models.ForeignKey(User) ... class Child(models.Model): parent = models.ForeignKey( Parent, limit_choices_to={'user': get_user()} ) def get_user(self): return self.request.user I want to limit choices for the child model to instances bound to current user. One way to do it would be to pass the request to the form class and solve it inside __init__, but it present's other limitations. Is there a way to do this inside the model class, kind of like in the example above? -
supervisor: couldn't exec /home/clouditech/bin/gunicorn_start: ENOEXEC: supervisor: child process was not spawned
I continuously get this error message when trying to deploy my Django app with Nginx and Gunicorn. I've almost read and implemented all suggestions about this issue on ST.Overflow I've already implemented the following. 1. Ensured there is a shebang: #!/bin/bash 2. Put sh in front of command in /etc/supervisor/conf.d/clouditech.conf Please find my configuration files /etc/supervisor/conf.d/clouditech.conf [program:clouditech] command =sh /home/clouditech/bin/gunicorn_start user=clouditech autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/clouditech/logs/gunicorn-error.log gunicorn_start file /home/clouditech/bin/gunicorn_start #!/bin/bash NAME="core" DIR=/home/clouditech/clouditech USER=clouditech GROUP=clouditech WORKERS=3 BIND=unix:/home/clouditech/run/gunicorn.sock DJANGO_SETTINGS_MODULE=core.settings DJANGO_WSGI_MODULE=core.wsgi LOG_LEVEL=error cd $DIR source ../bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- -
Is there a Bootstrap option for a list in django that you can click?
I built a app for my employer in PowerApps and now learned to code so attempting to recreate my program in Django/Python. Is there a bootstrap option or another way to create a similar gallery in django like there is in PowerApps? I want to be able to display a phone list from a db then when you click the name of the contact it opens and shows phone number,email,details,ect about the contact. -
Please how can i fix this?
No default language could be detected for this app. Hello, I have a problem on my git hoping you can help me this is an error (No default language could be detected for this app.) And I have no idea how to handle this problem. I did it all on the internet, but nothing clear. Thanking you, can you orient me please? LITTLE NOTE the procfile file and the requirements file had some sort of? on it and were not which clickable. So I transformed them into a textmate file by going through: right click, Override File type puire Textmate. Besides, are File text and File textmate really different? Windows 10 64bit -
django not rendering template in html but as ordinariny textfile on browser
all my codes are working correctly but showing as text on browser. they are not rendering as an html page here is what my views is like @login_required def product_list(request, template_name='product/product_list.html'): ppix = Profilepix.objects.filter(user=request.user) product = Product.objects.filter(username=request.user).order_by('-postdate') data = {} data['object_list'] = product return render(request, template_name, data, {'Profilepix': ppix}) -
Django 'QuerySet' object has no attribute '_deferred_filter'
Just upgrading from Django 2.2 to 3.2 and encountered this error: 'QuerySet' object has no attribute '_deferred_filter' From stacktrace: File "/Users/jlin/projects/mp2/ext_db/models.py", line 434, in get_queryset return super(SOActiveManager, self).get_queryset().exclude( File "/Users/jlin/virtualenvs/mp2/lib/python3.8/site-packages/django/db/models/query.py", line 949, in exclude return self._filter_or_exclude(True, args, kwargs) File "/Users/jlin/virtualenvs/mp2/lib/python3.8/site-packages/django/db/models/query.py", line 961, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "/Users/jlin/virtualenvs/mp2/lib/python3.8/site-packages/django/db/models/query.py", line 966, in _filter_or_exclude_inplace self._query.add_q(~Q(*args, **kwargs)) File "/Users/jlin/virtualenvs/mp2/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1393, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/Users/jlin/virtualenvs/mp2/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1412, in _add_q child_clause, needed_inner = self.build_filter( File "/Users/jlin/virtualenvs/mp2/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1295, in build_filter value = self.resolve_lookup_value(value, can_reuse, allow_joins) File "/Users/jlin/virtualenvs/mp2/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1087, in resolve_lookup_value value = value.resolve_expression( File "/Users/jlin/virtualenvs/mp2/lib/python3.8/site-packages/django/db/models/query.py", line 1365, in resolve_expression query = self.query.resolve_expression(*args, **kwargs) File "/Users/jlin/virtualenvs/mp2/lib/python3.8/site-packages/django/db/models/query.py", line 196, in query if self._deferred_filter: AttributeError: 'QuerySet' object has no attribute '_deferred_filter' And this is the code that raised the error class SOActiveManager(models.Manager): def get_queryset(self): return super(SOActiveManager, self).get_queryset().exclude( status__in=SOStatuses.closed_statuses() ) called by sos = ServiceOrders.active.filter(account__number=customer_id).count() -
'null' and 'None' has been automatically added to my product dictionary
I am working on a Django project where I have coded a logic for customer to add products in their cart(product id as key and quantity as value). But whenever customer adds a product to cart, sometimes 'null' or sometimes 'None'is being add as a key to the cart. Here is the code how I add products to cart when server gets request to add product; Cart = request.get(product) If cart: cart[product] =+1 else: cart ={} cart[product] = 1 request.session['cart']=cart How can I delete those two keys from cart? I am new here pardon my mistakes -
Model class xxx doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I'm trying to integrate scrapy with django. I'm new to django and I can't figure out what I have done wrong. I have read previous questions but none of the answers seem to solve my problem. I keep getting this error raise RuntimeError( RuntimeError: Model class emails.models.Email doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. email_spider.py from scrapyy.items import EmailItem class firstSpider(scrapy.Spider): name = "emails" ... def parse(self, response): ... item = EmailItem() item['email'] = text_list2 ... process = CrawlerProcess() process.crawl(firstSpider) process.start() item.py import scrapy from scrapy_djangoitem import DjangoItem from emails.models import Email class EmailItem(DjangoItem): django_model = Email INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'scrapyy', 'emails', ] emails/models.py from django.db import models # Create your models here. class Email(models.Model): email = models.CharField(max_length=100) here is the structure of my project -
Does Django need more resources of a server than Laravel? If the both are the same kind of application
Suppose I want to build a social Media Platform Website and App with API. Then which will be less resource-hungry between Django and Laravel ? Which framework can perform faster for the application in a same config server? and why ? Thanks in Advance -
Django not checking paths in DIRS for files
I have a folder outside my templates file which I want to render I tried this: { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'projects')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] It doesn't work I want to render it like this: return render(request, f"{username}/{name}/index.html") Please help! Happy Coding! -
Django search bar and capital letters
Hello i am making Django app and I have a question. I have made a search bar. Everything would work correctly as I want but the problem is when the Item has capital letter or vice versa, quering does not work as I would like to. I wanted to make it search for the item when it is written 'tea' or 'TEA' or 'TeA'. I hope you understand me. :) Code: views.py def searchView(request): if request.method == "GET": context = request.GET.get('search') items = Item.objects.all().filter(title__contains=context) urls.py: urlpatterns = [ path('', ShopListView.as_view(), name='home-page'), path('signup', views.signup, name='signup-page'), path('login', views.loginView, name='login-page'), path('logout', views.logoutView, name='logout-page'), path('detail/<int:pk>/', ShopDetailView.as_view(), name='detail-page'), path('search/', views.searchView, name='search-page') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I think here is an issue in quering 'items'. If you want me to paste more code, just write it. -
How can I make a receiver listen to a user-specific signal in Django?
I'm writing a Django blog site where blog posts need to be approved by an admin (superuser) before they can be posted. In my BlogPost model, there is a Boolean field "approved". I've managed to implement all of this. However, I also want the user to be notified (via a django message) when their post is approved. (The user can go and do whatever else they want in the interim, before the admin gets around to approving their post, and so the message must appear on whatever page the user is currently on. Furthermore, if the user has multiple pages open at the same time (say, on different tabs), the message should appear on all of them.) This is what I am having some issues with implementing. I've drafted a small code snippet which encapsulates what I want to do. @receiver(post_save, sender=BlogPost) def message_on_approve(sender, instance, **kwargs): if instance.user != (the current user who is logged in): return if instance.approved: messages.success((request, to be sent to the page user is currently on), 'Your post has been approved!') else: messages.error((the same request), 'Your post has not been approved.') There are two issues that I am facing now. Firstly, due to the fact that …