Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to dynamically use different existing database in django
i have around ten to twenty databases with same structure in mysql, and how can i load those database dynamically in django? (there will be a table storing those databases name, which may add/delete during the programme) -
Django not redirecting to next page with in-built login view
I don't know what's happening with my code, once a user that is not authenticated tries to access a page and it redirects to the login page, I can see the next parameter in the browser but after the user logins, it takes the user to the default LOGIN_REDIRECT_URL and not the next page. Also on the template next returns none, so seems the template is not getting thee next value, but in the url it shows the /?next=, thanks in advance. urls.py from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from blog import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.HomeView.as_view(),name="index"), path('accounts/login/', auth_views.LoginView.as_view(), name='login'), path('accounts/logout/', auth_views.LogoutView.as_view(next_page='/'), name='logout'), path('accounts/profile/', views.ProfileView.as_view(), name='profile'), ] registration/login.html {% extends 'app/base.html' %} {% block link %} id="active" {%endblock%} {% block content %} <div class="row"> <div class="col-md-3"> </div> <div class="col-md-6"> <div class="jumbotron" id="font"> {% if next %} {% if user.is_authenticated %} <h2 class="customtext" align="center">Your account doesn't have access to this page. To proceed, please login with an account that has access.</h2> {% else %} <h2 class="customtext" align="center">Please login.</h2> {% endif %} {% else %} <h2 class="customtext" align="center">Enter your login details.</h2> {% endif %} <form action="{% url 'login' %}" method="POST"> … -
Automatically create django model instances at startup with empty database
My django project requires some model instances to be created at startup if they do not exist. I currently create the required model instances I need in an app config. class MyAppConfig(AppConfig): name = 'my_app' def ready(self): create_required_objects() def create_required_objects(): from my_app.models import MyObject for name in MyObject.reserved_names: if not MyObject.objects.filter(name=name).exists(): MyObject.objects.create(name=name, not_editable=True) This works perfectly when the sqlite database is initialized, however if I clear the database and then try to run the sever, I get the following error: django.db.utils.OperationalError: no such table: my_app_object I would like to be able to clear the database (preferably by just removing db.sqlite3) and run the server. -
Django DateTimeField received a naive datetime while time zone support is active
I'm using Django 2.2 In my application, timezone support is enabled by USE_TZ=True in the settings file. I have models with DateTime field created. I need to filter data based on the date. The date can be provided by the user or else it will be default to now(). This is what I'm doing from datetime import datetime, timedelta from django.utils import timezone class Generator: def __init__(self, start_date=None, end_date=None): if end_date: self.end_date = datetime.strptime(end_date, '%Y-%m-%d').date() else: self.end_date = timezone.now().date() if start_date: self.start_date = datetime.strptime(start_date, '%Y-%m-%d').date() else: self.start_date = self.end_date - timedelta(days=7) def get_query(self, d): query = MyModel.objects.filter( d__in=d, created__gte=start_date, created__lte=end_date ) return query But this is giving error RuntimeWarning: DateTimeField MyModel.created received a naive datetime (2020-02-28 00:00:00) while time zone support is active. How can I get this issue solved? -
Django: How to put each graphs on a page without saving it
I’m struggling to put several graphs created with Matplotlib on a page with saving it on memory. While single graph got success, one more graphs has failed. When I tried to embed two matplotlib graphs (graph1 and graph2) in a webpage, for instance, it were displayed one combined graph. In addition that, the designated color also didn’t work. Why? What I want to know is how to display each graph without integration. The following are my code Views.py Matplotlib graph are converted to binary data and saved on memory Each graph are connected to url parameter def graph(): #create graph and save it on memory buff=io.BytesIO() plt.savefig(buff, format='png') bute_file=buff.getvalue() buff.close return bute_file def test_graph(request,para): if para==1: #graph1 accounts=[6,2,3,6] label=['A','B','C','D'] col=['darkred','red','orange','gold'] plt.pie(accounts,labels=label,colors=col) chart=graph() plt.cla response=HttpResponse(chart, content_type='image/png') return response elif para==2: #graph2 accounts=[3,6,9] label=['E','F','G'] col=['blue','cyan','darkblue'] plt.pie(accounts,labels=label,colors=col) chart=graph() plt.cla response=HttpResponse(chart, content_type='image/png') return response else: #graph3 accounts=[5,1,2] label=['X','Y','Z'] col=['green','limegreen','yellowgreen'] plt.pie(accounts,labels=label) chart=graph() plt.cla response=HttpResponse(chart, content_type='image/png') return response url.py urlpatterns = [ path('test_view/',views.test_view, name='test_view'), path('test/<int:para>',views.test_graph,name='test_graph') ] html <div> <img src="{% url 'mysite:test_graph' 1 %}"> </div> <div> <img src="{% url 'mysite:test_graph' 2 %}"> </div> And here is the displayed page Changing para in test_graph() to 3,4 which does not exist on url parameter, the webpage showed exceptional … -
Unable to send email from Django Rest framework application
I am trying to send email via Django Rest framework application. The mail should be sent to the user who would register to our system using Gmail. I am also using docker images python:3.7-slim and MySql:5.6 First I have created email configurations inside the Django project setting.py file as stated below. # Email Settings. EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 456 EMAIL_HOST_USER = 'steinnlabs@gmail.com' EMAIL_HOST_PASSWORD = 'SteinnLabs@123!!*' EMAIL_USE_TLS = 1 EMAIL_USE_SSL = 0 This is how view.py file of application looks like. from __future__ import unicode_literals from django.shortcuts import render from . import views from rest_framework.views import APIView from django.db import IntegrityError from rest_framework import status from . import models, serializers from rest_framework.response import Response from django.core.mail import send_mail class UserAPIViews(APIView): """ """ def post(self, request, format=None): """ """ print(request.data) serialized_data = serializers.UserSerializer(data=request.data) if serialized_data.is_valid(): try: user_id = serialized_data.save() except IntegrityError as error: message = f"Email already exist." return Response ({ 'error_message' : message, 'status' : status.HTTP_226_IM_USED }) subject = 'Eitan - Case Manager Account Credentials' body = f"Hi {serialized_data.validated_data.get('first_name')} Your case manager account is ready. Please use following credentials to login. Email - {serialized_data.validated_data.get('email')}, Password - {serialized_data.validated_data.get('password')} Thank You! Team Eitan." sender = "steinnlabs@gmail.com" to = serialized_data.validated_data.get('email') send_mail(subject, body, sender, … -
Accessing an element in a dictionaty using another key
I have a dictionary: D = <Queryset[{'name' : 1 , 'id' : 3, 'val': 4}]> D here is list of dictionaries. I have an object which can fetch me id by using (s.game_id). By using s.game_id, I get '3' as its value, which is correct. However, this object doesn't have 'val' accessibility. I want to get the corresponding value of 'val' using 'id'. But, I am unable to do so and stucked. -
xhtml2pdf don't move elements in generated pdf
I create a pdf file and I need to move the elements, but it does not move. If you open the template, you can see that everything is moving. I need to raise the text so that it is higher than the images. Classes "stamp" and "podpis" it's images. <style> .table { display: table; } .table-row { display: table-row; } .table-cell { display: table-cell; border: 1px solid black; } .text { display: inline-block; vertical-align: top; } </style> <body> <div class="table"> <div class="table-row"> <div class="text"> Name: </div> <div class="table-cell"> <img class="stamp" src="{% link_callback supplier.image_dog.url %}" > </div> <div class="text"> {{ supplier.chief}} </div> <div class="text"> Seconf: </div> <div class="table-cell"> <img class="podpis" src="{% link_callback supplier.image_sign.url %}" > </div> <div class="text"> {{ supplier.chief}} </div> </div> </div> </body> -
Passing value to the Django view function from template
{% for key,value in ls.items %} {% if value == "1" %} <form id="myForm" action="/data_display/" method="post"> <input type="hidden" name="date_selected" value= {{ key }}> <a href="#" onclick="document.getElementById('myForm').submit();"><font size="+1">{{ key }}</font>><br>available</a> {% csrf_token %} </form> {% else %} <p> <font> {{key}} </font></br> not available </p> {% endif %} {% endfor %} Here, "ls" is the dictionary. I want to pass the "key" to Django views function. The value in the input tag does take different values of key during each for loop, but when I pass when I click on the link, it only passes the key of 1st element. For eg, suppose my dictionary is: {'2020_01_01': '1', '2020_01_02': '1', '2020_01_03': '0', '2020_01_04': '1', '2020_01_05': '0', '2020_01_06': '0', '2020_01_07': '0', '2020_01_08': '1', '2020_01_09': '0'} so when I click on any of the link, "2020_01_01,2020_01_02,2020_01_04,2020_01_08", every time only 2020_01_01 key passes to the view function. But I want that whenever I click on any other link like 2020_01_02, then 2020_01_02 should pass on the view function. -
How to create a PNG image from HTML page and save it to the database using Django?
I'm new to django. So basically i have created a card view in my HTML page. When i click download buttton, an image file (PNG) of the HTML card (as exactly shown in the picture) should be created and saved it to the database. The downloaded image should be in media/cardimage folder in django project. The image is shown below.(Screenshot)card image HTML code is shown below <div class="container"> <div class="col" > <div class="col-lg-4 d-flex align-items-stretch" > <div id="html-content-holder" class="card rounded-lg shadow bg-white rounded" style="width: 25rem; width: 50vw; margin:auto;"> <div class="overlay"> <img class="card-img-top" src="{% static 'images/ab_nba_040320.jpg' %}" alt="Card image cap"> </div> <!-- Card content --> <div class="card-body"> <!-- Title --> <div style="text-align: left;"> <h4 class="card-title font-weight-bold align-left"> <p style="font-size: 80%;">NBA: Davis sparks Lakers over Sixers with hot second quarter, LeVert hits career-best 51pts as Nets beat Celtics <a id="btn-Convert-Html2Image" class="fa fa-download" aria-hidden="true" style="cursor: pointer;" title="Download"></a> </p> </h4> <!-- Text --> <p class="card-text" style="font-size: 85%;">Anthony Davis produced a devastating burst of scoring, as the Los Angeles Lakers came from behind to defeat the Philadelphia 76ers 120-107 on Tuesday (March 3) in their National Basketball Association (NBA) game. He led the Lakers' surge with 37 points at the Staples Centre after the hosts … -
IDE showing me error on objects keyword in " latest_questions = Question.objects.order_by('-pub_date')[:10] "
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/polls/'polls/index.html Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ ^polls/ ^$ [name='index'] ^polls/ ^(?P[0-9]+)/$ [name='detail'] ^polls/ ^(?P[0-9]+)/results$ [name='results']he current path, polls/'polls/index.html, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
Unable to initialise a Docker contained API server database
The goal is to set up the Bullet Train API server running on local servers. I'm completely new to dockerization, so need some help As per the docs at Bullet Train API server which I have cloned on my local machine. When I run docker-compose up on my local machine, the server seems to be up and running. However, I get this warning: When I search the code, I can't see this string anywhere in the code. I have some questions here. How do I force this docker container to initialize the database? What is causing this skip of database initialization? -
Django Cactus - NotImplementedError
Im following this guide on how to deploy a django app using Cactus to Netlify: https://www.netlify.com/blog/2016/04/08/a-step-by-step-guide-cactus-on-netlify/#building-your-site However, when I try to start the local server, I get this error: > cactus serve c:\...\desktop\dev\virtualenvs\ab_vb_py_3.8\lib\site-packages\django-1.6.11-py3.8.egg\django\template\base.py:1119: DeprecationWarning: inspect.getargspec() is deprecated since Python 3.0, use inspect.signature() or inspect.getfullargspec() params, varargs, varkw, defaults = getargspec(func) c:\...\desktop\dev\virtualenvs\ab_vb_py_3.8\lib\site-packages\cactus-3.3.3-py3.8.egg\cactus\utils\internal.py:36: DeprecationWarning: inspect.getargspec() is deprecated since Python 3.0, use inspect.signature() or inspect.getfullargspec() return inspect.getargspec(obj) c:\...\desktop\dev\virtualenvs\ab_vb_py_3.8\lib\site-packages\cactus-3.3.3-py3.8.egg\cactus\utils\internal.py:45: DeprecationWarning: inspect.getargspec() is deprecated since Python 3.0, use inspect.signature() or inspect.getfullargspec() spec = inspect.getargspec(getattr(obj, FUNC_OBJ_ATTR)) Running webserver at http://127.0.0.1:8000 for C:\...\Desktop\DEV\ab_full_project\cactus\twentytwenty\.build Type control-c to exit Traceback (most recent call last): File "C:\...\Desktop\DEV\virtualenvs\ab_vb_py_3.8\Scripts\cactus-script.py", line 11, in <module> load_entry_point('Cactus==3.3.3', 'console_scripts', 'cactus')() File "c:\...\desktop\dev\virtualenvs\ab_vb_py_3.8\lib\site-packages\cactus-3.3.3-py3.8.egg\cactus\cli.py", line 159, in cli_entrypoint main(sys.argv[1:]) File "c:\...\desktop\dev\virtualenvs\ab_vb_py_3.8\lib\site-packages\cactus-3.3.3-py3.8.egg\cactus\cli.py", line 155, in main ns.target(**kwargs) File "c:\...\desktop\dev\virtualenvs\ab_vb_py_3.8\lib\site-packages\cactus-3.3.3-py3.8.egg\cactus\cli.py", line 65, in serve site.serve(port=port, browser=browser) File "c:\...\desktop\dev\virtualenvs\ab_vb_py_3.8\lib\site-packages\cactus-3.3.3-py3.8.egg\cactus\site.py", line 452, in serve self.server.start() File "c:\...\desktop\dev\virtualenvs\ab_vb_py_3.8\lib\site-packages\cactus-3.3.3-py3.8.egg\cactus\server.py", line 126, in start self._server.listen(self.port) File "c:\...\desktop\dev\virtualenvs\ab_vb_py_3.8\lib\site-packages\tornado-6.0.4-py3.8-win32.egg\tornado\tcpserver.py", line 152, in listen self.add_sockets(sockets) File "c:\...\desktop\dev\virtualenvs\ab_vb_py_3.8\lib\site-packages\tornado-6.0.4-py3.8-win32.egg\tornado\tcpserver.py", line 165, in add_sockets self._handlers[sock.fileno()] = add_accept_handler( File "c:\...\desktop\dev\virtualenvs\ab_vb_py_3.8\lib\site-packages\tornado-6.0.4-py3.8-win32.egg\tornado\netutil.py", line 279, in add_accept_handler io_loop.add_handler(sock, accept_handler, IOLoop.READ) File "c:\...\desktop\dev\virtualenvs\ab_vb_py_3.8\lib\site-packages\tornado-6.0.4-py3.8-win32.egg\tornado\platform\asyncio.py", line 100, in add_handler self.asyncio_loop.add_reader(fd, self._handle_events, fd, IOLoop.READ) File "C:\...\AppData\Local\Programs\Python\Python38-32\Lib\asyncio\events.py", line 501, in add_reader raise NotImplementedError NotImplementedError Thank you -
What is wrong with this Django code for template and model
so I'm trying to make dynamic pages with Django. I already have 'name', 'background', and 'introduction' data input in the admin page. And now I'm trying to show this to my '.../index' page. But it doesn't work. This is the python code for models.py class UserInfo(models.Model): name = models.CharField(max_length = 10) background = models.CharField(max_length=30) introduction = models.CharField(max_length = 60) and in my views.py file, I have this: def index(request): user = UserInfo.objects.all() return render(request, 'index.html', {'user' : user}) and finally in my 'index.html' file, I have this: <p>{{user.name}}</p> <p>{{user.background}}</p> <p>{{user.introduction}}</p> So these codes are supposed to show me the name, background, and introduction in '.../index' page, but it shows nothing. I don't see what I did wrong. I very much appreciate your help. :) Thanks. -
could not actually find how from_db_value works in django source code?
I have a some fields in my model where I am trying to apply encryption on all the fields. Each field encryption depends on the values of two other fields in that same model class. I am able to achieve the encrypted data. But I also need those two other fields in the same class to decrypt the other field values that is returned by the function def from_db_value(self, value, expression, connection, *args). I have read docs and source code, but I didn't see a proper explanation on these parameters in from_db_value(self, value, expression, connection, *args): 1. expression 2. *args I want to know, How and where we can supply these parameters. How else we can use that function. I know the function returns value from database in python object. But I want to know what else it can do or we can o with it? P.S: Yes, I am trying to make custom field classes. Inspiration: django-fernet-fields -
How to extend categories, 'parent-child' functionality from django oscar dashboard to oscars restful API for category?
In the oscar dashboard, I can make any root category, I can make children under a category. This functionality I am able to explore in the oscar Restful API. But I want to inherit the dashboard functionality, where we can make any category relative to another category. for example- I have 2 categories. 1) cat 1 a)subcat1 2)cat 2 now if I have to make subcat1 as a child of cat2 I can easily select from the dropdown and set 'subcat1' to cat2, in the oscar dashboard. But how can I do the same using Django oscar restful API? Please let me know. This is what I get from oscarapi for categories. which is http://localhost:8000/api/admin/categories/ serializers/admin/product.py class AdminCategorySerializer(BaseCategorySerializer): url = serializers.HyperlinkedIdentityField(view_name="admin-category-detail") children = serializers.HyperlinkedIdentityField( view_name="admin-category-child-list", lookup_field="full_slug", lookup_url_kwarg="breadcrumbs", ) def create(self, validated_data): breadcrumbs = self.context.get("breadcrumbs", None) slug = validated_data["slug"] if breadcrumbs is None: breadcrumbs = slug else: breadcrumbs = "/".join((breadcrumbs, slug)) try: instance = create_from_full_slug(breadcrumbs, separator="/") except ValueError as e: raise APIException(str(e)) return self.update(instance, validated_data) views/admin/product.py class CategoryAdminList(generics.ListCreateAPIView, CategoryList): queryset = Category.get_root_nodes() serializer_class = AdminCategorySerializer permission_classes = (APIAdminPermission,) def get_queryset(self): try: return super(CategoryAdminList, self).get_queryset() except NotFound: # admins might be able to create so hold the error. return Category.objects.none() def get_serializer_context(self): … -
django widget in forms is not working correctly
I'm using django widgets into my forms.py for the content field. But whenever I change the coloumn and rows in forms.py with the widgets it's not changing in the template. my forms.py: from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment content = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Text goes here', 'rows': '4', 'cols': '10'})) fields = ('content',) -
Getting a socketio client connection to receive a "signal only works in main thread" error
So, I am trying to make my django app automatically connect to socketio client when some conditions happen and parse data from it in order to thereafter send it to my own web socket and show on web page. When I'm using this code: views.py def match(request, match_id): match = get_object_or_404(Match, pk=match_id) context = {'match': match} if match.is_live: livescore = Livescore(match.match_id, ) context.setdefault('livescore', livescore) return render(request, 'myapp/match.html', context) to create this class' object: def socket(self): sio = socketio.Client() @sio.event def connect(): print("connection established") ready_data = {"listId": self.list_id} sio.emit("readyForMatch", json.dumps(ready_data)) @sio.event def log(data): # do stuff @sio.event def event(data): # do stuff @sio.event def disconnect(): print("disconnected from server") sio.connect("<websocket URI im trying to connect to for data parsing>") return sio and parse info with callbacks. So, when I create sio object from barely anywhere (views.py in this case) I receive this error: ValueError: signal only works in main thread So after I figure out this problem (if I do) I want to put this code into my django-cron class which will every time check whether the condition has been fulfilled, connect to socketio and store its instance somewhere else to operate with info I'm receiving and put it into my own … -
Django ListView pagination when passing multiple objects in queryset
I'm working on Django app and currently ran into a problem. I have my ListView as: class CategoryView(ListView): template_name = "categories.html" def get_queryset(self): ... ... queryset = {"category": parent, "items": items.all()} return queryset Is there any walkaround for paginating "items" from queryset dict? Because when I set paginate_by = xx I get error unhashable type: 'slice'. What is, from my understanding, and it's pretty obvious cause by the fact that it doesn't know what if I request to paginate "category" or "items". Thank you for every input. Michal -
Python support for data / task Parallelism along with Async processing
I am new to Python and quite keen to shift,owing to brilliant framework like Django, excelllent foundation libraries. Also the ML apis available out of box. I have researched a bit to understand the fundamental design and whether the future use cases can be met. Following are my technical use cases: System scalability is low, not more than 50 concurrent users at any point of time (peak load), average would be 30 users This is a planning and Optimization system, therefore every user executes a high latency call, where to provide an example each call may internally deal with data set of 1 million records, which needs to be further processed End result is either a filtered, paginated 100 records or some average calculations, thus not a heavy network pay-load during response. Though while executing select call in the DB there's a heavy network payload, if bought to the application memory. Design (To meet the technical use cases): For a technical pay load of 1 million divide a call into 10 / 20 async IO calls an thus aggregate the data at the application / backend layer Use in memory cache to make the IO faster for future calls, it … -
How can I filter out errors on sentry to avoid consuming my quota?
I'm using Sentry to log my errors, but there are errors I'm not able to fix (or could not be fixed by me) like OSError (write error) Or error that come from RQ (each time I deploy my app) Or client errors (which are client.errors) I can't just ignore them because I consume all my quota. How I can filter out this errors? Here some references for interested people. uwsgi: OSError: write error during GET request Fixing broken pipe error in uWSGI with Python https://github.com/unbit/uwsgi/issues/1623 -
Return foreign key model from other model (not model instance)
I have model like this: class B(models.Model): value = models.CharField(etc...) class A(models.Model): name = models.Charfield( fk = models.ForeignKey(B, etc...) I have no instance of A in my database, but I have few instances of B. What I want to do is to get all instances of B through A model (not instance, since I have none) in Django template. I was thinking, since model is an object, maybe we can pass it like we pass any other object and use it's attributes in some way. Example In views.py: def my_view(request): B.objects.create(value=1) B.objects.create(value=2) B.objects.create(value=3) return render(request, 'template.html', {'model_a': A} In template.html: ... {% for b in a.fk_set.all %} {{ b }} {% endfor %} ... renders as 1 2 3 I understand that's wrong, because there is no A instance and db don't know that B is related to A in any way. Question: Is there a way to get similar effect like I mentioned in the example? -
Matplotlib package not working in django application
I have matplotlib install in docker.But not working in matplotlib.pyplot is not working in django app -
css and other static files not working in django
The current project I've started working on, uses django 2.2 and most of the links are hardcoded. All static content is in folder named media and used in base.html as follows in base.html {% load staticfiles %} ---- using this as first line of base.html ....... ....... <head> <link href="/media/css/backoffice/font-awesome.min.css" rel="stylesheet" type="text/css"> </head> in settings.py STATIC_URL = '/media/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'media'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'media/') STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) I've also added following to the main urls.py file: from django.conf.urls.static import static urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Yet I'm not able to render the static file listed in the head section of base.html I've also experimented with commenting out static root and staticfiles_dir but it does not work -
Need help! I have followed the official tutorial of Django to make a poll app, but I couldn't go on
I have followed the tutorial to make the app, but after I changed the code from def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) to def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now (The code is at mysite\polls\models.py and the required changing action is on part 5 of the tutorial), I ran the py manage.py test polls, and then I got the error: the error feedback, and I also couldn't run the webserver. Could you please help me? The platform: Windows 10 Django version: 3.0.4 Python version: 3.8.2 The database is MySQL8.0 and the tutorial:tutorial my code files:enter link description here