Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
want to convert my sql query into django orm query
This is my query SELECT form_fields.label_name, entry_details.value, entry_details.entry_id FROM form_fields join entry_details on entry_details.field_id = form_fields.id WHERE form_fields.id in (21401, 21402) and entry_details.entry_id = 79; I am a entry level developer having problem to convert this qery into djago query.....please help me -
Django - count number of inline elements in class based view
I have 2 models: Product and ProductComponent. How can I count the number of components in each product so when I want to loop products in the template it will give me the title and the number of components per product? class ProductComponent(models.Model): name = models.CharField(max_length=255) related_product = models.ForeignKey(Product, on_delete=models.CASCADE') @property def count_components(self): return self.component_name.count() class Product(models.Model): title = models.CharField(max_length=400) views.py class TestView(ListView): template_name = "test.html" model = Product def get_context_data(self, **kwargs): context = super(TestView, self).get_context_data(**kwargs) context['product_list'] = Product.objects.filter(?) return context I managed to do something like this in admin but only in the ProductComponent admin page but not in the Product admin page. admin.py class TestViewAdmin(ImportExportModelAdmin): resource_class = TestViewAdminResource list_display = ('get_component_count',) def get_component_count(self, obj): return obj.related_product.related_product.count() What I want to do is to create a loop of products with a number of components that are related to this product. {% for product in product_list %} {{product.title}} - {{product.count_components}} {% endfor %} I'd appreciate any advice on how to achieve something like that. -
using Azure Application Insights in a dockerized Django
i'm trying to embed Azure’s Application Insights in a dockerized Django/AngularJS environment to cover the data flow from end to end. In order to do so, I Added opencensus corresponding libraries to my requirements.txt file: opencensus-ext-azure opencensus-ext-django opencensus-ext-requests opencensus-ext-logging opencensus-ext-postgresql Edit the logging section in my settings.py: LOGGING = { 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '%(asctime)s - %(levelname)s - %(processName)s - %(name)s\n%(message)s', }, }, "handlers": { "azure": { "level": "DEBUG", "class": "opencensus.ext.azure.log_exporter.AzureLogHandler", 'connection_string': os.getenv('CONNECTION_STRING'), }, "console": { "level": "DEBUG", "class": "logging.StreamHandler", "stream": sys.stdout, }, }, "loggers": { 'my-app’s-name’: { "handlers": ["azure", "console"] }, }, 'version': 1 } And initialized a Tracer instance to my views.py: from opencensus.ext.azure.trace_exporter import AzureExporter from opencensus.trace import config_integration from opencensus.trace.samplers import AlwaysOnSampler from opencensus.trace.tracer import Tracer import logging logger = logging.getLogger("my-app-name") logger.setLevel(logging.DEBUG) tracer = Tracer( exporter=AzureExporter( connection_string = os.getenv('CONNECTION_STRING') ), sampler=AlwaysOnSampler()) Now I have several questions Where and how should I create a span? Can I implement it before a function returns its result? I.e. @login_required(login_url='login') def query_xyz(request): if request.method == 'GET': work_date_str = request.GET.get('workDate') work_date = parser.parse(work_date_str).date() if work_date_str is not None else datetime.now().date() column = [i.replace(' ', '_') for i in request.GET.getlist('column')] filters = json.loads(request.GET.get('filters')) if request.GET.get('filters') else None limit = … -
How to select another array of data by subscript in a django for loop
I have a problem when transfering two list to a html in django. I hope that it will be a:1b:2Each of two data is paired. But it does not work. There have some demo codes, showing the same error. Absolutly,it has no error log,because the {{l2s.order}} is null,and the system does not throw error.Maybe my poor English makes it confusing,If there are any where no description clearly, please point out, I'll add the appropriate information。 Thanks for your help. # fake view def test(request): l1s = ["a","b","c","d","e","f"] l2s = ["1","2","3","4","5","6"] return render(request,'fake.html',locals()) # fake html {% for l1 in l1s% } {% with order=forloop.counter0 %} {{l1}}-{{l2s.order}} {% endfor %} -
It is not possible to migrate a new user element to the django table
I am faced with the problem that it is not possible to migrate the new user value to the database table. At first there were errors on related_name, but I fixed it, and now that this value cannot be zero, at the same time, if I write that null=True, then the user cannot be displayed in the records in the future. class Writehelp(models.Model): users = models.ForeignKey(User,on_delete = models.CASCADE,related_name='helpedman',null=False,verbose_name='Автор') titles = models.CharField(max_length=200, verbose_name='Заголовок', blank=True) descriptions = models.TextField(blank=True, verbose_name='Описание') createdtimes = models.DateField(auto_now_add=True, db_index=True, verbose_name='Дата создания') prices = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='Цена') course = models.IntegerField(null=True, blank=True, verbose_name='Курс') semestr = models.IntegerField(null=True, blank=True, verbose_name='Семестр') subjects = models.CharField(max_length=200, null=True, blank=True, verbose_name='Предмет') institutes = models.CharField(max_length=200, null=True, blank=True, verbose_name='Институт') However, when I migrated this model, there were no problems: class UploadFile(models.Model): user = models.ForeignKey(User,on_delete = models.CASCADE,related_name='file_created' ,verbose_name='Автор') title = models.CharField(max_length=200, verbose_name='Заголовок',blank=True) # uploadedfile = models.FileField(upload_to='files/',null=True, verbose_name='Файл') description = models.TextField(blank=True, verbose_name='Описание') createdtime = models.DateField(auto_now_add=True, db_index=True, verbose_name='Дата создания') price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='Цена') number_course = models.IntegerField(null=True, blank=True, verbose_name='Курс') number_semestr = models.IntegerField(null=True, blank=True, verbose_name='Семестр') subjectt = models.CharField(max_length=200, null=True,blank=True,verbose_name='Предмет') type_materials = models.CharField(max_length=200,null=True,blank=True, verbose_name='Тип работы') institute = models.CharField(max_length=200, null=True,blank=True, verbose_name='Институт') -
Can someone please explain this django code to me?
I don't understand order_qs[0] and the order.items.filter. I mean items is not a class manager, so I don't understand how it is able to work. Then, I thought only list can be accessed by index with [0], and besides that should only return one item. It seems order_qs[0] contains more than one item def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item = OrderItem.objects.get_or_create( item=item, user = request.user, ordered = False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] #check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() else: order.items.add(order_item) The models: class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.title}" class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add= True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return self.user.username -
'SearchUsers' object has no attribute 'count'
I have problem with this it keeps saying: 'SearchUsers' object has no attribute 'count' class PaginatedElasticSearchAPIView(APIView, LimitOffsetPagination): serializer_class = None document_class = None @abc.abstractmethod def generate_q_expression(self, query): """This method should be overridden and return a Q() expression.""" def get(self, request, query): try: q = self.generate_q_expression(query) search = self.document_class.search().query(q) response = search.execute() print(f'Found {response.hits.total.value} hit(s) for query: "{query}"') results = self.paginate_queryset(response, request, view=self) serializer = self.serializer_class(results, many=True) return self.get_paginated_response(serializer.data) except Exception as e: return HttpResponse(e, status=500) from django_elasticsearch_dsl import Document, fields from django_elasticsearch_dsl.registries import registry @registry.register_document class UserDocument(Document): class Index: name = 'users' settings = { 'number_of_shards': 1, 'number_of_replicas': 0, } id = fields.IntegerField() class Django: model = User fields = [ 'first_name', 'last_name', 'username', ] #views from elasticsearch_dsl import Q class SearchUsers(PaginatedElasticSearchAPIView): serializer_class = UserSerializer document_class = UserDocument def generate_q_expression(self, query): return Q('bool', should=[ Q('match', username=query), Q('match', first_name=query), Q('match', last_name=query), ], minimum_should_match=1) #urls from django.urls import path from search.views import SearchUsers urlpatterns = [ path('user/<str:query>/', SearchUsers.as_view()), ] I'm facing this issue for the last 3 days. Searched for the similar question on StackOverflow but nothing helped me. Any Help, Would be appreciated. Thanks in Advance :) -
How to implement an Unsubscribe Newsletter button using Django
I have implemented a Subscribe to newsletter feature in my project and its working completely fine. I wanted to implement Unsubscribe the newsletter button beside it. I'm not able to figure it out on how to do it? Could someone help me out with this! Thanks in advance!! Here is my code: views.py def subscribe(request): if request.method=='POST': form=SubscribersForm(request.POST) if form.is_valid(): form.save() messages.success(request,'Subscription Successful') return redirect('/subscribe') else: form=SubscribersForm() context={ 'form':form } return render(request,'base/subscribe.html',context) urls.py path('subscribe/',views.subscribe,name='subscribe') subscribe.html {% load crispy_forms_tags %} {% block content %} <!-- Add code from body here --> <div class="container"> <div class="row mt-5 pt-5"> <div class="col-md-4 offset-md-4"> {% for message in messages %} <div class="alert alert-success"> {{ message }} </div> {% endfor %} <div class="card" style="width:150%; justify-content:center; align-items:center;"> <div class="card-body"> <h3 class="sub-text">Subscribe to Newsletter</h3> <hr> <form method="POST"> {% csrf_token %} {{form|crispy }} <input class="btn btn-success btn-block mt-5" type="submit" value="Subscribe"> <input class="btn btn-danger btn-block mt-5" type="submit" value="Unsubscribe"> </form> </div> </div> </div> </div> </div> {% endblock %} models.py class Subscribers(models.Model): email=models.EmailField(null=True) date=models.DateTimeField(auto_now_add=True) def __str__(self): return self.email forms.py class SubscribersForm(forms.ModelForm): email = forms.EmailField(label='Email', widget=forms.EmailInput(attrs={'class': 'form-control my-2','placeholder': 'Enter your Email','type': 'email','name': 'email'})) class Meta: model=Subscribers fields=['email',] -
Can we edit right side actions bar in Django admin
I am currently working on a Django Application. I have used Django Jazzmin (a drop-in theme for django admin). I have customised Django admin upto a certain extent according to my needs. However, I want to edit the available actions when Admin navigates to the user model. As you can see in the screenshot below there are only four options available which are 'Save', 'Delete', 'Save and add another' and 'Continue editing'. However, I want to create one more action Fetch Data that makes an API call with current user's id as parameter and fetch the related data of the user to update existing database. Can we do this by changing admin actions? Or there is a better alternative or approach to achieve this solution? -
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?