Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I convert 2020-03-20T04:00:00.000Z string to DateTime in Django?
My datetime parameter is '2020-03-20T04:00:00.000Z'. How can I convert it to datetime & how can separate in date & time. -
Which is best to use for Data Science Project , Flask or Django?
Which one would be the best for Data Science Project ? Django or Flask .... I need to make a school management system and their I need to use Machine Learning Algorithms for Predictions and modeling .. I am confused whether to use Django or Flask? .. The web app will be fully loaded with different kinds of features and facilities . The web project will be very heavy loaded . So Kindly Please help me to choose and suggest which framework will be the best one for fully loaded web application and which one framework (Django or Flask) is more secure ? Thank You 😊 -
Production settings not available in celery task
My settings are structured like: /Settings/ - init.py - base.py - dev.py - prod.py The constant RANDOM_VAR is set in base.py My celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings.prod') app = Celery("tasks") app.config_from_object('django.conf:settings', namespace="CELERY") app.autodiscover_tasks() I have a file called fetchdata.py from django.conf import settings def fetchdata(source): print(os.environ['DJANGO_SETTINGS_MODULE']) print(settings.RANDOM_VAR) results in: app.settings.prod AttributeError: module 'app.settings' has no attribute 'RANDOM_VAR' Why is from django.conf import settings not loading the production settings. -
Access object value by other object value in template in Django?
This {{ category.id }} returns me 1 This {{ categories_counts.1 }} returns me data But {{ categories_counts.category.id }} doesn't work? Is it possible to access value by other object value? -
How do I redirect user to a dynamic page that displays the data he/she input in a form in Django?
I've just started learning Django, and ran into a problem. So I'm trying to make a user-specific page that shows the information of each user which he/she has input in the beginning. I have a form InputUserForm in ModelForm. Below is my function in views.py, which I intended to let the user input his/her information in url '.../inputuserinfo' and then trying to redirect him/her to a page that shows the information he/she input. def inputuserinfo(response): if response.method == 'POST': form = InputUserForm(response.POST) if form.is_valid: form.save() return HttpResponseRedirect("usermain/"+"%i" %UserInfo.authuser_id) *authuser is a ForeignKey connected to the User, in my model. Obviously I'm having trouble in the return part. As mentioned earlier, what I was trying to do was as soon as the user submits the form, a dynamic page with the information he/she has input would show up. I have usermain.html file, and path('usermain/<int:id>', ...) in my urls.py, but I cannot figure out what the problem is. I'm not sure if this is clear enough for you to understand, but this is the best I could explain with my limited knowledge in Django :( I very much appreciate your help! :) -
Django_filter on an apiview
I have been trying to use the Django_filter on an APIView, but it just does not work. I am trying to implement a filter search, on some fields on a model. below is how the model is set up class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=250) picture = models.TextField(null=True, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=255, unique=True, blank=True) class Skill(models.Model): name = models.CharField(max_length=60) subcategory = models.CharField(max_length=60, blank=True, null=True) created_on = models.DateTimeField(auto_now=True) updated_on = models.DateTimeField(auto_now_add=True) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.DO_NOTHING) the views.py set up is also as shown below from django_filters import rest_framework as filters class UserFilter(filters.FilterSet): email = filters.CharFilter(lookup_expr='icontains') name = filters.CharFilter(lookup_expr='icontains') profiles__skills = filters.CharFilter(lookup_expr='icontains') class Meta: model = User fields = ('email', 'name', 'profiles__skills') class ListUsersView(APIView, MyPaginationMixin): ''' Gets all the users in the database ''' queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [AllowAny] pagination_class = api_settings.DEFAULT_PAGINATION_CLASS filterset_class = UserFilter def get(self, request): page = self.paginate_queryset(self.queryset) if page is not None: serializer_context = {"request": request} serializer = self.serializer_class(page, context=serializer_context, many=True) return self.get_paginated_response(serializer.data) and finally my serializer.py class UserSerializer(serializers.ModelSerializer): slug = serializers.SlugField(read_only=True) class Meta: model = User fields = ('email', 'name', 'slug', 'picture') … -
Django Rest Framework: urls with multiple slugs
I am develping the API for my blog. Every articles is related to a category, then the url of an articles is like this: "<slug:slug_category>/<slug:slug_post>/". Now my blog run without API and the previous path working fine. I need to have the same path with the API, then I've created this api view: @api_view(["GET"]) def blogPost_details_apiview(request, slug_post, slug_category): try: object = BlogPost.objects.get(slug_post=slug_post, slug_category=slug_category) except BlogPost.DoesNotExist: return Response({"Error": { "code": 404, "message": "Article not found!" }}, status=status.HTTP_404_NOT_FOUND) if request.method == "GET": serializer = BlogPostListSerializer(object) return Response(serializer.data) and this is the code in urls.py: path('<slug:slug_category>/<slug:slug_post>/', views.blogPost_details_apiview, name="details-blogpost"), I see this error: FieldError at /api/blog/gis/corso-applicativo-di-base-sistemi-informativi-territoriali/ Cannot resolve keyword 'slug_category' into field. Choices are: attachment, attachment_id, category, category_id, contents, description, draft, header_image, highlighted, id, publishing_date, slug_post, tags, timestamp, title, updating_date What I've wrong? I'm using Django 2.2 -
How do i store multiple photos that the author uploads in a blog?
I am stuck with how do i store all the photos that the author places in various sections in a blog. Can i use the same model with some ImageField but then What if there are multiple photos! As one field stores only one photo. Or, is it better to create a separate model class, so that i can get all the photos in a blog by referencing. Even then, how will it store multiple photos? -
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.