Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can Django queryset generate a SQL statement with self join?
I have a table that relates parents to children, it has the following data: +-----+-----+-----+--------+ | pid | rel | cid | relcat | +-----+-----+-----+--------+ | 13 | F | 216 | 1 | | 13 | F | 229 | 1 | | 13 | f | 328 | 2 | | 13 | F | 508 | 1 | | 13 | F | 599 | 1 | | 13 | f | 702 | 2 | | 560 | M | 229 | 1 | | 560 | m | 702 | 2 | +-----+-----+-----+--------+ I can find brothers of 229 by joining npr table to itself with SQL: SELECT npr_a.cid, CASE (SUM(IF(npr_a.relcat=1 AND npr_b.relcat=1,1,0))) WHEN 2 THEN '~FB~' WHEN 1 THEN '~HB~' ELSE '~Foster~' END AS BrotherType, abs(person_details.isalive) as isalive FROM person_details, npr npr_a, npr npr_b WHERE ( npr_b.cid = 229) AND ( npr_a.pid = npr_b.pid ) AND ( npr_a.cid <> 229) AND ( npr_b.relcat <> 3 ) AND ( npr_a.relcat <> 3 ) AND ( person_details.id = npr_a.cid ) GROUP BY npr_a.cid; to get: +-----+-------------+---------+ | cid | BrotherType | isalive | +-----+-------------+---------+ | 216 | ~HB~ | 1 | | 328 | ~Foster~ | … -
Django prefetch_related and inheritance
I am running into an issue with prefetch_related on a property of an inherited model.- In models.py I have: class Security(models.Model): name = models.TextField() ...other fields class Fund(Security): ...other fields @property def underlying_security(self): return self.maps_when_mapped.get().original_security_id class SecurityToSecurityMap(models.Model): original_security = models.ForeignKey(Security, related_name="maps_when_original") mapped_security = models.ForeignKey(Security, related_name="maps_when_mapped") and in serializers.py class UnderlyingSecuritySerializer(serializers.Serializer): id = serializers.IntegerField() name = serializers.CharField() class FundSerializer(serializers.ModelSerializer): underlying_security = UnderlyingSecuritySerializer(read_only=True, allow_null=True) class Meta: model = Fund fields = ("id", "name", "underlying_security") Now, I when I am quering fund objects: queryset = Fund.objects.prefetch_related("maps_when_mapped__original_security") Django ignores prefetching. Experimented with `Prefetch, tried moving property to the parent - no luck, still getting hundreds on queries. Any way this can be optimised? I am using Django 2.2 with Postgres 11 -
css broken after extending templte django
I'm quite new to django and I'm trying to build my first website. I've read that we can use template so they are used in several pages. I create my own template and then tried to extend it in a few pages. I have a login/register page. The view worked perfectly but when I extended the template, css broke and I do not have my body customized anymore (so no css). Any idea on how to fix it ? By the way, my template is a header that includes a nav bar. And i used a : {% block content%}{% endblock %} At the end of my template My register page looks like this: Any idea why my css not working anymore ? -
Sending email in Django throws Address family not supported by protocol exception
I'm sending emails using Django version 2.2 and have tested it on the local machine and it works. But the same code throws [Errno 97] Address family not supported by protocol exception. I also couldn't find any solution online. I have rechecked my code and there is nothing wrong in it. I'm using google smtp server with app_password. Below are Details. settings.py file EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = "*******@gmail.com" EMAIL_HOST_PASSWORD = "app_password" Email Sending Function subject = 'Account Password reset mail' ctx = { "user" : self.user, "website" : settings.WEBSITE_NAME, "site_url" : settings.WEBSITE_URL, } msg = render_to_string('login/forgot_password_email.html',ctx) from_email = settings.WEBSITE_ADMIN_EMAIL to_email = [self.cleaned_data.get('email'),] result = send_mail(subject, '', from_email, to_email, fail_silently=False, html_message=msg) return result I even try to login to server through SSH and execute through the shell but returns the same error. >>> from django.core.mail import send_mail >>> res = send_mail('Subject here', 'Here is the message.', 'example@gmail.com', ['example@gmail.com'], fail_silently=False,) Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/y6d62pncrpga/virtualenv/public_html/django/app2/3.7/lib/python3.7/site-packages/django/core/mail/__init__.py", line 60, in send_mail return mail.send() File "/home/y6d62pncrpga/virtualenv/public_html/django/app2/3.7/lib/python3.7/site-packages/django/core/mail/message.py", line 291, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/y6d62pncrpga/virtualenv/public_html/django/app2/3.7/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 103, in send_messages new_conn_created = self.open() File "/home/y6d62pncrpga/virtualenv/public_html/django/app2/3.7/lib/python3.7/site-packages/django/core/mail/backends/smtp.py", line 63, in open … -
How to print a receipt from a POS-system made in django from a webserver?
I've tried to print from an Epson printer in my django project using the python-escpos module on localhost. The problem is that the text size is either too small or too large. Text size 1 is very small and text size 2 is too large as the text doubles from size: 1 to size: 2. Can the problem be solved in the same module or is there a need for another module and which module could I otherwise use in django on a Linux machine? The second problem is when I deploy the project to a Linux-webserver, then how can the web server connect to the local printer from the website? And is it possible to install a universal driver for all printers on the web server or does a driver need to be installed for each printer locally on each client machine? Any help would be appreciated - thanks in advance! -
Prevent Duplicated user entries - Django
I'm working on a crud operation that corresponds to multiple users. Whenever I hit the update function, a new entry is being added without modifying the existing one. Can someone help me out with this? views.py def employee_form(request,id=0): if request.method == 'GET': if id == 0: # req = request.user.designation form = EmployeeForm(request) else: employee = Employee.objects.get(pk=id) if employee in request.user.employee.all(): form = EmployeeForm(request,instance=employee) else: return redirect('/emp') return render(request,'employee-form.html',{'form':form}) else: if id==0: form = EmployeeForm(request,request.POST) if form.is_valid(): print("Im passed") name = form.cleaned_data["name"] contact = form.cleaned_data["contact"] designation = form.cleaned_data["designation"] t = Employee(name=name,contact=contact,designation=designation) t.save() request.user.employee.add(t) else: employee = Employee.objects.get(pk=id) if employee in request.user.employee.all(): form = EmployeeForm(request,request.POST,instance=employee) if form.is_valid(): print("Im passed") name = form.cleaned_data["name"] contact = form.cleaned_data["contact"] designation = form.cleaned_data["designation"] t = Employee(name=name,contact=contact,designation=designation) t.save() request.user.employee.add(t) return redirect('/emp') I pretty much understand it's creating a new entry because of request.user.employee.add() I've tried making it update(), It threw an error update() has only 1 positional argument. -
PATCH AJAX Request to Django API View returns 405 (Method not allowed)
I am having issues making a PATCH request to my django backend. I'm utilizing Ajax to submit the request but I get a 405 Method Not Allowed response and I'm not sure why. I've noticed others have had issues with the urls, but I'm pretty sure this is not a problem in my case. Below is the Ajax request, the urls, and the view (which doesn't do anything at the moment). Thanks in advance. Ajax Request $jQuery.ajax({ url: "{% url 'definitional_phrase_update' 1 %}", data: {'definition': 'update_definition' }, cache: false, contentType: false, processData: false, type: 'PATCH', success: function(data){ window.location = "{% url 'definitional_phrase_review' %}"; } }); Urls url(r'^def/definitional_demo$', views.definitional_demo, name='definitional_demo'), url(r'^def/definitional_upload$', views.definitional_patient_upload, name='definitional_upload'), url(r'^def/definitional_view/(?P<report_id>[0-9]+)/$', views.definitional_view, name='definitional_view'), url(r'^def/definitional_phrase_review$', views.definitional_phrase_review, name='definitional_phrase_review'), url(r'^def/definitional_phrase_update/(?P<term_id>[0-9]+)/$', PhraseReview.as_view(), name='definitional_phrase_update') Simple View class PhraseReview(APIView): def update(self, request, *args, **kwargs): print("here") -
Django multiple dropdowns showing model objects
I want to have multiple dropdowns, each showing the available objects from one specific model. So Dropdown 1: Apples Oranges Pears and, Dropdown 2: Apples Oranges Pears etc. The bonus question is to have these dropdowns linked/be dependent so that as the user selects items, these chosen items are removed from the remaining dropdowns. Is this possible? -
how to write __str__ func in this case?
i have a 'user' model that have a OneToOneField to User Model and another model named 'user_agent' that have a foreign key to 'user' model. how can i use 'first_name' and 'last_name' in the str func?! class users(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, default='') user_type = models.ForeignKey(types, on_delete=models.SET_NULL, blank=True, null=True) mobile = models.CharField(max_length=20) active_code = models.CharField(max_length=50, blank=True) date_send_active_code = models.DateField(default=now, blank=True) count_send_active_code = models.IntegerField(default=0) token = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class user_agent(models.Model): user = models.ForeignKey(user_models.users, on_delete=models.CASCADE) agent = models.ForeignKey(agents, on_delete=models.CASCADE) parent = models.ForeignKey("self", on_delete=models.CASCADE, default='1') def __str__(self): return "(" + self.user.first_name + " " + self.user.last_name + ")" -
Is there a way I can filter by any one of x in a django query
In my webwapp, I would like the user to be able to filter search results by selecting categories from the sidebar. The data GET request in the view retrieves the list of selected options and are parsed out. This data to filter by is then separated into lists, as shown in the following snippet from Index in views.py: class Index(View): def get(request): ... some checks to ensure its a valid request... if valid: dietTypeList = request.GET.getlist('diettype[]') #['meat','vegetarian',...] categoryList = request.GET.getlist('categories[]') #['Italian','Western',...] .... return render(request,'results.html',context_dict) .... I would then like to filter the results within the .filter() filter function so that my results are any of the selected categories, with any of the dietary types applied to those categories. I have looked into Q queries however im not sure how to do the following in any case How do I effectively do the following: results = Recipe.objects.filter(Q(name__contains=searchCriteria) & Q(category=any of categoryTypeList )) -
django rest_framework. desirialize bytes represented as string from json response
Actually, I'm not sure how rest_framework serialize my bytes Data, it's assumption. I was trying to find how it works, but nothing happened. I think for my deserialization process it isn't important because it's already represented somehow bytes and i need to find a way how to deserialize it. I use: python 3.8.0 Django 3.0.3 djangorestframework 3.11.0 My code: root urls file from django.contrib import admin from django.urls import path, include from django.conf.urls import url from rest_framework import routers import rest_framework from AccontsCenter.views import AccountViewSet from rest_framework.serializers import HyperlinkedModelSerializer from django.contrib.auth.models import User, Group class UserSerializer(HyperlinkedModelSerializer): class Meta: model = User fields = ["url", "username", "email"] from rest_framework.viewsets import ViewSet, ModelViewSet class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer router = routers.DefaultRouter() router.register(r"users", UserViewSet) router.register(r"accounts", AccountViewSet) urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('admin/', admin.site.urls), # path('accounts/', include('AccontsCenter.urls')), # path('proxies/', include('Proxies.urls')), # url(r'^', include(router.urls)), # url(r'^api-auth/', include("rest_framework.urls", namespace="rest_framework")) ] Account model is: import typing import inspect import os, sys import json from django.db import models from Accounts import FloodAccount from modules_simpified import loadFromModules # modules_obj_list = loadFromModules() class Account(models.Model): # on_add_acc_events: typing.List[typing.Callable] = [(name, obj) for name, obj in vars(modules_obj_list).items() if inspect.isfunction(obj)] on_add_acc_events = [] username = models.CharField(max_length=200) email … -
Virtual Code Studio debug . Django debugging not stopping on breakpoint
It's clear in the image, " print " can work when a breakpoint is existing my question -
Using my django remotely with a ubuntu server
I want to have access to my Django project from anywhere. For this reason, I have a Raspberry Pi with Ubuntu. If I run the command python manage.py runserver, it runs the project in http://127.0.0.1:8000/ as default. But this is the localhost of my raspberry/ubuntu and what I want is run the project on my laptop. for this reason I change the 127.0.0.1 for the adress of my server http://xxx.xx.xx.x:8000/ and I run it on my browser. THIS FAILS. Ok, reading some information I see that I have to open a port to access remotely, for this goal I use the ufw library. I open the 80 port using ufw, Now if I write http://xxx.xx.xx.x:80 on my browser, don't fail, appear this, Thus I understand that now is opened. The problem is that if now I run again my django project as python manage.py runserver 80 and I write again http://xxx.xx.xx.x:80/user_app/login/ in my browser, appears the following, What I'm doing wrong? I'm newbie and I don't know what I have to do. The objective is to be able to access the project remotely. Can somebody help me? Thank you very much. -
Django 3 TemplateDoes not exist
Even though I am providing correct path it still giving me an error. in this project have made custom user model so I am not able to understand where i am going wrong kindly guide as i am a beginner. thank you And also added the required paths in settings.I tried the same code even by using include method in urls,py but still failed kindly guide as of where exactly i am making mistake model.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class MyAccountManager(BaseUserManager): def create_user(self, aadhar, name, phonenumber, password=None): if not aadhar: raise ValueError("Must have aadhar number") if not name: raise ValueError("Must have name") if not phonenumber: raise ValueError("Must have phone number") user = self.model( aadhar = aadhar, name = name, phonenumber = phonenumber ) user.set_password(password) #user.save(user=self._db) user.save(using=self._db) return user def create_superuser(self, aadhar, name,phonenumber, password): user = self.create_user( aadhar=aadhar, name=name, password =password, phonenumber=phonenumber ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using= self._db) return user class Account(AbstractBaseUser): aadhar = models.CharField(verbose_name='aadhar',max_length=18,unique=True) name = models.CharField(max_length=50, unique=False) phonenumber = models.CharField(max_length=30) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD … -
Update objects with values of a different model joined by multiple columns with additional filtering on their FKs using Django ORM
Here is what my models look like: EntryGroup(models.Model): ... EntrySource(models.Model): entry_group = FK(EntryGroup) ... Entry(models.Model): entry_group = FK(EntryGroup) ... EntryItem(models.Model): entry = FK(Entry) attribute_1 = ... attribute_2 = ... ... EntryItemCandidate(models.Model): entry_source = FK(EntrySource) attribute_1 = ... attribute_2 = ... existing_entry_item = FK(EntryItem, null=True) ... I am trying to achieve the following functionality: Get all the objects from model EntryItemCandidate with specified field entry_source_id (FK EntrySource), and update their exitsting_entry_item field with id of object EntryItem that meets following criteria: EntryItem has the same values of fields attribute_1 and attribute_2 as EntryItemCandidate EntryItem's Entry has the same value of field entry_group (FK EntryGroup) as EntryItemCandidate's EntrySource field entry_group (FK EntryGroup) If there is no EntryItem meeting these criteria, exitsting_entry_item should be set to Null. I used to perform this operation iterating for each Entry, but it was way to slow (it would execute order of 10000s queries for each task). I then managed to perform this operation using SQL: update entry_item_caindidate set entry_item_candidate.existing_entry_item = entry_item.id from entry_item_candidate inner join entry_item on entry_item_candidate.attribute_1 = entry_item.attribute_1 and entry_item_candidate.attribute_2 = entry_item.attribute_2 inner join entry on entry.id = entry_item.entry_id inner join entry_source on entry_source.id = entry_candidate.entry_source_id where entry_source.entry_group_id = entry.entry_group_id and entry_item_candidate.entry_source_id = {param} … -
boost django aggregation on a list of objects
I have a model and getting data out of it with django queries. class carts: product_id = models.foreginkey('Product') count = models.IntegerField() price = models.IntegerField() I need total_price for list of products: list_of_prices = [] for product in products: list_of_prices.append(carts.objects.filter(product_id=product.id)\ .aggregate(total_price=Sum(F(count) * F(price)))) is there any way to get list_of_prices without for loop? gettign it with just one or two queries? -
Error in Sending form data to Django views through AJAX
I have a HTML form, which takes in input from the user. On clicking the submit button, form data needs to be sent to the views.py in a JSON format, through AJAX. I tried out something, but I am getting an error the JSON object must be str, not 'NoneType' . The JSON data is being loaded in the views.py through: form = json.loads(request.POST.get('form')) The data is returned in form of a dictionary called 'searchdata'. The form has an id of inputForm . the AJAX call I have written: $.ajax({ url : window.location.href, type : 'POST', cache : false, data:{form:JSON.stringify(formdata)}, success:function(res){ if(typeof res.searchdata != 'undefined'){ self.$dispatch('searchdataevent',res.searchdata); } if(typeof res.message != 'undefined'){ self.message = res.message; } self.loading = false; }, error : function(err){ self.message = 'Error communicating with server'; self.loading = false; } }); Where am I going wrong? Any help is appreciated. -
How to change the default value of STATIC_URL = '/STATIC/' in django?
I'm trying to serve my static files through AWS s3, but I can't change the value of STATIC_URL which remain equal to '/STATIC/', no matter what I type in the settings.py file. -
how could pass dynamic variable with static text in template custom tag in django
How could I use the dynamic parameter with static text in template to custom tag ? in view.py you can use this way to pass many parameters message = 'hello {} this is {}'.format(from_user, to_user) how could I translate above code to template.html code ? I want following condition with multi args for example like this : {% if users|is_user_authorised_to_view_page:'users/<page_id>/<username>/'.format(page.id, user.username) %} {# do this ... #} {% endif %} how could I do that? I searched but didn't find any solution , thanks in advance .. -
celery worker print all log even i have defined only error
I have setup celery in my project and i run worker using celery -A scraper_api worker -l error to print any error if there. But it is printing all logs. Please check below image. -
django registerring apps in INSTALLED_APPS
What is the difference between registering apps in the INSTALLED_APPS like 'nameOfApp' and 'nameOfApp.apps.NameOfAppConfig' Registering the app in the settings.py file -
How can I change the django-leaflet openlayers canvas?
I have a django-leaflet widget, but the widget shows some imagery instead of openlayers map, how can i change this on modelform? from django import forms from django.contrib.gis.forms import OSMWidget, PointField, ModelForm from leaflet.forms.widgets import LeafletWidget class YourMapWidget(LeafletWidget): geometry_field_class = 'geom' class ApartmentForm(forms.ModelForm): class Meta: model = Apartment fields = '__all__' widgets = {'geom': YourMapWidget()} -
Django admin TypeError during templating: missing 1 required positional argument: 'context'
I can't figure out where I'm going wrong here. The error happens during templating when trying to view the admin list and the admin change views. Django==3.0.4 from django.contrib import admin from . import models @admin.register(models.Order) class OrderAdmin(admin.ModelAdmin): list_display = ('id', 'customer_email', 'date', 'status') search_fields = ('id', 'customer_email') date_hierarchy = 'date' list_filter = ('status',) Here's the full traceback: Traceback (most recent call last): File "/home/my_project/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/my_project/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/my_project/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 143, in _get_response response = response.render() File "/home/my_project/venv/lib/python3.6/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/home/my_project/venv/lib/python3.6/site-packages/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "/home/my_project/venv/lib/python3.6/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/home/my_project/venv/lib/python3.6/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/home/my_project/venv/lib/python3.6/site-packages/django/test/utils.py", line 95, in instrumented_test_render return self.nodelist.render(context) File "/home/my_project/venv/lib/python3.6/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "/home/my_project/venv/lib/python3.6/site-packages/django/template/base.py", line 903, in render_annotated return self.render(context) File "/home/my_project/venv/lib/python3.6/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/home/my_project/venv/lib/python3.6/site-packages/django/test/utils.py", line 95, in instrumented_test_render return self.nodelist.render(context) File "/home/my_project/venv/lib/python3.6/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "/home/my_project/venv/lib/python3.6/site-packages/django/template/base.py", line 903, in render_annotated return self.render(context) File "/home/my_project/venv/lib/python3.6/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/home/my_project/venv/lib/python3.6/site-packages/django/test/utils.py", line 95, in instrumented_test_render return self.nodelist.render(context) File … -
want to make infinite scroll i have data of 7000 lines
''' $(window).scroll(function () { // End of the document reached? if ($(document).height() - $(this).height() == $(this).scrollTop()) { $.ajax({ type: "POST", url: "http://192.168.1.8:8099/quran_app/surah/display/", contentType: "application/json; charset=utf-8", data: '', dataType: "json", success: function (items) { $.each( items, function (intIndex, objValue) { console.log(intIndex, objValue) // $("#data").appendTo( "div") ; $("#data").appendTo("div"); } ); }, error: function (req, status, error) { alert("Error try again"); } }); } }); here is the HTML {% block container %} {% for ayah in all_ayah %} {{ ayah.text_simple }} {% for word in ayah.word_set.all %} {% for trans in word.wordtransliteration_set.all %} {{ trans.text }} {% endfor %} {% endfor %} {% endfor %} -
Django Framework
I am new and learning DRF, I'm struggling to get the titles of the specific tag that I want to query in the postman, can anyone shed a light on this where I did wrong below? Thank you models.py class BookTags(TimeStampedModel): class Meta: verbose_name = _('Tag') verbose_name_plural = _('Tags') ordering = ['-created'] book_tags = models.CharField( _(u'Tag Name'), max_length=255, null=False, blank=False, ) def __unicode__(self): return self.book_tags class Title(TimeStampedModel): tags = models.ManyToManyField( "BookTags", verbose_name=_('tags'), blank=True, ) serializers.py class TagSerializer(serializers.ModelSerializer): title_set = LibraryTitleSerializer(read_only=True, many=True) ## when True I get an empty list [{}, {}] when False gives me an error AttributeError: Got AttributeError when attempting to get a value for field `title_set` on serializer `TagSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Title` instance. class Meta: model = BookTags fields = ['title_set'] views.py class TagApiView(generics.ListCreateAPIView): serializer_class = serializers.TagSerializer search_fields = ['tags__book_tags'] filter_backends = (filters.SearchFilter,) queryset = Title.objects.all() I want to output titles when I search tags localhost:8000/api/tags/?search=Comedy when I hit that endpoint it should list all titles that has tag of Comedy [ {'book_tags': 'Comedy', 'title': "Title 1", }, {'book_tags': 'Comedy', 'title': "Title 2", } ]