Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> … -
Heroku app shows Server Error (500) Django website
I launched my Django app on Heroku a while ago. Everything was running smoothly all this time. But now when I try to access the app, it shows this single line only : Server Error (500) Here are the logs: 2020-04-14T09:36:48.786258+00:00 app[web.1]: 10.69.178.208 - - [14/Apr/2020:09:36:48 +0000] "GET / HTTP/1.1" 500 145 "https://ncovidweb.herokuapp.com/preventive-measures/" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36" 2020-04-14T09:36:48.787091+00:00 heroku[router]: at=info method=GET path="/" host=ncovidweb.herokuapp.com request_id=d33234a9-222e-4ea8-9d4c-e93dbba0aa86 fwd="103.133.206.226" dyno=web.1 connect=0ms service=386ms status=500 bytes=380 protocol=https 2020-04-14T09:37:01.510013+00:00 app[web.1]: 10.109.140.73 - - [14/Apr/2020:09:37:01 +0000] "GET / HTTP/1.1" 500 145 "-" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36" 2020-04-14T09:37:01.514397+00:00 heroku[router]: at=info method=GET path="/" host=ncovidweb.herokuapp.com request_id=d179af23-8844-4aea-9b0a-c7f8dbf08b97 fwd="103.133.206.226" dyno=web.1 connect=0ms service=577ms status=500 bytes=380 protocol=https 2020-04-14T09:38:45.470752+00:00 heroku[router]: at=info method=GET path="/" host=ncovidweb.herokuapp.com request_id=4490976c-4df6-49ba-8eab-a92e527a3b08 fwd="103.133.206.226" dyno=web.1 connect=0ms service=446ms status=500 bytes=380 protocol=https 2020-04-14T09:38:45.471354+00:00 app[web.1]: 10.30.61.206 - - [14/Apr/2020:09:38:45 +0000] "GET / HTTP/1.1" 500 145 "https://dashboard.heroku.com/" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36" 2020-04-14T09:43:02.887254+00:00 heroku[router]: at=info method=GET path="/" host=ncovidweb.herokuapp.com request_id=8a378105-bd9c-476c-b9d0-7b58929e16c7 fwd="103.133.206.226" dyno=web.1 connect=1ms service=220ms status=500 bytes=380 protocol=https 2020-04-14T09:43:02.885109+00:00 app[web.1]: 10.150.193.19 - - [14/Apr/2020:09:43:02 +0000] "GET / HTTP/1.1" 500 145 "https://dashboard.heroku.com/" "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36" 2020-04-14T09:45:12.066183+00:00 heroku[router]: at=info method=GET path="/" host=ncovidweb.herokuapp.com request_id=96142b52-d016-466d-adb7-80a970cde6a2 fwd="103.133.206.226" dyno=web.1 connect=1ms service=414ms status=500 … -
Django REST Framework: AttributeError: 'DeferredAttribute' object has no attribute 'isoformat'
This is my first time using Django REST FRAMEWORK, I'm facing an issue with a registration api, on the first try the api worked properly, but on the following tries it started throwing this error AttributeError: 'DeferredAttribute' object has no attribute 'isoformat' first here is my code: serializers.py: class UserSerializer(serializers.ModelSerializer): def create(self, validated_data): user = User.objects.create(**validated_data) user.set_password(validated_data['password']) user.save() # return dict(status=True, code=1) return User class Meta: model = User fields = ['phone', 'email', 'first_name', 'last_name', 'birth_date', 'gender', 'user_type', 'password', 'username'] extra_kwargs = { "password": {"write_only": True} } apis.py: class RegisterApi(CreateAPIView): model = get_user_model() permission_classes = [permissions.AllowAny] serializer_class = UserSerializer models.py: class User(AbstractUser): notification_token = models.CharField(max_length=255, unique=True, blank=True, null=True) phone = models.CharField( _("Phone Number"), max_length=50, validators=[phone_validator], unique=True, ) is_active = models.BooleanField( _('active'), default=False, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) photo = models.ImageField( _('Profile Picture'), upload_to='profile/', help_text=_( "the user's profile picture." ), blank=True, null=True ) address = models.CharField(_("Address"), max_length=255) lives_in = models.ForeignKey('City', on_delete=do_nothing, null=True, blank=True) user_type = models.CharField( _("Type"), max_length=3, choices=USER_TYPES, help_text=_("The user's type can be one of the available choices, " "refer to the Model class for the detailed list."), ) birth_date = models.DateField(_('Birth Date'), blank=True, null=True) gender … -
Child process was not spawned error with Django application and Gunicorn
I'm following this tutorial to deploy my Django application to a Linux server. My problem is that, when i type sudo supervisorctl status MYAPP i'm getting the following status: MYAPP FATAL Exited too quickly (process log may have details) I've chedk my logs and i only found this: supervisor: couldn't exec /home/hst/bin/gunicorn_start: EACCES supervisor: child process was not spawned This error is quite generic, so i 'm struggling to find what's wrong, here is my gunicorn_start: #!/bin/bash NAME="MYAPP" DIR=/home/hst/MYAPP USER=hst GROUP=hst WORKERS=3 BIND=unix:/home/hst/run/gunicorn.sock DJANGO_SETTINGS_MODULE=myproj.settings DJANGO_WSGI_MODULE=myproj.wsgi LOG_LEVEL=error cd $DIR source ../bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- Can anyone help me with this? -
VS Python attach remote. Starts running for a couple seconds then stops
So I have this Django app inside of Docker running and I'm trying to attach VS code to it so I can debug here is my launch file { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Remote Attach", "type": "python", "request": "attach", "port": 8800, "host": "192.168.99.100", "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "." } ] } ] } The host 192.168.99.100 is the IP that Docker runs on(I'm using Docker Toolbox). For some reason it runs for like 5 seconds then cancels itself. Any suggestions? -
Django Group By not working with multiple joins
I'm facing a problem grouping the records with queryset having multiple joins in Django ORM. It works fine when running a sql raw query. Please find below the models, sql raw query and my try on Django ORM for the respective query. model.py class Merchants(models.Model): id = models.IntegerField(primary_key=True) prospectId = models.CharField(max_length=50, default=None) merchantAmount = models.FloatField(null=True, blank=True, default=None) lenderName = models.CharField(max_length=10, default=None) requestedLoanAmount = models.FloatField(blank=True, default=None) createdDate = models.DateTimeField(default=None) storeId = models.IntegerField(unique=True, default=None) eStatus = models.CharField(max_length=10, default=None) loanBookingDate = models.DateField(default=None) dueLoanAmount = models.FloatField(default=None) totalRepayAmount = models.FloatField(default=None) los_loanApplicationId = models.CharField(max_length=50, default=None) modifiedDate = models.DateTimeField(default=None) loanStatus = models.CharField(max_length=20, default=None) LLA_LLMM = models.ForeignKey(LOS_Loan_Application, on_delete=models.CASCADE, db_column='los_loanApplicationId', to_field='loanApplicationId', default=None) class Meta: db_table = "loan_lending_mca_merchants" verbose_name_plural = "Merchants" class Agent_Task_Log(models.Model): iVisitId = models.IntegerField(primary_key=True) iTaskId = models.IntegerField(default=None) ePaymentMode = models.CharField(max_length=30, default=None) iAmount = models.IntegerField(default=None) iStoreId = models.IntegerField(unique=True, default=None) dupdation_date = models.DateTimeField(default=None) store = models.ForeignKey('trx_insight.Store', on_delete=models.CASCADE, db_column='iStoreId', default=None) collection_dpd = models.ForeignKey(Collection_DPD, on_delete=models.CASCADE, db_column='iStoreId', to_field='iStoreId') class Meta: db_table = "agent_task_log" verbose_name = "Agent Task Log" class Agents_Task(models.Model): iAgentTaskId = models.IntegerField(primary_key=True) iStoreId = models.IntegerField(unique=True, default=None) iAgentId = models.IntegerField(default=None) iTaskTypeId = models.IntegerField(unique=True, default=None) iAssignedBy = models.IntegerField(default=None) tCreationDate = models.DateTimeField(default=None) tUpdationDate = models.DateTimeField(default=None) tasksLog = models.ForeignKey(Agent_Task_Log, on_delete=models.CASCADE, db_column="iStoreId", to_field="iStoreId", default=None) class Meta: db_table = "agents_task" verbose_name_plural = "Agents Task" class Tasks_Master(models.Model): iTaskMasterId = … -
Django queryset using select_related and prefetch_related
models.py class Question(Model): pass class Topic(Model): question = models.Foreignkey(Question) class Syllabus(Model): topic = models.Foreignkey(Topic) #The Bridge Model class Test_Syllabus(Model): test = models.Foreignkey(Test) syllabus = models.Foreignkey(Syllabus) class Test (Model): pass I have a test object as follows: test = Test.objects.get(id=pk) Using the test object, I want to get the related queryset of questions. So, I tried the following code: questions = test.test_syllabus_set.all() #don't know how to go further from here I think it has something to do with select_related and prefetch_related. Please help me out with a perfect query for this use case. -
Django installation issue & ERROR: Exception
Since last months I had worked properly on some django project but those I when I try to work on new project I meet issue in the Django in installation. [enter image description here][1] [1]: https://i.stack.imgur.com/kMZKF.jpg This code Erro appears when I type pip install Django in the prompt command please could anyone help me out to fix that issue? -
Waypoints Infinite Scroll not rendering script tag content
Currently using Wapypoints Infinite in a Django framework. I am trying to place a Jquery script tag into the infinite item generated to report back to django that it loaded. Unfortunately the script tag is loading, however nothing contained inside it is loading (as checked with google dev inspect). Please find the HTML below. Thanks for your help! <div class="infinite-container"> {% for post in posts %} <div class="infinite-item"> <div class="content-section"> <div class="media-body"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ post.user.username }}</h2> <h3 class="text-secondary">{{ post.highlight.quality }}</h3> <video src="{{ post.highlight.highlight.url }}" type='video/mp4' controls> Program is incompatable with your browser, please update it. </video> <script type="text/javascript"> $.post('/feed/submitview/', {id: {{ post.highlight_id }}}) </script> </div> </div> </div> {% endfor %} </div> <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function ($items) { $('.loading').hide(); } }); -
Eror in configuring allauth at AUTHENTICATION_BACKENDS
settings.py """ Django settings for classproject project. Generated by 'django-admin startproject' using Django 2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '%__uki0du$y1bwf)m!#!(9%k*9$^u%gtbye*283&2mwtj(vh0g' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'mainapp', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'classproject.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', 'django.template.context_processors.request', ], }, }, ] WSGI_APPLICATION = 'classproject.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' … -
Serial file upload VS Parallel file upload
Scenario: There's a frontend (an iOS application) and a backend (a server). Frontend needs to upload a set of images ranging from 1 - 10 (Nos. may vary) with some image data, to the backend. Question: 1) Do I upload the images in parallel (One network request per image) or in serial (all images in a network request). Which method method would be better in terms of speed and other factors? 2) If serial upload is best suited, to my knowledge, multipart form-data is used. Considering the below details of the image, how to create the body to accommodate multiple records? { "picture" : "@/Users/userName/Desktop/picture.png", "model" : "the model name to which the image is linked", "record_id" : "the record, to which the image is linked" } I use Swift and Python (Django). For testing purposes I use postman and curl. Thank you -
login_required decorator not redirecting to the following view
I want to render the specified template only when the admin got logged in so I used login_required decorator but it is redirecting to admin rather than rendering and displaying the specified template @login_required(login_url='/admin/') def employeesignupview(request): return render(request,'todoapp/employeesignup.html') -
Why does my html not render in my Django app home page?
I am new to to using Django I am making a pet gallery app, I am using bootstrap for my front-end and i want to create pet card in my home page, my problem is the html i write in my index.htm doesn't render in the home page. My index.htm: <!DOCTYPE html> <html lang="en"> <head> <title> The Pet Gallery </title> {% load static %} <link rel="stylesheet" href="{% static 'pet_gallery/style.css' %} " /> <link rel="stylesheet" href="https://bootswatch.com/4/litera/bootstrap.min.css"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> </head> <body> {% include 'nav_bar.htm' %} <div class="card_container"> <div class="card_image"> <img src="" alt=""> </div> <h4 class="card_title"></h4> <div class="card_body"> </div> </div> <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> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </body> </html> style.css: .card_container{ width: 200px; height: 700px; background-color: grey; } I really need help i have been at this for days, if you need any additional information to be of help I will gladly provide. -
Attach Multiple Instances of A Single Object Type To Multiple Parent Objects Types in Django
I have these models: class Organization(models.Model): name = models.CharField(verbose_name="Orgainzation Name", max_length=100, unique=True) ein = models.CharField(verbose_name="Entity Identification Number", max_length=10, unique=True) address = models.ForeignKey(Address, on_delete=models.SET_NULL) created = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, models.SET_NULL) updated = models.DateTimeField(auto_now=True) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, models.SET_NULL) class User(AbstractUser): address = models.ForeignKey(Address, models.SET_NULL) birth_date = models.DateField() phone = models.CharField(max_length=15)``` I want to be able to attach multiple files to each object type Organization and User. I created these models to do so: class OrgFile(models.Model): file = models.FileField() parent = models.ForeignKey(Organization, models.SET_NULL) class UserFile(models.Model): file = models.FileField() parent = models.ForeignKey(settings.AUTH_USER_MODEL, models.SET_NULL) It seems like there should be a way to use one File model and attach it to different types of objects. Is this possible or do I need to make a class for each parent type?