Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React Router changing URL, but component not rendering
I have been trying to learn React over the past couple of weeks and started working on a site which displays art works. I would like for the user to be able to click on one of the images displayed and for a new component to be loaded with information about the work. I have the implementation below of the gallery view, but when I click on an image the URL changes, but the WorkPage component never loads. Would anyone be able to spot what I am doing wrong? The links and images are generated in the renderItems() function. import React, { Component } from "react"; import Masonry from 'react-masonry-css'; import WorkPage from "./WorkPage" import axios from "axios"; import { Link, Route, Switch, useRouteMatch, useParams } from "react-router-dom"; import { BrowserRouter as Router } from "react-router-dom"; class Works extends Component { constructor(props) { super(props); this.state = { viewPaintings: true, workList: [] }; axios .get("http://localhost:8000/api/works/") .then(res => this.setState({ workList: res.data })) .catch(err => console.log(err)) }; displayPaintings = status => { if (status) { return this.setState({ viewPaintings: true }) } return this.setState({ viewPaintings: false }) }; renderTabList = () => { return ( <div> <ul className="tab-list-buttons"> <li onClick={() => this.displayPaintings(true)} className={this.state.viewPaintings ? … -
Pass data to django view with ajax
I am very new to django and the whole world of jquery, ajax, etc. I am having a page that when a function (javascript, jquery) function is run, I use the POST method to pass some data to my django view. My jquery function is: function handleClick(e) { var myDataVariable = Variable var url = window.location.href var obj = {'Cellid': myDataVariable } $.ajax( {type:'POST', url: url, data: JSON.stringify(obj), contentType: 'application/json; charset=utf-8', success: function (data) {} }); } and in my django views I have: def Main(request): if request.method == 'POST': params = json.loads(request.body) Cellid = params['Cellid'] CellData = cellData.cell_Data(int(Cellid)) else: CellData =[] context = { 'CellData':CellData, } return render(request, 'Main/Main.html', context) Although the page works fine, when the function is called I am getting an error: Forbidden (CSRF token missing or incorrect.): /Main/Main Can someone please help me with this error? It is probably something simple but as I said I am very new to this and it is killing me! I would really appreciate a simple and easy to understand explanation. Many thanks! -
WHEN I DELETE A SINGLE RECORD INTO A TEMPLATE ALL RECORDS ARE DELETED
I have two models child and academy by which these two models have relationship to each other here is child models from django.db import models class Child_detail(models.Model): Firstname = models.CharField(max_length = 50) Lastname = models.CharField(max_length = 50) Tribe = models.CharField(max_length = 50) def __str__(self): return self.Firstname And here is academy model from django.db import models from child.models import Child_detail class Academic(models.Model): Student_name = models.ForeignKey(Child_detail,on_delete = models.CASCADE) Class = models.CharField(max_length = 50) Average_grade = models.CharField(max_length = 10) def __str__(self): return str(self.Student_name) Here is my views.py file that contain delete functionality,instead of delete a single academy record of that specific child it delete all academic details of that specific child def delete_academy(request,pk): child=get_object_or_404(Child_detail,pk=pk) academy=Academic.objects.filter(Student_name=child) if request.method == 'POST': academy.delete() return redirect('more',pk=pk) context={ 'child':child, #'form':form } return render(request,'functionality/more/academy/delete.html',context) -
Setting ArrayField to null or []
files = fields.ArrayField(models.UUIDField(null=True), blank=True, default=None) So I have this line in my model, the task is to keep array of UUIDs of files in the field "files", but i still get an error The array field was imported from postgres fields like so from django.contrib.postgres import fields and models was imported from django.db import models Here is the error File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 447, in add_field self.execute(sql, params) File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 137, in execute cursor.execute(sql, params) File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.IntegrityError: column "files" contains null values -
Why a speciffic CSS class in not applied?
I have recently started learning Django framework with Python. I've been doing a course on YouTube. Unfortunately, one of the steps did not go as on the course. The CSS and JS features does not apply to my page. Do you have some suggestions to make it apply to my page? I was using the starter template. <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <meta charset="UTF-8"> {% if title %} <title>Django Blog - {{ title }}</title> {% else %} <title>Django blog</title> {% endif %} </head> <body> <div class="container"> {% block content %}{% endblock %} </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html> ``` -
Dynamically How to arrange bootstrap grid vertically for mega menu categories
I am using Django for may backend, I have render a list of categories in an ordered sequence. I want to display the categories mega-menu using the bootstrap grid system, but in vertical sequence HTML : <div class="menu-sub" id="mega_id"> <div class="col-md-8" style=""> <div class=""> {% for category in cateogries %} <div class="masonary-grid-item menu-col col-right-33 col-box-category" style=""> <h3 class="menu-category"> <a style="text-transform: uppercase;" href="#0" target="_blank" {{category.name}} </a> </h3> <ul class="ul-height"> {% category_child category.id as childs %} {% for child in childs %} <li><a class="child-a" href="#0" target="_blank">{{child.name}}</a></li> {% endfor %} </ul> </div> {% endfor %} </div> </div> <div class="col-md-4" style="text-transform: uppercase !important;"> <div class="menu-col col-r-100"> <!- Other siderbar --> </div> </div> check the image for reference. -
Share data from host to docker container
I have an application that writes correctly a file generated on a docker container to the host machine. Using the same approach, I was thinking that the problem would be similar if I want to read a file on the container but coming from the host. I use volumes in the docker-compose file: volumes: - /home/qcuci/dockerized_apps/unidosi_logs:/app/unidosi/data/unidosi_logs # here I want to read from the host - /home/qcuci/dockerized_apps/unidosi_silicon:/app/unidosi/data/unidosi_silicon # here I write to host Why I can't read the file? In fact, if I use the bash command I can see that the files aren't copied from the host to the container accordingly -
How can I solve the problems of Testing that are not in the same model?
In my model, there are fields as follows. class Home(TitleSlugDescriptionModel): seller= models.ForeignKey("data.seller", null=True, on_delete=models.SET_NULL) date = models.DateField() picture = models.ImageField(upload_to="images") In my test.py class HomeTestCase(TestCase): def test_random(self): with open("img/no-image.jpg", "rb") as f: for home in range(10): G(Home, picture=ImageFile(f), seller=F(name="test1"), I have a problem when I test. It alerts that: django_dynamic_fixture.ddf.InvalidConfigurationError: ('homes.models.Home.seller', BadDataError('data.models.Seller', ValidationError({'data': ['This field cannot be blank.']}))) I know that This field cannot be blank, And I solved the problem as follows. [add name data] class HomeTestCase(TestCase): def test_random(self): with open("img/no-image.jpg", "rb") as f: for home in range(10): G(Home, picture=ImageFile(f), seller=F(name="test1"), data=F(name="test2") It does not work and alerts that django_dynamic_fixture.ddf.InvalidConfigurationError: Field "data" does not exist. I don't know how to fix it. Can someone recommend me? Thank you very much -
PermissionError: [Errno 1] in collectstatic in django
I have use command python manage.py collectstatic But I got permission error -
Django objects error in view, why I got this error? It looks like my model does not exist
This is my view code: class Planificare_concedii(AllView): template_name = "pep/planificare_concedii.html" def get_context_data(self, *args, **kwargs): magazinu = self.request.GET.get('magazinul') queryset = Planificare_concedii.objects.filter(magazin=magazinu) context = context = super(Planificare_concedii, self).get_context_data( *args, **kwargs) return context This is the error that I got in view page: AttributeError at /planificare_concedii/ type object 'Planificare_concedii' has no attribute 'objects' -
how to create unique id for each department in django model
i created a model in django for student information <!-- language: python --> class student(models.Model): department_choices=(('cse','cse'),('mech','mech'),('EEE','EE')) name=models.CharField(max_length=35) department=models.CharField(max_length=30,choices=department_choices) i want id to be generated unique for department for example if i chose cse department id should be cse0001, cse002 or if mech means id should be mech001 , mech002 what should i do -
Django ajax error: net::ERR_TOO_MANY_REDIRECTS
I want to implement search with django and ajax. HTML: <form class="form-horizontal action-form filter-form" method="get" id="search-form-panel"> {% csrf_token %} <div class="form-group"> <div class="col-lg-6"> <input type="text" name="product-title" class="form-control" placeholder="products" id="search-text-panel"> </div> <div class="col-lg-6"> <button type="button" class="btn btn-success search-btn">search</button> </div> </div> </form> <div class="table-responsive" id="manager-list-container"> <table class="table table-striped table-bordered table-hover" id="basic_list" style="width:100%"> <thead> ... <script> let updateProductSearchUrl = '{% url "update-product-search-item" %}'; </script> <script type="text/javascript" src="/static/product/panel-update-product.js?v={{ SITE_VERSION }}"></script> and in JS: $(document).ready(function () { console.log('it is calling JS part'); $('.search-btn').click(function () { submitSearch(); }); $("#search-text-panel").keyup(function (e) { if (e && e.keyCode === 13) { submitSearch(); } else if (e) { let searchText = $('#search-text-panel').val().trim(); if (searchText.length > 3) submitSearch(); } e.stopPropagation(); e.preventDefault(); return false; }); function submitSearch() { let searchText = $('#search-text-panel').val().trim(); console.log(updateProductSearchUrl); $.get({ url: updateProductSearchUrl, data: {'q': searchText}, method: 'GET', success: function (res) { if (res) { $('#basic_list').find('tbody').empty().append(res.res); } } }); } }); ursls.py: path('update-product-search-item/', views.update_product_search_item, name='update-product-search-item'), and in views.py: @staff_only(url_name='panel/product-type/update') def update_product_search_item(request): print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2') print('it is calling this funciton') try: products = ProductType.objects.first() res = render_to_string('product/panel_update_product_type.html', {'products': products}, request=request) return HttpResponse(json.dumps({'res': res}), content_type="application/json") except Staff.DoesNotExist: return HttpResponseForbidden() by using these codes, when I click on search box it returns : jquery-3.1.1.min.js:4 GET http://127.0.0.1:8082/admin/login/?next=/admin/update-product-search-item/%3Fq%3Dproducts net::ERR_TOO_MANY_REDIRECTS what is this error and how can … -
Add django-tinymce to Django application on server
I've installed django-tinymce package to my Django application on server. But during makemigrations it returns the following error, and I don't know the reason for solving it: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/progbash/pdproject/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/progbash/pdproject/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/progbash/pdproject/env/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/progbash/pdproject/env/lib/python3.5/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/progbash/pdproject/env/lib/python3.5/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/progbash/pdproject/env/lib/python3.5/site-packages/tinymce/models.py", line 7, in <module> from tinymce import widgets as tinymce_widgets File "/home/progbash/pdproject/env/lib/python3.5/site-packages/tinymce/widgets.py", line 95 html = [f"<textarea{flatatt(final_attrs)}>{escape(value)}</textarea>"] -
how to print python list in html table horizontally (django)
I have a list l and want to want to display in html table horizontally. I am new in html and django. l=[10,40,50] I did the fowllowing but it displays vertically <table> <tr><th>grades</th></tr> {% for items in l %} <tr><td>{{ items }}</td></tr> {% endfor %} </table> this is what i want to achieve where i can alsp display years: 2019 2018 2017 grades 10 40 50 I would be grateful for any help. -
django filter table jquery in disorder
I need to filter the table When write the title in textBox, the list table is filtered but in disorder and in a bad format, maybe for the table structure .. this is my code template.html {% load static %} <html lang="en"> <head> ... all src </head> <body> <script src="{% static 'videoclub/js/search.js' %}"></script> <h1 id="searchTitle">Search a movie</h1> <div class="table-wrapper"> <div class="container"> <td> <label for="title">Search by title</label> <input type="text" id="title" placeholder="Title" > </td> <td> <label for="director">Search by Director</label> <input type="text" id="director" placeholder="Director" > </td> <td> <label for="years">Choose a year</label> <select class="form-control-sm ml-1 w-40" id="years"></select> </td> <td> <input type="submit" id="searchButton" value="Search Movie"> </td> </div> <table class="table table-striped table-hover" id="list-movie" > <thead> <td> LIST OF MOVIES</td> </thead> <tbody id="tableBody"> <!--película description--> {% for movie in allMovies %} <tr> <td align="center" ROWSPAN="4"> <img width="100" height="" src="{% static movie.movie_url_cover %}" alt="Pulp Fiction "> </td> <td abbr="red" ><font color="#B40431" size="3"> {{movie.movie_title}} ({{movie.movie_year}})</font></td> </tr> <tr> <td>{{movie.movie_rating}}</td> </tr> <tr> <td><font color="#084B8A" size="2">{{movie.movie_director}}</font></td> </tr> <tr> <td><font color="#585858" size="1">{{movie.movie_actors}}</font></td> </tr> {% endfor %} <!-- ****** --> </tbody> </table> </div> </body> </html> search.js $(document).ready(function(){ $("#title").on("keyup", function() { var value = $(this).val().toLowerCase(); $("#tableBody tr").filter(function() { $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1) }); }); }); At first the table list contains all the movies in correct … -
CSS definitions in django-allauth account templates
I am trying out django-allauth and have come across a block while customizing the allauth account templates. I am presently working on the emails.html template but I am unable to find any definition for the css classes used inside the default templates. CSS classed such as ctrlHolder or primary_email. Please help me with figuring out where these are defined. I can use the bootstrap css but was hoping to keep the default ones if they are good enough. accounts/emails.html {% extends "account/base.html" %} {% load i18n %} {% block head_title %}{% trans "E-mail Addresses" %}{% endblock %} {% block content %} <h1>{% trans "E-mail Addresses" %}</h1> {% if user.emailaddress_set.all %} <p>{% trans 'The following e-mail addresses are associated with your account:' %}</p> <form action="{% url 'account_email' %}" method="post"> {% csrf_token %} <div class="form-group"> {% for emailaddress in user.emailaddress_set.all %} <div class="ctrlHolder"> <label for="email_radio_{{ forloop.counter }}" class="{% if emailaddress.primary %}primary_email{% endif %}"> <input id="email_radio_{{ forloop.counter }}" type="radio" name="email" {% if emailaddress.primary or user.emailaddress_set.count == 1 %}checked="checked"{% endif %} value="{{ emailaddress.email }}"/> {{ emailaddress.email }} {% if emailaddress.verified %} <span class="verified">{% trans "Verified" %}</span> {% else %} <span class="unverified">{% trans "Unverified" %}</span> {% endif %} {% if emailaddress.primary %}<span class="primary">{% trans "Primary" … -
Django Guardian - Check Permission during filtering
Im using Django Guardian to use Instance Permissions. It works well but I have a question about filtering. Lets say we have a models called FakeItem. Lets say we want to filter FakeItems list with only item with a specific permission. @staticmethod def purge_list(entity_list , userOrUsername, permission_name): requesting_user = userOrUsername if not isinstance(userOrUsername, User): requesting_user = User.objects.get(username = username) acl_listed = [] total_rows = 0 for entity in entity_list: if requesting_user.has_perm(entity, permission_name): acl_listed.append(entity) total_rows = total_rows + 1 return { "list" : acl_listed , "totals" : total_rows } This is an example of a method to purge list from item the user can access. Unfortunally this method is called AFTER I get the total list from database with a previous filter. I need to make a O(n) interation over the list to purge it. I need something to purge the list directly in the original filter to optimize the query. search_filter = Q() search_filter = search_filter & Q(name__icontains = "foo") search_filter = search_filter & Q(some_guardian_filter) already_purged_list = FakeItem.objects.filter(search_filter) Guardian's Documentation only explain how to use single method like has_perm etc... -
AWS S3 bucket connect to store the files in django
I am learning django and AWS from this site. I tried to point 'dropbox' to my bucket but in vain. I don't have a file selection button. It looks like this: enter image description here enter image description here Here is my code: storage_backends.py class MediaStorage(S3Boto3Storage): location = 'media' file_overwrite = False settings.py AWS_ACCESS_KEY_ID = 'xxx' AWS_SECRET_ACCESS_KEY = 'xxx' AWS_STORAGE_BUCKET_NAME = 'xxx' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) DEFAULT_FILE_STORAGE = 'project.storage_backends.MediaStorage' models.py class Document(models.Model): uploaded_at = models.DateTimeField(auto_now_add=True) upload = models.FileField() views.py from django.views.generic.edit import CreateView from django.urls import reverse_lazy from .models import Document class DocumentCreateView(CreateView): model = Document fields = ['upload', ] success_url = reverse_lazy('home') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) documents = Document.objects.all() context['documents'] = documents return context home.html {% csrf_token %} {{ form.as_p }} type="submit">Submit Name Uploaded at Size {% for document in documents %} {{ document.upload.name }} {{ document.uploaded_at }} {{ document.upload.size|filesizeformat }} {% empty %} No data. {% endfor %} The above code compiles fine. -
Heroku Django: Build succeed but application error. code=H10 app crashed
I have been testing the django website on my local machine.But now I have been stuggling hours trying to deploy on Heroku. I had gunicorn downloaded, procFile set up, etc. All the methods I can find so far. And I completely dont understand the error message. I have the ondelete on my files but it seems the error comes from heroku. I am really lost. web: gunicorn blog_proj.wsgi --log-file - class Answer(models.Model): question = models.ForeignKey(MCQQuestion, verbose_name='Question', on_delete=models.CASCADE) content = models.CharField(max_length=1000, blank=False, help_text="Enter the answer text that \ you want displayed", verbose_name="Content") correct = models.BooleanField(blank=False, default=False, help_text="Is this a correct answer?", verbose_name="Correct") 2020-04-14T10:02:36.405420+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-04-14T10:02:36.405421+00:00 app[web.1]: worker.init_process() 2020-04-14T10:02:36.405421+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 119, in init_process 2020-04-14T10:02:36.405422+00:00 app[web.1]: self.load_wsgi() 2020-04-14T10:02:36.405422+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-04-14T10:02:36.405422+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-04-14T10:02:36.405423+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-04-14T10:02:36.405423+00:00 app[web.1]: self.callable = self.load() 2020-04-14T10:02:36.405424+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2020-04-14T10:02:36.405424+00:00 app[web.1]: return self.load_wsgiapp() 2020-04-14T10:02:36.405424+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2020-04-14T10:02:36.405424+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-04-14T10:02:36.405425+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 358, in import_app 2020-04-14T10:02:36.405425+00:00 app[web.1]: mod = importlib.import_module(module) 2020-04-14T10:02:36.405425+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module 2020-04-14T10:02:36.405426+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) … -
How to catch the exception of StreamingHttpResponse in Django
I practice at the use of StreamingHttpResponse to write a interface play a video, everytime I update the progress bar, the backend throw an Exception: and the follow is the page: -
How can I use function in models class to add or modify field value before save it?
Hi I am creating one app in Django and created the UserTravelDetails model which will help to store user_id, start and end destination stations_id and route_string. In the route_string field, I want to perform some logic which I wrote in route_string1 function before store data in this field. Here is my code: class UserTravelDetails(models.Model): def __init__(self, route_string1): self.func = route_string1 usr = models.ForeignKey(Users, on_delete=models.CASCADE) start_station_id = models.ForeignKey(Station, on_delete=models.CASCADE, related_name='start_station') destination_station_id = models.ForeignKey(Station, on_delete=models.CASCADE, related_name='destination_station') route_string = models.CharField(max_length=50, default="ok") def __call__(self, *args, **kwargs): return self.func(self) class Meta: verbose_name_plural = "Users Travel History" @UserTravelDetails def route_string1(user): start_station = user.start_station_id destination_station = user.destination_station_id # A and C both on same color # A-->C if start_station.color == destination_station.color: user.route_string = f"{start_station.name}---> {destination_station.name}" else: # A---> D---> C color1_objects = [i.name for i in Station.objects.all().filter(color=start_station.color)] color2_objects = [i.name for i in Station.objects.all().filter(color=destination_station.color)] junction_station = [i for i, j in zip(color1_objects, color2_objects) if i == j] if junction_station: user.route_string = f"{start_station}--> {junction_station}--> {destination_station}" else: # remaining_color_list = pass # A---> B---> D---> C but I am getting error: TypeError: __init__() missing 1 required positional argument: 'route_string1' is there any way to use functions in models class for specific fields? -
Wrap some text in Django Admin field
I have this Django admin page: The second field, "Descrizione", contains a string (taken from a database) of max 500-chars length: I want that this text is entirely displayed in the page, while Django sets up a field as long as the string length, and so I have to sshift it with the right arrow in order to read it. So, how can I make an automatic text wrapping? Hope the question is clear. -
Python requests get content from streaminghttpresponse
I have a django API that stream a response using protobuff messages def retrieve(self, request, event_date=None, notification=None): ... return StreamingHttpResponse(self.generator(leaseEvents, 2000), content_type='application/protobuf') def generator(self, qs, BATCH_SIZE=2000): pages = Paginator(qs.order_by("event_date").values_list('reference', 'event_date', 'event_msg'), BATCH_SIZE) for i in pages.page_range: p = pages.get_page(i) for event in p: # filling protobuf object yield lease_event.SerializeToString() Using Postman to querry the api works well. My goal is to get the result with the python requests module, but i only get an empty response. with requests.get(url, stream=True) as r: print(r) print(r.headers.get('content-type')) print(r.headers) print(r.content) print(len(r.content)) print(r.elapsed.total_seconds()) for line in r.iter_lines(): print("hi") if line: # filter out keep-alive new lines print(line) Here is the result <Response [200]> application/protobuf {'Date': 'Tue, 14 Apr 2020 09:05:45 GMT', 'Server': 'WSGIServer/0.2 CPython/3.8.1', 'Content-Type': 'application/protobuf', 'Vary': 'Accept, Cookie', 'Allow': 'GET, HEAD, OPTIONS', 'X-Frame-Options': 'SAMEORIG IN', 'Content-Length': '0'} b'' 0 0.675784 I thinks Requests assume the content-length is 0, event if I'm using StreamingHttpResponse which dosen't provide content-length. Am I missing something ? Thanks in advance :) -
How to create inner join in django with mongodb?
I use django framework and mongodb database. I want to show all the customers with all their phones. What can I do to avoid using your nesting for loop? How can I do that? I know that customer information can be obtained through the Foreign key in the phone model, But I want the for loop on the customers table to reduce the number of counter for loop my models: class Customers(models.Model): firstName = models.CharField(max_length=50) lastName = models.CharField(max_length=50) class Phones(models.Model): phone_number = models.CharField(max_length=50) customer = models.ForeignKey(Customers, on_delete=models.CASCADE) -
django models and views not rendering images
I am trying to use django to build a music streaming website.I used a models.integer field in my models.py and called it in views.py.But when i try to load the template using the live server the images just wont show up.Instead just the file name is being rendered. my models.py:- from django.db import models # Create your models here. class song_thumb(models.Model): artist=models.CharField(max_length=100,null=True) song_title=models.CharField(max_length=100,null=True) album=models.CharField(max_length=100,null=True) song_duration=models.FloatField(null=True) img=models.ImageField(upload_to='pics',null=True) my views.py:- from django.shortcuts import render from .models import song_thumb # Create your views here. def songs(request): artist1=song_thumb() artist1.artist='Alcest' artist1.song_title='Kodama' artist1.album='Kodama' artist1.song_duration='9.10' artist1.img='kodama.jpg' artist2=song_thumb() artist2.artist='Tash Sultana' artist2.song_title='Jungle' artist2.album='Jungle' artist2.song_duration='5.17' artist2.img='jungle.jpg' artist3=song_thumb() artist3.artist='Animals as leaders' artist3.song_title='Cafo' artist3.album='Cafo' artist3.song_duration='6.56' artist3.img='cafo.jpg' artists=[artist1,artist2,artist3] return render(request, 'home.html', {'artists':artists}) my homepage.html which is used to render all the data:- {% load static %} {% static "images" as baseurl %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Home Page</title> <script src=" https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src= " https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <link rel="stylesheet" href= 'https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css' integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src= 'https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js' integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <link rel="stylesheet" href="{% static 'home.css' %}"> <script src= 'https://kit.fontawesome.com/b99e675b6e.js'></script> </head> <body> <!--sidebar--> <div class="wrapper"> <div class="sidebar"> <h2>Sidebar</h2> <ul> <li><a href="#"><i class="fas fa-home"></i>Home</a></li> <li><a href="#"><i class="fas fa-user"></i>Register</a></li> <li><a href="#"><i class="fas fa-address-card"></i>About</a></li> <li><a href="#"><i class="fas fa-project-diagram"></i>Sign in</a></li> <li><a href="#"><i class="fas fa-address-book"></i>Contact</a></li> …