Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I check the notification from the application?
enter image description here I check if there are any notifications that I haven't read through the DB data every 15 seconds. However, this method is likely to put a lot of pressure on the server when there are more users. How can I check notifications in a way other than a time interval? Please explain the new method! -
how to convert live djnago project to rest api project
what is the best way to convert the project from django to django rest framework i have live django project, which is completely working, but now it want to convert the project into rest api. i had make the rest api for project which has new classes and function for the rest api with (form verification and same logic) copy from the django class which has been implemented. so there is duplication of logic, so is there any way to do not replicate the logic and make running both of the classes django and django rest framework ? problem is when any update needed for any page then i have to code both side django and django rest framework , so there can be some mistake arise in copy !! suggestions are welcomed!! -
How to add extra_context to django admin panel
As I know I can see context of page adding {% debug %} to template. I tried to add extra context using django_with_extra_context_admin library: def get_extra_context(self, request, **kwargs): extra_context = super().get_extra_context(request, **kwargs) or {} extra_context.update({ 'testextra': 1, }) return extra_context And I don't see this context neither {% debug %} nor {{ extra_context }} nor {{ testextra }}. Next I tried to add context by redefining changelist_view of ModelAdmin: def changelist_view(self, request, extra_context=None): # extra_context = extra_context or {} extra_context = {'test': 1} return super(RegisterDaposAdmin, self).changelist_view( request, extra_context=extra_context, ) And I don't see this context neither {% debug %} nor {{ extra_context }} nor {{ test }}. Finally, I tried to add context in urls: path("admin/", admin.site.urls, {'extra_context': {'mycontext': 1}}), And I don't see this context neither {% debug %} nor {{ extra_context }} nor {{ mycontext }}. What did I do wrong? -
get field value on its change in django models
I hope you are fine. I have two fields with the name of price and discountedPrice in a model. The thing that I want is to get the values of these two fields on their change to calculate the discount percent from them before the admin clicks on the save button. I will thank anyone to give me a piece of guidance about this matter. -
Django TestCase can't edit object
I want to test my edit object view in Django. This is my view class EditRoomView(View): def get(self, request, room_id): room = ConferenceRoom.objects.get(id=room_id) return render(request, "edit_room.html", context={"room": room}) def post(self, request, room_id): room = ConferenceRoom.objects.get(id=room_id) name = request.POST.get("room-name") capacity = request.POST.get("capacity") capacity = int(capacity) if capacity else 0 projector = request.POST.get("projector") == "on" if not name: return render( request, "edit_room.html", context={"error": "Podaj nazwę sali"}, ) if capacity <= 0: return render( request, "edit_room.html", context={"error": "Podaj dodatnią pojemność sali"}, ) try: room.name = name room.capacity = capacity room.has_projector = projector room.save() except: return render( request, "edit_room.html", context={"error": "Sala o podanej nazwie już istnieje"}, ) return redirect("/") and this is my test: def test_edit_room_POST(self): response = self.client.post(self.edit_room_url, { 'room_name': "test3", 'capacity': 5000, 'projector': False, }) self.room1.refresh_from_db() self.assertEquals(self.room1.name, "test3") I'm created my object by this: @classmethod def setUpTestData(cls): cls.room1 = ConferenceRoom.objects.create(name="test", capacity = 1000, has_projector = True) I tried to do with and without refresh_from_db but i can't edit my object in test. Editing object in view work correctly. -
Django user created via google auth without social application token
Using django-allauth users signed-in via google API, but social application token is not being created, how to get it? -
What is the Best Practices when comes to Security Headers for Django settings.py and NGINX?
With reference to OWASP, and industry best practice, what is the most ideal way of configuring security headers? This is what I have done so far: Nginx.conf add_header Strict-Transport-Security "max-age=31536000; includeSubdomains"; add_header Permissions-Policy "geolocation=(), midi=(), sync-xhr=(), microphone=(), camera=(), magnetometer=(), gyroscope=(), fullscreen=(self), payment=()"; add_header X-Xss-Protection "1; mode=block" always; add_header X-Content-Type-Options "nosniff" always; django settings.py SECURE_REFERRER_POLICY = "strict-origin-when-cross-origin" CSRF_COOKIE_SECURE = True CSRF_USE_SESSIONS = True CSRF_COOKIE_HTTPONLY = True SESSION_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = 'Strict' #django-csp omitted out Current Im getting a server grade A+ for this existing configuration. However, I would definitely love to learn more from the public whom are more proficient in this field! -
How to add multiple orderitems to one order
Disclaimer: I am new in django and i am trying to create a shopping store Here are my models.py class Service(models.Model): name = models.CharField("name",max_length=255) class Order(models.Model): date = models.DateField(auto_now_add=True) isDelete = models.BooleanField(default=False) class OrderItem(models.Model): order_id = models.ForeignKey(Order, on_delete=models.CASCADE, null=False) service_id = models.ForeignKey(Service, on_delete=models.CASCADE, null=False) quantity = models.PositiveIntegerField(null=False) price = models.DecimalField(decimal_places=2,max_digits=99, null=False) I have made this api_view function which can create one order with one orderitem. Note : I do not have any serializers for this. I run this api through Postman. @api_view(['GET', 'POST']) @csrf_exempt # class CreteOrderView(View): def create_order(request, *args, **kwargs): if request.method == 'POST': now = datetime.date.today() order = Order.objects.create(date=now) order.save() orderid = order.id order_id = orderid orderitems = OrderItem.objects.all().values() price = request.POST.get('price') quantity = request.POST.get('quantity') service_id = request.POST.get('service_id') orderitemcreate= OrderItem.objects.create(order_id_id=order_id, service_id_id=service_id,quantity=quantity,price=price) orderitemcreate.save() return Response({"Order Created"}) else: order_qs = models.Order.objects.all().values_list() OrderItem_qs = models.OrderItem.objects.all().values_list() return Response({"Order":str(order_qs),"OrderItem":str(OrderItem_qs)}) Problems: It only accepts data through form data (but i want to send data in json form) I want to add multiple orderitems in one order. Is there any solution for this? Expected Input/Output: [ { "service_id": 1, "quantity": 2 "price": 20, }, { "service_id": 2, "quantity": 2 "price": 20, }, { "service_id": 3, "quantity": 2 "price": 20, }, ] -
Django RawQuerySet
I'm try to do a RawQuerySet in my django model, but it not return any data. I do this query direct at database and works well, but to django RawQuerySet nothing is returned. Could you help me? data_in = "'2022-05-15'" data_out = "'2022-08-20'" id_estudo = 1 query = f'''SELECT ag.id, dia, first_name, last_name, descricao, modelo, serialNumber, acronimo FROM model_1 ag,model_2 ma, model_3 user, model_4 es ON ag.model_2_id = ma.id AND ag.model_3_id = user.id AND ag.model_4_id = es.id WHERE dia BETWEEN {data_in} and {data_out} AND es.id = {ester_id}; ''' return Model.objects.raw(query) -
Django + Celery + Rabbit: kombu.exceptions.OperationalError: [Errno 111] Connection refused
Although celery reports no problems at start and says it successfully connected to redis (see log), I get this error running celery inspect ping Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/kombu/connection.py", line 446, in _reraise_as_library_errors yield File "/usr/local/lib/python3.8/site-packages/kombu/connection.py", line 433, in _ensure_connection return retry_over_time( File "/usr/local/lib/python3.8/site-packages/kombu/utils/functional.py", line 312, in retry_over_time return fun(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/kombu/connection.py", line 877, in _connection_factory self._connection = self._establish_connection() File "/usr/local/lib/python3.8/site-packages/kombu/connection.py", line 812, in _establish_connection conn = self.transport.establish_connection() File "/usr/local/lib/python3.8/site-packages/kombu/transport/pyamqp.py", line 201, in establish_connection conn.connect() File "/usr/local/lib/python3.8/site-packages/amqp/connection.py", line 323, in connect self.transport.connect() File "/usr/local/lib/python3.8/site-packages/amqp/transport.py", line 129, in connect self._connect(self.host, self.port, self.connect_timeout) File "/usr/local/lib/python3.8/site-packages/amqp/transport.py", line 184, in _connect self.sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/bin/celery", line 8, in <module> sys.exit(main()) File "/usr/local/lib/python3.8/site-packages/celery/__main__.py", line 15, in main sys.exit(_main()) File "/usr/local/lib/python3.8/site-packages/celery/bin/celery.py", line 217, in main return celery(auto_envvar_prefix="CELERY") File "/usr/local/lib/python3.8/site-packages/click/core.py", line 1130, in __call__ return self.main(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/click/core.py", line 1055, in main rv = self.invoke(ctx) File "/usr/local/lib/python3.8/site-packages/click/core.py", line 1657, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/usr/local/lib/python3.8/site-packages/click/core.py", line 1404, in invoke return ctx.invoke(self.callback, **ctx.params) File "/usr/local/lib/python3.8/site-packages/click/core.py", line 760, in invoke return __callback(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/click/decorators.py", line 26, in new_func return f(get_current_context(), *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/celery/bin/base.py", … -
django jsonresponse data not showing in django templates javascript
I am trying to get JSON data in django templates javascript. It working on the views.py file but in javascript it's not showing data def home(request): ModList=model.objects.all() brands=brand.objects.all() searchproducts=request.GET.get('Search') social_link=socialLinks.objects.all() if searchproducts!='' and searchproducts is not None: brands=brand.objects.filter(title__icontains=searchproducts) data={ 'jsondata':JsonResponse(list(brand.objects.values()), safe=False), 'brands':brands, 'ModList':ModList, 'social_link':social_link } return render(request, 'firmApp/home.html', data) In my views function, I parse jsondata to home.html. But in the home.html script, it is not working <script> const data='{{jsondata}}' console.log(data) </script> when I console data it shows below in console &lt;JsonResponse status_code=200, &quot;application/json&quot;&gt; this is not correct data. -
I still get You are seeing this page because DEBUG=True is in your settings file and you have not configured any URLs
thats my app urls from django.urls import path from . import views urlpatterns = [ path('', views.tasklist, name='tasks'), ] thats my projects urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('list.urls')), ] thats views urls from django.shortcuts import render from django.http import HttpResponse def tasklist(request): return HttpResponse('TO DO List') I tried a lot of things but none of them worked -
Django pk for not corresponded user
I got a school and many teachers. While one to many works for the user group I have a staff group which needs to see all teachers corresponding to their school. But while everything is connected via pk, the staff dont see any teacher bc they dont have a pk for that data, how is it possible to have pk data and also display all of it, while editing deleting is possible for staff WITH a pk so that the edited data is correct etc. -
How to use local sqlite on Heroku
I am trying to deploy a Django app on Heroku, but I want to use my local sqlite as the application DB and not postgres. I know that it sounds weird but that's what I need now. I am trying to understand how to not overwrite my DB settings and keep them pointing at my local sqlite and not to Heroku's postgres. Any idea? -
Send email with data of an incomplete Django ModelForm
I have a rather large Django ModelForm on my website. Some of my visitors claim that the form does not work. I assume that they missed a required field, but their browser somehow does not show them which field is missing. Therefore, I want to send an email to myself when users try to submit an incomplete form such that I can better understand what is going on. My idea was: def signup(request): if request.method == "POST": ... if form.is_valid(): # Save content else: # Form not valid but send mail send_mail(...) However, we never get to the else part when we miss a required field of the form as the browser handles this earlier (view jumps to the missing field and no POST request is made). Any ideas? Maybe additional Javascript on the submit button of the form? -
Label on radio select updates wrong object
In my project there is a form which is displayed beneath each object in a list. The objects in this case are ideas. The form is there to enable to user to rank each idea from 1 to 3. The form uses radio buttons with a little label beside it. It goes from "good" "so so" and "bad", where "good" is 1 and so on. Everything works as it should, except that when the label is pressed on any idea instead of the radio button. The first idea in the list is being updated, not the one the user intended to update. This is my form: class IdeaRankForm(forms.ModelForm): CHOICES = [ (1, 'Good'), (2, 'So so'), (3, 'Bad'), ] rank = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect(attrs={'onchange': 'submit();'})) class Meta: model = Idea fields = ['rank', ] I tried both this and this. Essentially the same suggestion but none of the suggested solutions solved my problem. Does anybody know how this can be solved? Is javascript needed in the template to solve this? Or is there any way where the label can be disabled and not being able to be pressed? -
django channel took too long to shut down and was killed
I'm having this error when refreshing or after disconnecting the WebSocket. In my consumer async def connect(self): await self.accept() while True: //some function// async def receive(self, event): print("Receive", event) await self.send({ "type": "websocket.send", "text": "From receive..." }) async def disconnect(self, event): print("Disconnect", event) await self.send({ "type": "websocket.close" }) -
Best framework for CURD operations - Django vs Flask vs FastAPI
Am in the process of building web frame work. The web application should retrieve the data from the database and display. As well as insert/ update process should also be supported from the front end. Am looking for a best python based web frame work, the requirement is pretty simple. Need an assistance to choose the right frame work. Django Flask FastAPI I have gone through all the documentations of these frameworks, each has its own limitations and functionalities. Any assistance will be helpful. -
I want to add range filter in django eg.(100-500)
I've applied django filters on my data but there is a data on which I want to apply range filter like a data between (100-1000). -
How to call call a static function from the same Model in the Model upon initialisation? DJANGO PYTHON
So long story short, I have a Car model and a CarVersion model and I want the user to have the ability to choose from the availble car versions saved in the database, through a html select field. I cannot understand how to dynamically generate the choices field from the CarVersion model. I have the function, but I cannot call it inside the Car model. Here is the code I have so far: class Car(models.Model): choices = get_choices() name = models.CharField(max_length=50, unique=True) version = models.ForeignKey(CarVersion, choices=get_choices(), on_delete=models.RESTRICT) @staticmethod def get_choices(): options = CarVersion.objects.all().values_list("pk", "name") try: if not options: return [(0, "No versions in database. Call your administrator.")] except ProgrammingError: return [(0, "No versions in database. Call your administrator.")] return [(1, "Test")] I want to call the function get_choices in version = models.ForeignKey(CarVersion, choices=get_choices(), on_delete=models.RESTRICT) but I don't know how to do that while the function is declared to the model. If I define it outside of the model, it works, but there must surely be a better way that im missing, rather than cluttering my models.py file with a bunch of model specific functions. P.S.get_choices is not finished but as soon as I can call it, I will deal with … -
Setting a project level django constant
In my application, there is one configuration I am setting in my db (let say buffer_radius) that is not going to change frequently. I want to set one constant BUFFER_RADIUS in Django so that every-time Django restarted/redeployed, the value of this constant set to buffer_radius. I want to do this to minimise db call. -
one-to-one relationship but of multiple types in Django
I'm creating an online shop with Django. I figured since there could be different types of item for sale that share some attributes and fields, I'd better make an Item Model and other models subclass it. So I now have an abstract Item model and some other models like Dress, Pants and shoes. Now I wanna have a new model (e.g. Comment) which should have a relationship with the Item model. But since Item model is abstract I can't do it. Is there way I could have a one to one relationship whose one side could accept different types? Some thing like this: class Comment(models.Model): item = models.ForeignKey(to=[Dress, Pants, Shoes]) -
Djongo DB of MongoDB crashed suddenly in Django
I was using MongoDB as my Backend Database which was working perfectly today until now!. I didn't make any changes, yet suddenly every time i run server, I get this error. can't even debug what's the issue here. I really haven't made any change in Django yet this is happening. please help me figure this out! Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Meraz\anaconda3\lib\site-packages\djongo\sql2mongo\query.py", line 808, in __iter__ yield from iter(self._query) File "C:\Users\Meraz\anaconda3\lib\site-packages\djongo\sql2mongo\query.py", line 166, in __iter__ for doc in cursor: File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\cursor.py", line 1238, in next if len(self.__data) or self._refresh(): File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\cursor.py", line 1130, in _refresh self.__session = self.__collection.database.client._ensure_session() File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\mongo_client.py", line 1935, in _ensure_session return self.__start_session(True, causal_consistency=False) File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\mongo_client.py", line 1883, in __start_session server_session = self._get_server_session() File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\mongo_client.py", line 1921, in _get_server_session return self._topology.get_server_session() File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\topology.py", line 520, in get_server_session session_timeout = self._check_session_support() File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\topology.py", line 504, in _check_session_support self._select_servers_loop( File "C:\Users\Meraz\anaconda3\lib\site-packages\pymongo\topology.py", line 218, in _select_servers_loop raise ServerSelectionTimeoutError( pymongo.errors.ServerSelectionTimeoutError: ac-qk5nrrk-shard-00-02.bppaqzd.mongodb.net:27017: ,ac-qk5nrrk-shard-00-00.bppaqzd.mongodb.net:27017: ,ac-qk5nrrk-shard-00-01.bppaqzd.mongodb.net:27017: , Timeout: 30s, Topology Description: <TopologyDescription id: 62fd16f8972a661b8168f504, topology_type: ReplicaSetNoPrimary, servers: [<ServerDescription ('ac-qk5nrrk-shard-00-00.bppaqzd.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-qk5nrrk-shard-00-00.bppaqzd.mongodb.net:27017: ')>, <ServerDescription ('ac-qk5nrrk-shard-00-01.bppaqzd.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-qk5nrrk-shard-00-01.bppaqzd.mongodb.net:27017: ')>, <ServerDescription ('ac-qk5nrrk-shard-00-02.bppaqzd.mongodb.net', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ac-qk5nrrk-shard-00-02.bppaqzd.mongodb.net:27017: ')>]> The above exception was the … -
How can I update my data table in page without refreshing page when I do db changes?
[NOTE] I'm really new to web development. I'm trying to figure out how to make things. Sorry about that with basic questions. But I'm totally lost. That's why I'm asking. I'm trying to update my data page without reloading. I have to do this with AJAX, but most of examples about clicking the button and adding or updating the table. I don't want to create button, I want to reload with adding new record in database. I'm using Django, when I add new blog post in admin page for example, I want to see this blog post in my page without refreshing or clicking any button. Do I have to write API for this? How can I write this API for watching db? Do you have any resources with this? Thank you for your answers. -
django 4.1 tutorial how to change the link on the admin page header from http://localhost:8000 to http://localhost:8000/polls/
In the Admin pages of the Polls Tutorial there is a link to "View Site" that has the URL http://localhost:8000/ but it should be http://localhost:8000/polls/ to list the polls in the indexView class. I could not find where to change that View Site link. Right now with the Polls Tutorial done and all working except this last little bit I want to get it done to use as a reference. http://localhost:8000 now gives... Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: polls/ admin/ The empty path didn’t match any of these.