Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set the range of the primary-key of django objects based on the foreign key range and is it advisable?
I have the below models: class Author(model): name = CharField(...) class Post(mode): author = ForeignKey(Author) title = CharField(...) Suppose we have at most 100 authors. So the primary key of the autors would be in the range of 1 to 100 I want the primary keys of the post model be based on the primary key of the author of the post. I mean, if the author's primary key is 34, then his/her posts primary keys be 34000001, 34000002, 34000003 is advisable to do this and how can I do it? -
Classification using a django app creating 'UnicodeDecodeError' error
I am getting a csv file as an input from the user and then loading a saved pickle file to perform classification. But i am getting errors like: UnicodeDecodeError at /home_/Link5/classification/ 'charmap' codec can't decode byte 0x81 in position 47: character maps to < undefined > Template file(Link5.html): <h3>Upload your file here for classification</h3> <form method="post" action="{% url 'classification' %}" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="file" accept=".csv"> <button type="submit">Upload File</button> </form> views.py: from django.shortcuts import render from django.shortcuts import HttpResponse import numpy as np import pandas as pd import pickle import os from sklearn.preprocessing import StandardScaler from sklearn.metrics import confusion_matrix def classification(request): if request.method == 'POST': file = request.FILES['file'] dataset=pd.read_csv(file) x=dataset.iloc[:,[2,3]].values y=dataset.iloc[:,4].values sc=StandardScaler() x=sc.fit_transform(x) #decision_tree_model_pkl = open('decision_tree_classifier.pkl', 'rb') decision_tree_model_pkl=open(os.path.dirname(os.path.realpath(__file__)) + 'decision_tree_classifier.pkl', "r") decision_tree_model = pickle.load(decision_tree_model_pkl) y_pred = decision_tree_model.predict(x) cm=confusion_matrix(y,y_pred) ans='<H1>TP=%d <br> TN=%d<br> FN=%d<br> FP=%d</H1>' % (cm[0][0],cm[1][1],cm[0][1],cm[1][0]) return HttpResponse(ans) return HttpResponse('') urls.py: from django.urls import path from Link5 import views urlpatterns = [ path('', views.Link5, name='Link5'), path('classification/', views.classification, name='classification'), ] -
How to change admin detail view?
I have a question about Django-Admin Detail View. I have some items in admin Django, and when I click on them, it will show up detail of that specific item. Every item has some status, which could be changed by the user. And now I am getting to the problem... I want to show only relevant fields, buttons, etc. which will depend on item status or type of person. Which part of code will I put in admin.py under the specific class to make it work? I tried something like this for superuser but it will not work. Can you please show me how to display only some fields based on user status or item status(field name: Status ... in models) class JournalEntriesAdmin(admin.ModelAdmin): list_display = ('EngagementCode', 'EngagementManager', 'EngagementIncharge') list_filter = ('published', 'EngagementCode') search_fields = ('EngagementCode', 'EngagementManager', 'EngagementIncharge') def show_relevant(self, obj): if request.user.is_superuser: fieldsets = ( (None, { # label 1: None 'fields': ( # dictionary ('EngagementCode', 'EngagementManager'), ) }), ('More details', { # under label 2 : More details 'classes': ('collapse',), # css-class : minimized 'fields': ( ('published'), ) }) ) -
TypeError: __str__ returned non-string (type NoneType) in django template
I am working on django models and templates. while rendering the html, got following error. Please any one, is this error from models or django templates. File "/dj2.1/lib/python3.6/site-packages/django/template/base.py", line 978, in render_value_in_context value = str(value) TypeError: __str__ returned non-string (type NoneType) -
Django: How to populate ForiegnKey field with a related name?
I have two models one BookModel and another AuthorModel. I basically want to create a foreign key field to BookModel for referencing it to the AuthorModel. And I have been able to establish this successfully. But when I retrieve an object/record of the BookModel I get the author id instead of the whole author object. How do I do that? Here's what I've in my code In models.py: class AuthorModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField('Name', max_length=255) pen_name = models.CharField('Pen Name', max_length=255) class BookModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField('Book Name', max_length=255) author = models.ForeignKey(Author, on_delete=models.CASCADE, blank=True, default='', related_name='book_authorid') In serializers.py: class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('id', 'name', 'pen_name') class BookSerializer(serializers.ModelSerializer): author = AuthorSerializer() class Meta: model = Book fields = ('id', 'name', 'author') -
Error: 'django.contrib.sites.models.Site.settings.RelatedObjectDoesNotExist: Site has no settings.'
On running python manage.py runserver I get no errors. System check identified no issues (0 silenced). October 09, 2019 - 07:58:46 Django version 2.2.4, using settings 'saleor.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. But when homepage is loaded I get this RelatedObjectDoesNotExist Error django.contrib.sites.models.Site.settings.RelatedObjectDoesNotExist: Site has no settings. Can you help direct me here or even just spotlight on anything that I might be missing? What I have already tried - Flushing the database - Dropping the database, creating database again, making and running migrations again. -
Django: Parameters in URLs .... which start with a slash
I use a regex for URL dispatching like described in the Django docs. r'^remote/(?P<slug>[^/]+)/call_rfc/(?P<rfc_name>.+)$' Unfortunately rfc_name can start with a slash! Example: https://example.com/remote/my_slug/call_rfc//MLK/FOO The rfc_name is /MLK/FOO. But this fails. Somewhere (I don't know yet if it is in the browser or in Django) the duplicate slash gets removed. What is the best practice to handle URL parameters which can start with a slash? -
Is is bad to implement NodeJS on the backend and use Node Child Process to run python? project: Algorithmic trader. Should I use just Django?
I am highly experienced with NodeJS, but not Python or Django. I want to manipulate API's in JS, but do all computational tasks in Python. Is this a good way to go about it, or should I take the time to learn django, and utilize that as my full-stack framework. -
Column is not being added to table Mysql using Django
The following diagram is from my database Database schema I have the following model that represents that schema: class Finalproduct (models.Model): idfinalproduct = models.AutoField(primary_key=True) idproduct = models.ForeignKey('Product',on_delete=models.CASCADE) idtaste= models.ForeignKey('Taste', on_delete=models.CASCADE) idpresentation = models.ForeignKey('Presentation', on_delete=models.CASCADE) idcategory = models.ForeignKey('Category', on_delete=models.CASCADE) cantidad = models.IntegerField(), class Meta: unique_together = (("idproduct","idtaste","idpresentation","idcategory"),) The cantidad field is not being added in my database table finalproduct. The following is the result of the migration in MySql: Mysql, table generated with model shown above I have tried deleting my database, migrations, and the problem is never solved. -
Django: send email via Office365
What I have: A domain purchased in webs.com (I'll call it contoso.com); An Office 365 account connected to that domain (my email address is something like john@contoso.com); A Django application hosted in Azure; What I want: I would like to configure Django in order to send emails using my john@contoso.com address. What I'v done: I tried this Django configuration: EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.office365.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'john@contoso.com' EMAIL_HOST_PASSWORD = 'xxxxxx' but it didn't work. So, just for a test, I tried the free Google SMTP server: EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'john@gmail.com' EMAIL_HOST_PASSWORD = 'yyyyyy' This time it works but, obviously, the email is sent from john@gmail.com and not from john@contoso.com. What's wrong in the previous configuration? Or maybe I need to make some changes in my Office 365 account? -
I would like to integrate google maps to my E-commerce website that is built on django framework
I have built my E-commerce website on django framework and i would like to integrate google maps to it. A buyer within my site should be able to specify the distance radius of the seller from whom they are comfortable to purchase from. So for example, a buyer can go to my site and from their location they can specify that whatever they are looking for should be from a seller who is within their specified geographical radius. So for example if they specify a 10Km radius, they should not see products from sellers who are 15Km away. A good example of what i am talking about is the Tinder app, where you can specify in the settings that you only want to see profiles within a specific geographical radius from your current location. I have never dealt with google maps that is why i have sought to get directions before i begin so that i do not post a code that cannot be understood here. Someone please point me in the right direction of how such a functionality can be integrated in django. Thank you. -
What exactly does the update() method here given that the if loop is giving an empty dictionary?
I don't understand what the dict_dictionary does to the email_ctx dictionary here, does it stay empty of is it overriding some data here? class EmailTemplateContext(Context): @staticmethod def make_link(path): return settings.MAILING_LIST_LINK_DOMAIN + path def __init__(self, subscriber, dict_=None, **kwargs): if dict_ is None: dict_ = {} email_ctx = self.common_context(subscriber) email_ctx.update(dict_) super().__init__(email_ctx, **kwargs) def common_context(self, subscriber): subscriber_pk_kwargs = {'pk': subscriber.id} unsubscribe_path = reverse('mailing_list:unsubscribe', kwargs=subscriber_pk_kwargs) return { 'subscriber':subscriber, 'mailing_list': subscriber.mailing_list, 'unsubscribe_link': self.make_link(unsubscribe_path), } -
i was unable to find the error in path i mentioned in django
i wanted to add two numbers .so i used request.get to get two values and then my code has to add the numbers and print the result on the server.but my terminal shows- Not Found: / [09/Oct/2019 18:07:30] "GET / HTTP/1.1" 404 2082 Not Found: /favicon.ico [09/Oct/2019 18:07:33] "GET /favicon.ico HTTP/1.1" 404 2133 i tried adding my appname in the INSTALLED_APP section too. urls.py from django.urls import path from . import views urlpatterns = [ path('add',views.add,name='add'), ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'calc', ] ROOT_URLCONF = 'new12.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] views.py from django.shortcuts import render from django.http import HttpResponse def add(request): val1=request.GET['num1'] val2=request.GET['num2'] res=val1+val2 return render(request,"result.html",{'result':res}) index.html {% extends 'base.html' %} {% block content %} <form action="add"> enter ist num: <input type="text" name="num1"><br> enter 2nd num : <input type="text" name="num2"><br> <input type="submit"> </form> {% endblock %} printing the result on server result.html {% extends 'base.html' %} {% block content %} {{result}} {% endblock %} base.html <html> <body bgcolor="red"> {% block content %} {% endblock %} </body> </html> -
use values in the queryset of modelmultiplechoicefield
i have a ModelForm like this: class CustomModelMultipleChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return obj.get_allowed_user_name class AddUserToPrivateCourseForm(forms.ModelForm): users = CustomModelMultipleChoiceField(queryset=None) class Meta: model = Course fields = [ 'users', ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['users'].queryset=User.objects.all() and the method get_allowed_user_name in model is def get_allowed_user_name(self): return "{} {} - {}".format(self.firstname, self.lastname, self.mobile) the database has around 60k users and loading this page is very long and takes about half a minute so i wanted to instead of capturing everything from db just use .values() and take just what is needed for form so if i use User.objects.values_list('firstname', 'lastname', 'mobile', 'id') it works ok and captures and generate what i need but the problem is it is unable to show already selected users and just shows a list of all users what should be done to generate options correctly? -
How can I store mathematical formulas with django
I'm working on a calculator that uses some mathematical formulas produced with multi linear regression. The problem here is this formulas should be constructed in dynamic way. With the admin interface the user can update and create formulas. The issue is how to model f= a0 +a1x + a2x^2.... and save all the data on the database(coefficients). And in the future we will have complex formulas. Is there like a library or better way to model the application to support these features. -
Axios put request not working properly with Django Rest Framework
From axios I have to make a put request to the DRF. In DRF I'm using APIView class-based view. Before I was getting 403 forbidden error when I was making put request. Because it was not sending csrftoken in the request. I googled it and went through the CSRF with Django, React+Redux using Axios stack overflow question and somehow I was able to fix 403 forbidden issue. Going through the above StackOverflow question I changed a few lines of codes and they are. In my axios file axios.defaults.xsrfHeaderName = "X-CSRFToken"; axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.withCredentials = true; In my project's settings. py file ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True But the wiered part is here when I pass any data to thorough put request from axios, it actually passing the flow to the APIView class (It's my assumption) from there I get a wired response. I could see that it sends the react's index.html as the data in the response. My views.py code class TestView(APIView): def put(self, request): print('inside put method') print(request.data) return Response('Test data passing in return') My Axios code import axios from "axios"; axios.defaults.xsrfHeaderName = "X-CSRFToken"; axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.withCredentials = true; return axios({ method: "put", … -
How do I correctly stack 2 slug models in the urls?
I have slugs set for my products and my categories, and when I click a product from my categories, my link goes from /shop/badges/ to shop/lakers, instead of shop/badges/lakers. Django spits out an attribute error. Generic detail view ProductDetailView must be called with either an object pk or a slug in the URLconf. My urls: urlpatterns = [ path('', CategoryView.as_view(), name='shop'), path('<slug:product_category>/', ProductListView.as_view(), name='products'), path('<slug:product_category>/<slug:product>/', ProductDetailView.as_view(), name='detail'), ] My get_absolute_url: def get_absolute_url(self): return reverse("products", kwargs={"product_category":self.slug}) return reverse("detail", kwargs={"product":self.slug}) I would like to have my urls implement each slug for category and badges stacked on top of each other, instead of just one when I click a product link. -
Django Middleware to Extend self.request for a social media apps
We know in Django, we can access to too many instances in self.request like self.request.user, self.request.data, self.request.authenticator etc I am trying to get self.request.mygroup writing custom middleware this is my models from django.contrib.auth.models import User from django.db import models class Person(models.Model): id = models.UUIDField( primary_key=True, default=uuid4, editable=False ) auth_user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='auth_user', ) class Group(models.Model): members = models.ManyToManyField( Person, related_name='group_members' ) I wrote this middleware and it is working fine: class GroupMiddleWare(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): person = Person.objects.filter( auth_user__id=request.user.id ).first() mygroup = Group.objects.filter( members__alias__in=[person.alias] ) request.mygroup = mygroup.first() response = self.get_response(request) return response Above middleware working fine but the problem is when I visit from incognito mode, I mean when I am not logged in, it throws me an error like AnonymouseUser doesn't have attribute self.request.user to handle this, I tried writing condition like if self.request.user.is_authenticated: but it occurs another error as same. I guess I crafted the middleware wrongly, Can anyone help me to extend self.request to get my own instance like self.request.mygroup? I am not getting what is the right way to write a middleware, i am very new in middleware I want self.request.mygroup should retun only authinticated user's group -
Django attribute module OS
I'm trying to intall Vataxia social network platform on my local windows machine, but I'm receiving message like. ERROR: Command errored out with exit status 1: command: 'c:\users\rade\desktop\vataxia\back\env\scripts\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Public\\Documents\\Wondershare\\CreatorTemp\\pip-install-mb9x0ep8\\uWSGI\\setup.py'"'"'; __file__='"'"'C:\\Users\\Public\\Documents\\Wondershare\\CreatorTemp\\pip-install-mb9x0ep8\\uWSGI\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base pip-egg-info cwd: C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-install-mb9x0ep8\uWSGI\ Complete output (7 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-install-mb9x0ep8\uWSGI\setup.py", line 3, in <module> import uwsgiconfig as uc File "C:\Users\Public\Documents\Wondershare\CreatorTemp\pip-install-mb9x0ep8\uWSGI\uwsgiconfig.py", line 8, in <module> uwsgi_os = os.uname()[0] AttributeError: module 'os' has no attribute 'uname' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. Anyone know how to fix it? -
Adding an autoincrementing model to django 1.11 with UUID as primary key
I have a legacy Django Application (1.11) which uses UUID as primary key, hence doesn't have an ID field. My DB is postgres class model_name(models.Model): .... #model data ... companyId = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) .... # Other model data I now need to add a human readable auto-incrementing identifier which will be used by users to refer to the records outside the system. The challenges are as follows: The system can have multiple entries being added simultaneously, so it needs to manage that without collisions ideally would need to add this to the save() method because new I have around 20000 records already in the database for this model. So whatever method I use, I will need to be able to add values for all previous records. I need to start numbering at 100,000 Is there a way to do this (Autofield may not work because its not going to be primary key and i already have n records in the system.) so it will remain consistent? -
How can i serialize that dictionary in Django?
{'test': , 'answers': , , , ]>, 'test_question': , 'test_button_list': [[{'number': 1, 'answered': False, 'correct': False}, {'number': 2, 'answered': False, 'correct': False}, {'number': 3, 'answered': False, 'correct': False}, {'number': 4, 'answered': False, 'correct': False}, {'number': 5, 'answered': False, 'correct': False}]], 'view': , 'form': } in my view: context = self.get_context_data() print(self.get_context_data()) html = render_to_string('difficult_test.html', context) if self.request.is_ajax(): return http.JsonResponse({"html":html, "context":context}) return response If i try to serialize i get this response: TypeError: is not JSON serializable -
Adding Bootstrap Modal (Dialogue window) to Django navbar
I want to add Bootstrap Modal to Navbar on Django. It works on documentaion page of official Bootstrap, but not in my Django project. Is that possible? <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> -
Is it possible to refer to acknowledged tasks after calling app.autodiscover_tasks() in django-celery?
In Django-Celery, is it possible to refer to a particular task after it gets discoverred with app.autodiscover_tasks() without explicitly reimporting it from a module? Something like app.discoverred_tasks.django_app1.task1? Are there any benefits of autodiscoverring other than printing a list of available tasks upon starting a celery worker? -
Decorator pattern to implement filtering and pagination in django api rest
I am trying to implement filtering and pagination in an rest api developed with Django and python. I need to choose when to use filtering, pagination, both or none of them in my endpoints. To do this, I have thought of combining a template pattern with a decorator pattern. This is my designed solution, when ModelViewSet is an abstract class provided by Django Rest Framework, DummyViewSet is my endpoint, and FilteringViewSetDecorator and PaginationViewSetDecorator are my decorators. This is my source code: class CustomView(viewsets.ModelViewSet): __metaclass__ = ABCMeta @abstractmethod def get_queryset(self, request, **kwargs): pass def serialize_queryset(self, queryset): print("CustomView: _serialize_queryset") serializer = self.get_serializer(queryset, many=True) return JsonResponse(serializer.data, safe=False) def list(self, request, **kwargs): print("CustomView: list") queryset = self.get_queryset(request, **kwargs) return self.serialize_queryset(queryset) class ViewSetDecorator(CustomView): __metaclass__ = ABCMeta def __init__(self, viewset): print("ViewSetDecorator: __init__") self._viewset = viewset def get_queryset(self, request, **kwargs): print("ViewSetDecorator: _get_queryset") return self._viewset.get_queryset(request, **kwargs) class FilteringViewSet(ViewSetDecorator): @staticmethod def __build_filters(params): filters = [] for key, value in params.items(): if key != 'limit' and key != 'offset' and value is not None and value != '': query_filter = {key: value} filters.append(query_filter) return filters def get_queryset(self, request, **kwargs): print("FilteringViewSet: _get_queryset") queryset = super(FilteringViewSet, self).get_queryset(request, **kwargs) filters = self.__build_filters(request.GET) for query_filter in filters: queryset = queryset.filter(**query_filter) return queryset class PaginationViewSet(ViewSetDecorator): … -
How can I set header in swagger_auto_schema?
I have a next code. How can I add header: {'Authorization': 'JWT Token'} In settings: SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'Bearer': { 'type': 'apiKey', 'name': 'Authorization', 'in': 'header' } }, 'USE_SESSION_AUTH': False }