Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"SMTP AUTH extension not supported by server." on live server, works fine on localhost
This is the code I'm using (after declaring a model): def order_update(sender, instance, created, **kwargs): subject = 'subject' from_email = 'sender@mail.com' to = 'receiver@mail.com' text_content = f'text' html_content = f'html' msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send(fail_silently=False) post_save.connect(order_update, sender=Order) On localhost it works fine, sends an e-mail whenever an object is being created. But when I upload it to a live environment, Ubuntu 16.04, it gives me this error: SMTP AUTH extension not supported by server.. -
Prevent Redis/Celery scheduled tasks from being processed multiple times - Django on Heroku
I am looking for some advice. I use Celery/Redis Scheduled tasks to check changes via an API request every 10 seconds. If there is a change, a database object will be created and when it did some calculations a boolean named is_called will be set to True, to prevent duplicates. This worked fine locally and for a time also on Heroku, but since an update (nothing in the task code changed) the worker seems busy and uses up to 7 ForkPoolWorkers. For example the ForkPoolWorker-1 will work on the same task as ForkPoolWorker-7, which ignores the is_called = True boolean and gives me duplicate calculations with 1 database object created. What's the best way to serve a task only to 1 ForkPoolWorker at a time? I read the docs and google research, but it's not completely clear what and how to do this. I build in Django on Heroku. -
TypeError: kitty() got an unexpected keyword argument 'startdate'
\\I am getting this error -TypeError: kitty() got an unexpected keyword argument 'startdate' which i am clueless. Probably a date format issue. model ----- //Model of the Kitty from django.db import models import datetime from datetime import datetime from multiselectfield import MultiSelectField class kitty(models.Model): company = models.CharField(max_length=3) code = models.CharField(max_length=6) type = models.CharField(max_length=10) name = models.CharField(max_length=100) startdate = models.DateField durinmonths = models.IntegerField() enddate = models.DateField totalmembers = models.IntegerField() totalamount = models.FloatField() installmentamount = models.FloatField() status = models.CharField(max_length=1) creator = models.CharField(max_length=20) cretime = models.DateTimeField(default=datetime.now) updator = models.CharField(max_length=20) updtime = models.DateTimeField(default=datetime.now, blank = True) //View that i have created View ----- from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect import datetime from .models import kitty from django.db import transaction from django.contrib import messages import re def index(request): return render(request, 'kitty/index.html') def kitty_save(request): if request.method == 'POST': company = "1" code1 = request.POST['code'] type1 = request.POST['type'] name = request.POST['name'] startdate = request.POST['startdate'] durinmonths = request.POST['durinmonths'] enddate = request.POST['enddate'] totalmembers = request.POST['totalmembers'] totalamount = request.POST['totalamount'] installmentamount = request.POST['installmentamount'] print(startdate) status = "A" creator = request.user kitty1 = kitty(company=company, code=code1, type=type1,name=name, startdate=startdate, durinmonths=durinmonths, enddate=enddate,totalmembers=totalmembers,totalamount=totalamount,installmentamount=installmentamount, status=status, creator=creator) kitty1.save() transaction.commit() messages.success(request, 'Kitty Added') return HttpResponseRedirect(request.path_info) else: return render(request, 'kitty/kitty.html') //URl file to render URL --- … -
The current path, % url 'accounts:logout' %, didn't match any of these
So, everything in my newly started Django project is working fine except this logout url. I'm using django=1.11.17 and python 3. When I try to logout from the accounts, this is the error I get. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/%25%20url%20'accounts:logout'%20%25 Using the URLconf defined in conspiverse_project.urls, Django tried these URL patterns, in this order: ^$ [name='home'] ^test/$ [name='test'] ^thanks/$ [name='thanks'] ^admin/ ^accounts/ ^accounts/ The current path, % url 'accounts:logout' %, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. accounts/urls.py from django.conf.urls import url, include from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ url(r"login/$", auth_views.LoginView.as_view(template_name="accounts/login.html"),name='login'), url(r"logout/$", auth_views.LogoutView.as_view(template_name="thanks.html"), name="logout"), url(r"signup/$", views.SignUp.as_view(), name="signup"), ] project/urls.py from django.conf.urls import url, include from django.contrib import admin from . import views urlpatterns = [ url(r"^$", views.HomePage.as_view(), name="home"), url(r"^test/$", views.TestPage.as_view(), name="test"), url(r"^thanks/$", views.ThanksPage.as_view(), name="thanks"), url(r"^admin/", admin.site.urls), url(r"^accounts/", include("accounts.urls", namespace="accounts")), url(r"^accounts/", include("django.contrib.auth.urls")), ] settings.py STATIC_URL = '/static/' STATICFILES_DIR = [os.path.join(BASE_DIR,'static')] LOGIN_REDIRECT_URL = 'test' LOGOUT_REDIRECT_URL = 'thanks' I tried verifying the URL paths, cross-checked almost everything, it is driving me crazy. Huge … -
Django doesn't provide a DB representation for AnonymousUser- Django rest api
I tried to change password without the traditional way. Give old password and new password, update the old password. I used UpdateApiView.But i get the following error. Django doesn't provide a DB representation for AnonymousUser I tried passigng Authorization token in header using POST MAN. But Same error. view.py class ChangePassword(generics.UpdateAPIView): serializer_class = serializers.ChangePasswordSerializer model = models.Customer def get_object(self, queryset=None): obj = self.request.user return obj def update(self, request, *args, **kwargs): self.object = self.get_object() serializer = self.get_serializer(data=request.data) if serializer.is_valid(): if not self.object.check_password(serializer.data.get("old_password")): return Response({"old_password": ["Wrong password."]}, status=HTTP_400_BAD_REQUEST) self.object.set_password(serializer.data.get("new_password")) self.object.save() return Response("Success.", status=HTTP_200_OK) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) serializers.py class ChangePasswordSerializer(serializers.Serializer): old_password = serializers.CharField(required=True) new_password = serializers.CharField(required=True) urls.py path('update_password', views.ChangePassword.as_view()), -
Django Forms (with crispy forms) - Am I over complicating this? Is there an easier way?
I've created a form in Django using crispy forms, it works fine but I can tell just by looking at it that I've most likely over engineered it. It's a lot of very similar pieces of code. How should I actually be doing this? I would presume there's a much better way. class New_Contact(forms.Form): title = forms.CharField(label=False, max_length=10,required=False) givenName = forms.CharField(label=False, max_length=255) middleName = forms.CharField(label=False, max_length=255,required=False) surname = forms.CharField(label=False, max_length=255) jobTitle = forms.CharField(label=False, max_length=255,required=False) companyName = forms.CharField(label=False, max_length=255,required=False) department = forms.CharField(label=False, max_length=255,required=False) businessHomePage = forms.CharField(label=False, max_length=255,required=False) assistantName = forms.CharField(label=False, max_length=255,required=False) homePhones = forms.CharField(label=False, max_length=255,required=False) # phones mobilePhone = forms.CharField(label=False, max_length=255,required=False) # phones businessPhones1 = forms.CharField(label=False, max_length=255,required=False) # phones businessPhones2 = forms.CharField(label=False, max_length=255,required=False) # phones homeAddress = forms.CharField(label=False,required=False,widget=forms.Textarea(attrs={'style': 'height: 8em'})) # addresses businessAddress = forms.CharField(label=False,required=False,widget=forms.Textarea(attrs={'style': 'height: 8em'})) # addresses emailAddresses1 = forms.CharField(label=False, max_length=255,required=False) # mail emailAddresses2 = forms.CharField(label=False, max_length=255,required=False) # mail def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.fields['title'].widget.attrs['placeholder'] = 'Title' self.fields['givenName'].widget.attrs['placeholder'] = 'First Name' self.fields['middleName'].widget.attrs['placeholder'] = 'Middle Name' self.fields['surname'].widget.attrs['placeholder'] = 'Last Name' self.fields['mobilePhone'].widget.attrs['placeholder'] = 'Mobile' self.fields['homePhones'].widget.attrs['placeholder'] = 'Home Phone' self.fields['emailAddresses1'].widget.attrs['placeholder'] = 'Email' self.fields['emailAddresses2'].widget.attrs['placeholder'] = 'Email' self.fields['homeAddress'].widget.attrs['placeholder'] = 'Address' self.fields['companyName'].widget.attrs['placeholder'] = 'Company Name' self.fields['department'].widget.attrs['placeholder'] = 'Department' self.fields['jobTitle'].widget.attrs['placeholder'] = 'Job Title' self.fields['assistantName'].widget.attrs['placeholder'] = 'Assistant Name' self.fields['businessHomePage'].widget.attrs['placeholder'] = 'Website' self.fields['businessPhones1'].widget.attrs['placeholder'] = … -
Django Postgres user vs apache user
I have set up environment variables for django user to connect to the postgres database, but the env variables are becoming the apache user as well, which won't give access to httpd file If I take out the postgres user env variables then the pod starts. If I add in the postgres user variables then the apache process can't access the httpd file -
Django-Admin Site: Combine two models in one html
here is my code in admin.py @admin.register(StudentsPaymentSchedule) class StudentsPaymentSchedule(admin.ModelAdmin): list_display = ('Students_Enrollment_Records','Payment_Schedule','Amount','Remarks') ordering = ('Students_Enrollment_Records',) @admin.register(StudentsEnrollmentRecord) class StudentsEnrollmentRecordAdmin(admin.ModelAdmin): list_display = ('lrn', 'Student_Users', 'Education_Levels', 'Courses', 'Section', 'Payment_Type' ,'School_Year') ordering = ('Education_Levels','Student_Users__lrn') list_filter = ('Student_Users','Education_Levels','Section','Payment_Type') Can you guys help me, If I click here, I just want to look like this -
How add blank line in messages django?
I have a line of my code messages.error(request, 'A soma das despesas correntes e das despesas de capital ultrapassam o valor total do projeto.') popping up a message in my template A soma das despesas correntes e das despesas de capital ultrapassam o valor total do projeto. But I want to get a new line after the point, like: A soma das despesas correntes e das despesas de capital, ultrapassam o valor total do projeto. How do I get that? I tryed A soma das despesas correntes e das despesas de capital, \n ultrapassam o valor total do projeto. and A soma das despesas correntes e das despesas de capital, < br \> ultrapassam o valor total do projeto. and {{ message|linebreak }} -
How to access all content from request.session | Django
I want to print all the content of request.session (a django.contrib.sessions.backends.db.SessionStore object). It looks like a dictionary but I am not able to parse it like so: for item in request.session: print(item) # returns KeyError '0' I found a quirky workaround that works in my case: for i in range(1, 4): print(request.session.get(str(i))) Though this is not very maintainable. What is a good way of fetching all the data from this session object? -
csrf verification failed request aborted when uploading media
I am getting the "csrf verification failed request aborted" error when uploading media files via forms. I am setup on a digital ocean server and everything else seems to be running fine. I have the {% csrf_token %} tags in my forms and have the proper settings in my settings.py: 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', My django version: django.VERSION (2, 2, 6, 'final', 0) Static files are also being served no problem. Everything works correctly on my local machine and I don't have this problem. Not sure where to go from here. -
search results from a Django model method including the results from earlier calls to the same method
I have a Django Model that tracks email message IDs as the message passes through different servers. It has a models.ForeignKey field to itself, so we can chain them together to follow the full path of a message through many servers. The model has a 'get_children()' method that recursively looks for all messages descended from the given message. class Msg(models.Model): hostname = models.CharField(max_length=48) qid = models.CharField(max_length=24) received_from = models.ForeignKey( "self", blank=True, null=True, default=None, on_delete=models.SET_DEFAULT ) def get_children(self, parent_messages=set()): for r in Relay.objects.filter(received_from=self): r._get_all_child_messages(parent_messages) parent_messages.add(self) p = list(parent_messages) parent_messages = set() return p If I run a single query from the Django shell, it works as expected. "Solo" messages return only themselves. Messages with multiple child/descendant messages are found as well. >>> r = Relay.objects.get(qid='xo2') >>> r.get_children() [<Relay: server2 foo>, <Relay: server3 bbb>, <Relay: server1 xo2>] If I kill and restart the shell, the next query works as expected, fetching a single message >>> r = Relay.objects.get(qid='singletonMsg') >>> r.get_children() [<Relay: server5 singletonMsg>] But if I run get_children() repeatedly within a single Django shell session, it always includes the results of the previous get_children() calls. >>> r = Relay.objects.get(qid='singletonMsg') >>> r.get_children() [<Relay: server5 singletonMsg>] # expected result >>> >>> r = Relay.objects.get(qid='xo2') … -
Django REST Framework: Direct assignment to the reverse side of a related set is prohibited. Use AuditedClientPeriodMatrices.set() instead
I have the next issue and i dont know why because im send: % self._get_set_deprecation_msg_params(), TypeError: Direct assignment to the reverse side of a related set is prohibited. Use AuditedClientPeriodMatrices.set() instead. Could you help me please? JSON { "clientName": "PRUEBA", "AuditedClientPeriods": [ { "clientNamePeriod": "PRUEBA", "AuditedClientPeriodMatrices": [ { "AuditedClientPeriodMatrizDatas": [] } ] } ] } serializers.py from rest_framework import serializers from ...models import Audited_Client, Audited_Client_Period, Audited_Client_Period_Matriz, Audited_Client_Period_Matriz_Data class AuditedClientPeriodMatrizDataSerializer(serializers.ModelSerializer): class Meta: model = Audited_Client_Period_Matriz_Data fields = [ 'id', 'clientName', 'clientNamePeriod', 'ANIO', 'MES', 'GRUPO', 'DOCUMENTO_MATRIZ', 'NOMBRE_MATRIZ', 'DOCUMENTO_CLIENTE', 'NOMBRE_CLIENTE', 'CNAE_ACTIVIDAD', 'SEGMENTO_IRB', 'ID_EXPEDIENTE', 'IND_DRC', 'SEGMENTO_DRC_S_CIRCULAR', 'TIPO_OPERACION_SUBTIPO_IRB', 'COD_INSOLVENCIA', 'CLASIFICACION', 'CONCEDIDO', 'DPTO_NORMAL', 'DPTO_VIG_ESPECIAL', 'DPTO_DUDOSO', 'DPTO_MUY_DUDOSO', 'DPTO_TOTAL' ] class AuditedClientPeriodMatrizSerializer(serializers.ModelSerializer): #Ojo esta variable esta en related_name en models.py AuditedClientPeriodMatrizDatas = AuditedClientPeriodMatrizDataSerializer(many=True) class Meta: model = Audited_Client_Period_Matriz fields = [ 'id', 'clientName', 'clientNamePeriod', 'matriz', 'author_matriz_audited_client_period', 'created_matriz', 'updated_matriz', 'AuditedClientPeriodMatrizDatas' ] class AuditedClientPeriodSerializer(serializers.ModelSerializer): #Ojo esta variable esta en related_name en models.py AuditedClientPeriodMatrices = AuditedClientPeriodMatrizSerializer(many=True) class Meta: model = Audited_Client_Period fields = [ 'id', 'clientName', 'clientNamePeriod', 'author_audited_client_period', 'created_audited_client_period', 'updated_audited_client_period', 'AuditedClientPeriodMatrices' ] class AuditedClientSerializer(serializers.ModelSerializer): #Ojo esta variable esta en related_name en models.py AuditedClientPeriods = AuditedClientPeriodSerializer(many=True) class Meta: model = Audited_Client fields = [ 'id', 'clientName', 'author_audited_client', 'created_audited_client', 'updated_audited_client', 'AuditedClientPeriods' ] #validated_data es un diccionario # y .pop(key) busca la clave especificada … -
Django admin Site 2 foreignkeys
class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True) Remarks = models.TextField(max_length=500,null=True,blank=True) def __str__(self): suser = '{0.Student_Users} {0.Education_Levels}' return suser.format(self) class ScheduleOfPayment(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE,blank=True, null=True) Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Display_Sequence = models.IntegerField(blank=True, null=True) Date = models.DateField(null=True,blank=True) Amount = models.FloatField(null=True, blank=True) Remark = models.CharField(max_length=500,blank=True, null=True) Status = models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True) /admin StudentsEnrollmentRecordAdmin class StudentsEnrollmentRecordAdmin(admin.ModelAdmin): list_display = ('lrn', 'Student_Users', 'Education_Levels', 'Courses', 'Section', 'Payment_Type', 'amount' ,'School_Year') ordering = ('Education_Levels','Student_Users__lrn') list_filter = ('Student_Users','Education_Levels','Section','Payment_Type') admin.site.register(StudentsEnrollmentRecord,StudentsEnrollmentRecordAdmin) ScheduleOfPayment @admin.register(ScheduleOfPayment) class ScheduleOfPayment(admin.ModelAdmin): list_display = ('Education_Levels','Payment_Type','Display_Sequence','Date','Amount','Remark','Status') ordering = ('Education_Levels','Payment_Type','Display_Sequence') list_filter = ('Education_Levels','Payment_Type') how to combine this two table/listview in Django admin site? please help me, i already research this for 3 days but i cant find solve this problem. -
Can't understand how work @login_required in Django
I look how work @login_required in Django and I can't understand one row. lambda u: u.is_authenticated Please explain me, from where appear 'u'. I can't understand where does this argument come from. Full code def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): actual_decorator = user_passes_test( lambda u: u.is_authenticated, login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator -
why homepage is not showing while runserver in django and after uploading in heroku it's not working?
starting new in django, first i run pipenv and pipenv shell in cmd and then i have stated the "pages" project in django. in pages_project/settings.py file: ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ ................... 'pages.apps.PagesConfig', # new ] TEMPLATES = [ {................. 'DIRS': [os.path.join(BASE_DIR,'templates')],.....} in pages_project/urls.py: from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('pages.urls')), ] in pages/views.py: from django.views.generic import TemplateView Create your views here. class HomePageView(TemplateView): template_name='home.html' class AboutPageView(TemplateView): template_name='about.html' in pages/urls.py: from django.urls import path from .views import HomePageView,AboutPageView urlpatterns = [ path('about/', AboutPageView.as_view(), name='about'), path('', HomePageView.as_view(),name='home'), ] i have created three html files in pages/templates/..... home.html, base.html and about.html home.html code: {%extends 'base.html'%} {%block content%} Homepage {%endblock%} about.html code: {%extends 'base.html'%} {%block content%} About Page {%endblock%} base.html code: Home|About {%block content%} {%endblock%} running python manage.py runserver base.html and about.html is working but when i click on home link it is showing the following: Using the URLconf defined in pages_project.urls, Django tried these URL patterns, in this order: admin/ about/ [name='about'] [name='home'] The current path, home, didn't match any of these. but about link is working and base is showing the front face. this is my first problem. after installing heroku and … -
Django CKEDITOR, Image Upload path different with ImageField upload path
I'm using django-ckeditor to load images.I can't merger my image upload path in model with django-ckeditor image upload path. I have already created a upload image path in models: image = models.ImageField(upload_to="news/%Y/%m") In order to merger it with django-ckeditor,I set this in settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') CKEDITOR_UPLOAD_PATH = 'news/%Y/%m' But although the image upload through django-ckeditor will also be in news directory,however the path will be different from the image that upload through models.ImageField.They both are in news directory but in two different sub directories. Is there any way that can merger the two path into one? -
Django Aggregate from 3 Models with 2 ManyToMany relations
I have the following Django structure: User has a ManyToMany relashionship to Genre and Movie has a ManyToMany relashionship to Genre as well. What I want to achieve is make a query that retrieves only the users that have genres available along with their movies (and movies to have distinct values). So the result would be like this: [{user_id: 1, movies_ids: [1, 2, 3]}, {user_id: 7, movies_ids: [2, 3]}, {user_id: 13, movies_ids: [5, 6, 7]}] I've searched a lot but haven't found a solution. My idea would be to use an ArrayAgg. Something like this: User.objects.filter(genres__isnull=False).annotate( movies_ids=ArrayAgg( Movie.objects.filter(genres__in=???), distinct=True ) ).values('id', 'movies_ids') But I don't know if this is optimal or possible. The number of users and movies are very large and the query would be very slow. -
Can't PUT from Android to DJANGO REST
I have a DJANGO REST server on my personal network that is set up to get and receive JSON strings to update "statuses" for a project I'm working on. I can GET the information down into my Android application just fine but when I try to PUT information up to the server, I get the error: Bad Request: /api/users/1/ [28/Oct/2019 21:23:23] "PUT /api/users/1/ HTTP/1.1" 400 107 I think it's the app because I can successfully do a PUT request via Windows Powershell, but it doesn't work on the Android app. Here is the code using the OKHTTP class: MediaType JSON = MediaType.parse("application/json; charset=utf-8"); String content = String.format("{'status':%s}", selectedStatus); RequestBody body = RequestBody.create(JSON, content); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(IPAddress + "api/users/" + currentUserID + "/") .addHeader("Content-Type", "application/json") .put(body) //PUT .build(); client.newCall(request).execute(); I have tried using the standard HttpURLConnection class, which is what I did for the GET method, but I don't even get a response from the server when I do that. I've tried about a dozen ways to PUT something to the server, but nothing has worked. Any help achieving this goal would be appreciated. Thanks. -
Django Media Files - Failed to load resource: the server responded with a status of 403 (Forbidden)
I dont know how this can be possible I have a model with a user and image and 2 identical for-loops in my template, like: {% for object in object_list %} {{ object.user }} {{ object.image.url }} {% endfor %} This returns a list of users and images as expected. But in the second for-loop, the image of the 4th object in list throws this 403 Forbidden Error. No matter what I do, if I try to replace the file with one that was working before (3rd or 6th in list), the 4th object's image file wont show up. Thank you for any help -
Django REST Framework: Show only latest of nested object, return as un-nested JSON
What I'm trying to do in Django REST Framework: Return only latest nested object in list for an object and return it as JSON, with the sub-object un-nested. My models: class BaseObject(models.Model): name = models.TextField() object_type = models.ForeignKey(ObjectType) class ObjectStatus(models.Model): baseobject_id = models.ForeignKey('objects.BaseObject', related_name='status') object_status = models.IntegerField() object_status_timestamp = models.DateTimeField() My serializers: class ObjectStatusSimplifiedSerializer(serializers.ModelSerializer): #helper serializer to simplify status objects class Meta: model = ObjectStatus fields = ['object_status', 'object_status_timestamp'] class ObjectStatusListSerializer(serializers.ModelSerializer): #request for last status of several objects status = ObjectStatusSimplifiedSerializer(many=True) class Meta: model = BaseObject fields = ['id', 'name', 'object_type', 'status'] My current view: class ObjectStatusListView(generics.ListCreateAPIView): serializer_class = ObjectStatusListSerializer def get_queryset(self): queryset = BaseObject.objects.all() id = self.request.query_params.getlist('id') if id: queryset = queryset.filter(id__in=id) return queryset Current URL: url(r'^objectstatus/status/list$', views.ObjectStatusListView.as_view()), So now, when going to, for example, [...]/objectstatus/status/list?id=9, the result I get looks like this: [ { "id": 9, "name": "r5", "object_type": "router", "status": [ { "object_status": 1, "object_status_timestamp": "2019-10-24T09:40:15.605391Z" }, { "object_status": 2, "object_status_timestamp": "2019-10-24T09:40:28.133296Z" }, { "object_status": 3, "object_status_timestamp": "2019-10-24T09:40:40.829486Z" }, { "object_status": 1, "object_status_timestamp": "2019-10-24T09:40:53.333332Z" } ] } ] What I want is to display only the object status with the most recent timestamp. Also, I can't figure out how to flatten the JSON object, like this: [ … -
Unable to get supervisord celery worker process running on elastic beanstalk django app
I'm trying to get celery beat running on django within an elastic beanstalk environment. I've been following the deployment advice here: How to run a celery worker with Django app scalable by AWS Elastic Beanstalk? After deployment the supervisord process fails to work. This is what's show in the logs: ------------------------------------- /opt/python/log/supervisord.log ------------------------------------- 2019-10-28 19:58:35,321 CRIT Supervisor running as root (no user in config file) 2019-10-28 19:58:35,333 INFO RPC interface 'supervisor' initialized 2019-10-28 19:58:35,333 CRIT Server 'unix_http_server' running without any HTTP authentication checking 2019-10-28 19:58:35,334 INFO supervisord started with pid 3034 2019-10-28 19:58:36,338 INFO spawned: 'httpd' with pid 3118 2019-10-28 19:58:37,805 INFO success: httpd entered RUNNING state, process has stayed up for > than 1 seconds (startsecs) 2019-10-28 19:59:37,279 INFO spawned: 'celeryd-beat' with pid 3543 2019-10-28 19:59:37,289 INFO spawned: 'celeryd-worker' with pid 3544 2019-10-28 19:59:38,023 INFO stopped: celeryd-beat (terminated by SIGTERM) 2019-10-28 19:59:38,325 INFO spawned: 'celeryd-beat' with pid 3552 2019-10-28 19:59:38,383 INFO exited: celeryd-worker (exit status 1; not expected) 2019-10-28 19:59:38,932 INFO exited: celeryd-beat (exit status 1; not expected) I don't understand what these logs are telling me and haven't been able to shed any light on it through my own research. This is the shell script used to create … -
Converting Django project from Python 2 to Python 3: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I am converting a Django website from Python 2 to Python 3. To do this, I ran 2to3 on the whole project. Now, upon running the server (which works fine in Python 2). Now, there appears to be an error django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. that seems to originate with an issue loading the django_comments app. It is not clear to me whether this is related to a templates/models issue or something else. Python3 was installed in the virtual environment for this project. (env) user:project user$ python3 manage.py check Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File ".../src/project/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File ".../src/project/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File ".../src/project/env/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File ".../src/project/env/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File ".../src/project/env/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File ".../src/project/env/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File … -
how to fix a populate models from csv? Primary key unhashable
I'm trying to populate some models from csv files. but when I try to save it I get "TypeError: Model instances without primary key value are unhashable". I already try with get_or_create() but I'm getting the same issue. Models class Clients(models.Model): client_name = models.CharField(max_length=30) def __init__(self, *args, **kwargs): super().__init__() class Products(models.Model): client = models.ForeignKey(Clients, on_delete=models.CASCADE) product_name = models.CharField(max_length=100) address_incl = models.BooleanField() def __init__(self, *args, **kwargs): super().__init__() def log_to_db(self): try: self.save() return 0 except DatabaseError as E: transaction.rollback() print("Add Job Model not saved to DB...transaction rolled back") print("Exception Reason" + E) return 1 Populate script if mode == MODE_CLEAR: return with open("./clientAvailable.csv") as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for row in readCSV: client = Clients() # client.id = row[0] client.client_name = row[1] client.log_to_db() with open("./productsAvailable.csv") as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for row in readCSV: product = Products() print(Clients.objects.get(client_name=row[1])[0]) # product.id = row[0] product.client = Clients.objects.get(client_name=row[1])[0] product.product_name = row[2] product.address_incl = row[3] product.log_to_db() -
How to link a Django model's property in HTML audio source tags?
I've managed to figure out this much thanks to the Django documentation and Stack Overflow of similar problems, but I can't seem to use song.audio as src in my html's <source> tags. The Goal: Display a list of songs with a playable audio file. This is only uploaded from the admin/ page. My Problem: When I inspect element, the <source>'s src prop appears to successfully point towards the audio file, but it does not load it as an actual playable 'thing' in the browser. Chrome inspect of the output of the following code: My Stuff: Folder Structure: song-viewer/ | media/ | | song1.mp3 | | song1_w784FH21.mp3 | | song2.mp3 | | song2_r8JJfq0.mp3 | | song-viewer/ | | __init__.py | | settings.py | | urls.py | | views.py | | songs/ | | migrations/ | | templates/ | | | songs/ | | | | song_list.html | | __init__.pyt | | admin.py | | apps.py | | forms.py | | models.py | | urls.py | | views.py | | static/ | | styles.css | | templates/ | | base_layout.html | | manage.py | README.md | requirements.txt song-viewer/settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static'), ] STATIC_ROOT = '' """ The above …