Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> … -
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?