Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Creating model managers does not work
Please help me ... I understand that the problem is very simple ... but I'm stuck! I Creating model managers class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Post(models.Model): ................... objects = models.Manager() published = PublishedManager() and this is what I get in the terminal >>> Post.objects.filter(publish__year=2020, author__username='sasa') <QuerySet [<Post: try>, <Post: 3 article>]> >>> Post.published.filter(publish__year=2020, author__username='sasa') <QuerySet []> >>> Post.object.filter... works correctly, but Post.published.filter returns an empty object This is not right? Where am I mistaken? -
Start docker image with python3.6.8 and django3.0.4 got pkg_resources.DistributionNotFound: The 'supervisor==3.0' distribution was not found
I upgraded from python 2.7 to python3.6.8 and django1x to django3.0.4. When I start the docker image, this is what shown on the docker logs: I tried install supervisor3.0 but it said supervisor is not supported in python 3x. Please help me if I can solve this problem or another version of 3x python could help? -
How to configure django-tenant-schemas to exclude port in request?
I am developing a django project that implements multi tenancy using django-tenant-schemas. I have the following records in my Client models: 1) Public schema with domain_url "huncho.com" and schema name "public" 2) tenant schema with domain_url "tenant1.huncho.com" and schema name "tenant1" 3) tenant schema with domain_url "tenant2.huncho.com" and schema name "tenant2" when I access the public schema using url: huncho.com:8000, it accepts the url and shows content from public schema. However, when i try to access tenant schema using tenant1.huncho.com:8000, it raises a 404 error saying "No tenant found for "tenant1.huncho.com:8000". I have tenant1.huncho.com in my hosts file. 127.0.0.1 huncho.com 127.0.0.1 tenant1.huncho.com 127.0.0.1 tenant2.huncho.com ... Earlier in this project, i had set domain_url of public schema as huncho ie single word. tenant urls were tenant1.huncho, tenant2.huncho and so on, with schema nams tenant1, tenant2. my hosts file had this: 127.0.0.1 huncho 127.0.0.1 tenant1.huncho 127.0.0.1 tenant2.huncho ... This was working perfectly and it did not cause any trouble to seperate the schemas. All data was seperately stored and managed, according to host and schema, as it should be. In short, when I am setting the hostname to huncho.com instead of huncho, it includes the port number also while checking for schemas. … -
Sending real time data to a webpage in Django
I'm creating a Django project and i found myself at a dead end when looking for a solution to retrieve data and display it on a page in real time. My app is a trading analytics webapp, so i need to show those trades in real time on a HTML page whenever a user opens the page. So i have an external Python app which retrieves the trades and updates them on a database and then my Django app, which should retrieve them again and put them in real time on the html page, whenever a user opens it. Now, the first thing that came to my mind is Django Channels; the problem with using it, though, is that i would be flooding my database with requests and i would end up crashing it, since it should handel 1+ requests per second for every user. Then i thought of using RabbitMQ and Celery, but the problem is that i don't know, in that case, how the data would be sent to my frontend/html page. I know this question will probably get downvoted for being too broad, so i'm trying to make it as specific as possible; is there a service/solution … -
Hide divs and display div when button clicked
I am a total newbie of Jquery and JavaScript. I am using this code as reference: https://jsfiddle.net/6uzU6/2/ What I am trying to do is similar as the link above, which is to display a div after a corresponding button is clicked while others divs are hidden. I was trying to modify the code to use div instead of unordered list. The problem I am having right now is when I use Brave Browser to open the page, the divs are not hiding and no changes are made after clicking the button. While using Chrome, the page will be blank, nothing is shown. tutorialIndex.html {% extends "morse_logs/base.html" %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'morse_logs/css/style.css' %}"> <link href="{% static 'morse_logs/js/jquery-ui/jquery-ui.min.css' %}" rel="stylesheet"> <link href="{% static 'morse_logs/js/jquery-ui/jquery-ui.structure.min.css' %}" rel="stylesheet"> <link href="{% static 'morse_logs/js/jquery-ui/jquery-ui.theme.min.css' %}" rel="stylesheet"> <div class="container"> <h1>Tutorial</h1> </div> <div id="menu"> <button class="justClick" href="#">A</button> <button class="justClick" href="#">B</button> <button class="justClick" href="#">C</button> <button class="justClick" href="#">D</button> </div> <div class="content"> </div> <div class="content1"> <h1>A</h1> <img src="{% static 'morse_logs/img/A.png' %}" alt="A" style="width:128px;height:128px;"> </div> <div class="content2"> <h1>B</h1> </div> <div class="content3"> <h1>C</h1> </div> <div class="content4"> <h1>D</h1> </div> <script src="{% static 'morse_logs/js/jquery-3.4.1.min.js' %}"></script> <script src="{% static 'morse_logs/js/jquery-ui/jquery-ui.js' %}"></script> <script src="{% static 'morse_logs/js/app.js' %}"></script> {% … -
How can I give foreign key to two models (so as to represent the activity logs)
The problem is, I have to give foreign key reference to two different models so as to record the activity logs of the user I have model named Activity Log to record the activities done by the user class ActivityLog(models.Model): target = models.ForeignKey(Build, on_delete=models.CASCADE, null=True, blank=True) # Target, (Optional) The object to which the activity was performed. user = models.ForeignKey(User, on_delete=models.CASCADE) # Actor The object that performed the activity. action_object = models.ForeignKey(Team, on_delete=models.CASCADE, null=True, blank=True) # Action Object. (Optional) The object linked to the action itself. content = models.TextField() # Content of the activity timestamp = models.DateTimeField() I need to give the target field with foreign key refering to two different models. Is it possible to use generic relations? -
Login Records of each Admin Panel User to be available
I am working upon a Django app and wants to trace the login records based on timestamp, IP address and city identification through IP. How do I do it? -
How can I make a an html form from a image of a scanned form using pyhon 3.x APIs?
I want to get the output as digital/HTML form from a scanned image or pdf form I've got to know that I've to first read all the textual data from the image using OCR and further Django would be used. I'm not so familiar with Django though so I don't know what type of output should I get to pass to Django so that it'd give me an HTML form as an output. Following is the code for reading text from an image, that's working import numpy as np import requests import io import json img = cv2.imread("C:\\Users\\Asus\\Desktop\\ocr\\screenshot.jpg") height, width, _ = img.shape # Cutting image """roi = img[0: height, 400: width]""" roi = img # Ocr url_api = "https://api.ocr.space/parse/image" _, compressedimage = cv2.imencode(".jpg", roi, [1, 90]) file_bytes = io.BytesIO(compressedimage) result = requests.post(url_api, files = {"screenshot.jpg": file_bytes}, data = {"apikey": "helloworld", "language": "eng"}) result = result.content.decode() result = json.loads(result) parsed_results = result.get("ParsedResults")[0] text_detected = parsed_results.get("ParsedText") print(text_detected) cv2.imshow("roi", roi) cv2.imshow("Img", img) cv2.waitKey(0) cv2.destroyAllWindows() But what shall be done next? I would be grateful if anyone can enlighten me on how to proceed through this whole thing. Thanking in advance -
Django: ConnectionResetError: [Errno 54] Connection reset by peer
Anytime when the program calls for either favicon.ico or any admin css files, I'm getting the ConnectionResetError: [Errno 54] Connection reset by peer I'm using Django==3.0.4 Python 3.6.1 For any of the below calls "GET /favicon.ico HTTP/1.1" 404 2104 "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 "GET /static/admin/css/changelists.css HTTP/1.1" 200 4096 "GET /static/admin/css/dashboard.css HTTP/1.1" 200 412 "GET /static/admin/css/widgets.css HTTP/1.1" 200 4096 I'm getting Traceback error like Exception happened during processing of request from ('127.0.0.1', 60974) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 639 , in process_request_thread self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 361 , in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socketserver.py", line 696 , in __init__ self.handle() File "/Users/sunilhn/Documents/programming/Envs/proenv/lib/python3.6/site-packages/django/core/s ervers/basehttp.py", line 174, in handle self.handle_one_request() File "/Users/sunilhn/Documents/programming/Envs/proenv/lib/python3.6/site-packages/django/core/s ervers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/socket.py", line 586, in r eadinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer The program runs fine in the frontend without any issues. But this error in console is bugging me. -
Session key is None in django?
guys, I have been trying to use cookie sessions to save user's data,I have used session successfully in my previous applications but this time it's not working properly I know that in order to get the value of the session key the session has to modified or saved. So what I used to do before is make a mixin and used to call that on the view I needed the session key, The case for me here was to grab the session key and the save link that with a model instance but the session key is None or if I change my code to what I have wrote at the bottom it creates a new session key at every request Here's the mixin I used in my previous applications and it worked fine class SessionMixin: def get_session(self,request,*args,**kwargs): session = self.request.session if not session.get('has_session'): session["has_session"] = True return self.__class__.get(self,request,*args,**kwargs) class MyView(SessionMixin,generic.View): def get(self,request,*args,**kwargs): super().get(self,request,*args,**kwargs) print(self.request.session.session_key,"Gives me none") # rest of the code goes here My setting for session cookies SESSION_COOKIE_AGE = 604800 SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies" Here's what I tried too but it just created a session key on every single request. class SessionMixin: def get(self,request,*args,**kwargs): session = self.request.session if not … -
How to get sum of values inside django loop
inside my loop i am getting the values in a variable i want to get sum of these values .code is given value for index in range(len(json_objects)): getsum = 0 sum = json_objects[index]['fields']['bill'] getsum += float(sum) print(getsum) but i am getting only values except sum can any one please help me related tihs ?? > json_objects[index]['fields']['bill'] i am getting values like 100 > and 200 in a loop i want the sum 300 in getsum variable -
Django Patterns: One-To-One Field, Auto Create
Is there a good way, or a common pattern to automatically create one-to-one fields that do not yet exist? Conceptually, I want my OneToOneField to work like a get_or_create call. For example: class Foo(models.Model): user = models.OneToOneField(User, related_name="foo", unique=True) class User(models.Model): ... @property def foo(self): """ This is what I want to achieve conceptually. """ foo, created = Foo.objects.get_or_create(...) return foo ... user.foo() # if none, will create. -
Django: related_name vs Queryset Performance?
I have a Django model with a ForeignKey to another model: class Foo(models.Model): user = models.ForeignKey(User, related_name="foo", unique=True) However, I don't really like needing to call user.foo.all().first(), because this is going to exclusively be a unique one-to-one. So I've decided to do this: class User(models.Model): ... @property def foo(self): foo, created = Foo.objects.get_or_create(...) So I can just return user.foo. Is there any benefit to using the reverse relationship? -
Django - Bootstrap for loop doesnt iterate through all objects
I got a Django app with bootstrap and i want to display an image preview so i made a small view of the image and after clicking it, it should appear over the whole screen. So i did this: <img class="painting " src="{{ paintings.Gemälde.url }}" data-toggle="modal" data-target=".bd-example-modal-xl" /> <div class="modal fade bd-example-modal-xl" tabindex="-1" role="dialog" aria-labelledby="myExtraLargeModalLabel" aria-hidden="true"> <div class="modal-dialog modal-xl" role="document"> <div class="modal-content"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h5 class="modal-title mx-auto" id="exampleModalLongTitle">"{{ paintings.Bildname }}"</h5> <img class="painting-active" src="{{ paintings.Gemälde.url }}"> <div class="modal-footer"> <p class="mx-auto">{{ paintings.Bildtechnik }}, {{ paintings.Erstelldatum }}, {{ paintings.Bildmaße_in_cm }}cm {% if paintings.Bildpreis == 0 %} </p> {% else %} {{ paintings.Bildpreis }} {% endif %} </p> </div> </div> </div> </div> This code is inside a for loop {% for paintings in artist.paintings.all %}, more code is here So if I click a picture it shows all the attributs of the first saved object. But if I remove the codeblock above and replace it with a simple list <ul> <li> {{ paintings.name }} </li> <li> {{ paintings.etc }} </li> </ul> everything is shown correctly. Is this a problem with bootstrap or is there a stupid mistake of myself? I use django version 3. -
Django 3.x error: 'mysql.connector.django' isn't an available database backend
Having recently upgraded a Django project from 2.x to 3.x, I noticed that the mysql.connector.django backend (from mysql-connector-python) no longer works. The last version of Django that it works with is 2.2.11. It breaks with 3.0. I am using mysql-connector-python==8.0.19. When running manage.py runserver, the following error occurs: django.core.exceptions.ImproperlyConfigured: 'mysql.connector.django' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' I am aware that this is not official Django backend but I have to use it on this project for reasons beyond my control. I am 80% sure this is an issue with the library but I'm just looking to see if there is anything that can be done to resolve it beyond waiting for an update. -
Django better Solution for EditUser [closed]
i have a question. So im new in Django and i worked with forms a few days. So i just made a "context" and put my form in it to give it to my Template. After i worked with it i edit my Code much so i can load Data from my Model to the Template, just like a edit User Page where you can see your stuff. I solved that with the Basic stuff like " name = request.POST["name"]. But my Code is ugly and i dont like it. So my question is, is it possible to work with forms in this task? I just want to load Data in a EditUser Page and load Data from Template in DB. I tried it with the Crispy Forms and with the normal forms but it doesnt work. U guys know a better solution? Bc now i have like 5 Functions with stuff like that: if request.method == "POST": name = request.POST["name"] stuff1 = request.POST["stuff1"] stuff2 = request.POST["stuff2"] stuff3 = request.POST["stuff4"] -
Filter objects by ManyToManyField Django
I have a friends feature on my website, and I want the homescreen to be posts filtered by the users the current user follows. Here is the relevant model class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,max_length=30) friends = models.ManyToManyField(User,blank=True,related_name='user_connections') And the relevant view class PostViewList(HitCountDetailView,SelectRelatedMixin,ListView): model = Post count_hit = True template_name = 'mainapp/list.html' select_related = ("user","group",) paginate_by = 5 context_object_name = 'posts' queryset = models.Post.objects.all() def get_queryset(self): # return Post.objects.filter(author__friends__friend__id=self.request.user.id) qs = super().get_queryset() select_related = ("user","group",) # user = self.user return qs.filter(Q(friend__author=self.kwargs['post.author'])) *note that the group in the select_related is there because of another unrelated feature As you can see, I have tried to filter out posts, but it doesn't work. I don't know what I am missing/doing wrong. -
__str__ returned non-string (type float)
Although there are many questions of this type, but none of them is of type float. I am trying to send a float value to my django template. models.py: class BudgetInfo(models.Model): items= models.CharField(max_length=20) cost= models.FloatField(blank=False, null=True) date_added= models.DateField() user= models.ForeignKey(User, on_delete= models.CASCADE) def __str__(self): return self.cost views.py (after logged in redirecting it to the this view): def app_view(request): budget_qs=BudgetInfo.objects.filter(user=request.user) budget=budget_qs[0] return render(request,'tasks_notes/index.html',{'budget':budget}) index.html using budget: <div class="container center"> <h3 class='center'>Your total budget is: <span style="color:green;">{{ budget|floatformat:"-2" }}</span> dollars</h3> I am getting an error of this type: __str__ returned non-string (type float) highlighting the second line of the html mentioned here. How can I resolve this? -
Python: Django/Flask/ Casino/Payment [closed]
One wants to build casino, but one wants to figure out what one needs to know to do the most essential thing of it, knowing how to make real money convert to the 'points' or 'markers', and perhaps some ranking visuals of the top players or most returning costumers is fine too, so one need to know this, and one wondering what one should look into? what areas, and topics? Perhaps need to better my knowledge in some areas, and such, but one is dedicated to this project, perhaps need to develop some software in tkinter. One is at the moment concidering using django but maybe flask would be more suited for it from, web developments stand point? Django always feel as a superhighway, perhaps more advanced projects is better to do in flask? -
Django form invalid, Field is required, even through input is given
I am getting invalid form error: this Field is required views: class ValueSubmitView(TemplateView): template_name = 'multichoice.html' def get(self, request, *args, **kwargs): return render(request, self.template_name, {'form': symptomsForm}) def post(self, request, *args, **kwargs): form =symptomsForm(request.POST) if form.is_valid(): print('is valid called') values = form.cleaned_data.get("symptoms") print(values) return send_rich_text_response(request, { 'answer': values, }) else: print('form invalid', form.errors) return render(request, self.template_name, {'form': form}, content_type='text/html') whereas my form.py is class symptomsForm(forms.Form): MEDIA_CHOICES=((1,'Dry Cough'),(2,'Loss or diminished sense of smell'),(3,'Sore Throat'),(4,'Weakness'),(5,'Change in Appetite'),(6,'None of above'),) symptoms = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple( attrs={ 'class':'some classes ' } ),choices=MEDIA_CHOICES) HTML page is: <form method="post" onsubmit="submit_form('{% url "Value-Submit-View" %}','Value-Submit-View')" class="book-test-drive border pt-3 pl-3 pr-3 pb-1"> {% csrf_token %} <p class="h5-responsive text-center font-weight-bold text-body">Symptoms</p> <div class="row"> <div class="col-12"> {{ form.symptoms }}</div> </div> <div class="row"> <div class="col-12 text-center"> <input type="submit" class="btn btn-indigo btn-sm btn-submit"> </div> </div> </form> I even tried different form fields like char field but didn't work out, getting the same error, I tried this same code in my previous project which work well but the difference is I used it for form model back then error: <ul class="errorlist"><li>symptoms<ul class="errorlist"><li>This field is required.</li></ul></li></ul> -
Cannot install pip package dependencies cloned from a GitHub repo into a separate virtualenv
I have forked and cloned a private Django GitHub repo of a friend of mine into my local directory. Since I am using Windows 8 and my friend created the repo using Linux(Ubuntu), I couldn't use his virtual env. So, I created a separate virtual environment using virtualenv(16.7.8) in my local directory. However, when I run pip install -r requirements.txt only some packages gets installed and others give error. So I had to install all the required packages by manually typing with their specific versions. However, I am unable to install two particular dependencies viz. django-compressor and rcssmin. When I ran pip install django-compressor==2.4 It "failed to build wheel for rcssmin" and logged an error on the terminal that reads error: Microsoft Visual C++ 14.0 is required .... The full error log is shown below: How do I solve this? Also, is there an alternative and better way to work on GitHub projects like this where I have to involve different OS(without using virtual machines to match OS)? -
How to add custom response message in django rest swagger?
I have created a custom function to write parameters with Django rest swagger schema = coreapi.Document( title='Thingy API thing', 'range': coreapi.Link( url='/range/{start}/{end}', action='get', fields=[ coreapi.Field( name='start', required=True, location='path', description='start time as an epoch', type='integer' ), coreapi.Field( name='end', required=True, location='path', description='end time as an epoch', type='integer' ) ], description='show the things between the things' ), } ) this produces below result But it does not help in writing custom response messages. I want to write custom response messages also. How can i do that -
unable to run django-nose test with coverage in Django
I've django-nose installed in my virtual environment and added in my settings.py file as follows : INSTALLED_APPS = ( 'backoffice_engine', 'items', ... ... 'django-nose', ) # Use nose to run all tests TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' # Tell nose to measure coverage on the 'backoffice_engine' app NOSE_ARGS = [ '--with-coverage', '--cover-package=backoffice_engine', ] the folder structure of backoffice_engine app is as follows │ admin.py │ apps.py │ forms.py │ models.py │ urls.py │ views.py │ views_ithcos.py │ views_ithcos_mtas.py │ __init__.py │ ├───migrations │ │ 0001_initial.py │ │ 0002_auto_20180414_0836.py │ │ ├───templatetags │ │ backoffice_extras.py │ │ __init__.py | ├───tests │ │ tests_forms.py │ │ tests_models.py │ │ tests_views.py │ │ test_urls.py │ │ __init__.py in my test_views.py file i have from django.test import SimpleTestCase class Testviews(SimpleTestCase): def test_sample_view(self): self.assertEqual(1 == 1) similarly in my test_models.py file i have: from django.test import SimpleTestCase class Testmodels(SimpleTestCase): def test_sample_model(self): self.assertEqual(1 == 1) my understanding is that i now have total of two tests and doing python manage.py test --keepdb should show me a coverage report of all the files in my app that were tested and test result stating 2 test were conducted and both were successful however i get coverage report as expected but … -
Django : how to display images from database in template?
Hi I don't know why but I can't display images from my database. I think it is because of my path in my template. My model : class Article(models.Model): titre = models.CharField(max_length=200) auteur = models.CharField(max_length=200) pub_date = models.DateTimeField('date de publication') numero = models.CharField(max_length=200) categorie = models.CharField(max_length=200, default="culture") contenu = models.CharField(max_length=200000) image = models.ImageField(upload_to='image_publie', blank=True, null=True) def __str__(self): return self.titre def was_published_recently(self): return self.pub_date >= timezone.now() -datetime.timedelta(days=7) My view : def detail(request, article_id): article = get_object_or_404(Article, pk=article_id) return render(request, 'gazette/detail.html', {'article':article}) My url : path('<int:article_id>/', views.detail, name='detail'), Settings : STATIC_URL = '/static/' MEDIA_URL = '/images/' MEDIA_ROOT = os_path.join(BASE_DIR, 'images/') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] My template : {% extends "base.html" %} {% load static %} {% block content %} <h1>{{ article.contenu }}</h1> <ul> {% if article.image %} <img src="{{article.image.url}}" alt="{{article.titre}}" style="width: 200px; height: 200px;"> {% endif %} </ul> {% endblock %} And : And what I see on my template -
Test case written for url resolver using resolve() in django application not working
I am trying to write test cases for simple user login and registration system in django. First, I was thinking of writing test cases for the urls. The only test case I have written so far is from django.test import SimpleTestCase from django.urls import reverse, resolve, path from main.views import homepage, register, login_request, logout_request import json # Create your tests here. class TestUrls(SimpleTestCase): def test_list_is_resolved(self): url = reverse('homepage') self.assertEquals(resolve(url).func,homepage) The default urls.py is from django.contrib import admin from django.urls import path, include urlpatterns = [ path('tinymce/',include('tinymce.urls')), path("",include('main.urls')), path('admin/', admin.site.urls), ]` The main application urls.py is from django.urls import path from . import views app_name='main' # here for namespacing the urls urlpatterns = [ path("", views.login_request, name="login"), path("homepage/",views.homepage, name="homepage"), path("register/", views.register,name="register"), path("logout", views.logout_request, name="logout"), ]` Now every time I am running the tests, I am getting the following error. (myproject) C:\Users\rohan\mysite>py manage.py test System check identified no issues (0 silenced). E ====================================================================== ERROR: test_list_is_resolved (main.tests.test_urls.TestUrls) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\rohan\mysite\main\tests\test_urls.py", line 11, in test_list_is_resolved url = reverse('homepage') File "C:\Users\rohan\Envs\myproject\lib\site-packages\django\urls\base.py", line 87, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "C:\Users\rohan\Envs\myproject\lib\site-packages\django\urls\resolvers.py", line 677, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'homepage' not found. 'homepage' is not a valid view …