Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Google Calendar API: writer access error when setting up events on someone's calendar
HttpError 403 when requesting https://www.googleapis.com/calendar/v3/calendars/some-domain.com/events?sendNotifications=true&alt=json returned "You need to have writer access to this calendar."> Hi. I'm getting this error when I try to set a calendar event from my service account via the calendar api. Can someone help figure what it means? Is it due to some access issues on end user's calendars? Or is it due to some limitation on my own service account? Please help. -
NoReverseMatchError 'Reverse for 'password_reset_confirm' not found.' In Django
I was following a Django tutorial series on youtube when I was stuck at a part where we can send an email to the user's email address to reset the password. I was using mostly Django's included functionality for it. I have created a url path in which the user can reset his password but Django somehow don't recognize it. Error: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. I'm guessing there is something wrong with my urls.py My Urls.py from django.conf.urls import url from django.contrib.auth import views as auth_view from django.urls import path app_name = "blog" urlpatterns = [ # for /blog/password-reset/ path('password-reset/', auth_view.PasswordResetView.as_view(template_name='blog/password_reset.html'), name="password_reset"), # for /blog/password-reset/done/ path('password-reset/done/', auth_view.PasswordResetDoneView.as_view(template_name='blog/password_reset_done.html'), name="password_reset_done"), # For /blog/password-reset-confirm/<uidb64>/<token>/ path('password-reset-confirm/<uidb64>/<token>/', auth_view.PasswordResetConfirmView.as_view(template_name='blog/password_reset_confirm.html'), name='password_reset_confirm'), ] My password_reset_confirm.html {% extends 'blog/base_for_log.html' %} {% load crispy_forms_tags %} {% block title %}Reset Password{% endblock %} {% block body %} <div class = "container"> <div class="content-section py-5"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Password Reset </legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type ="submit">Reset Password</button> </div> </form> </div> </div> {% endblock %} I expect the output to be ConnectionRefusedError But It's Showing A NoReserve Error. Thanks … -
Styling errors in the form
There is the following form. <form id="contact_form" class="get-in-touch-form" method="post" enctype="multipart/form-data"> {% csrf_token %} <h1 class="title {% if component.css_title_style %}{{ component.css_title_style }}{% endif %}"> {{ component.title }} </h1> <p class="subtitle {% if component.css_subtitle_style %}{{ component.css_subtitle_style }}{% endif %}"> {{ component.description }} </p> <div class="row"> <div class="col-sm-6"> <div class="input-wrapper"> {{ contact_form.name }} </div> <div class="input-wrapper"> {{ contact_form.email }} </div> <div class="input-wrapper"> {{ contact_form.phone }} </div> <div class="input-wrapper" style="position: relative;"> {{ contact_form.text }} <img id="clip" src="{% static 'images/clip.png' %}" style="position: absolute; left: 95%; top: 5%;" onclick="document.querySelector('#id_file').click()"> </div> <div class="input-wrapper" style="display: none"> {{ contact_form.file }} </div> <div class="input-wrapper"> <div class="col-md-5"> <div class="custom-checkbox"> {{ contact_form.nda }} <label for="checkbox1">Send me an NDA</label> </div> </div> <img src="/static/images/loader.svg" height="65" alt="Loading..." style="display: none;"> <input type="submit" value="Send" class="green-button"> </div> </div> <div class="col-sm-6"> <img src="{% static 'images/map_all.png' %}"> </div> </div> </form> When I submit it and errors occur, text is displayed near the field that generates the error in its usual form. How can I style this text? For example, to highlight this field somehow? I tried to do this through ajax, but it didn’t work. When I try to send a form containing errors to the server, I immediately get an error (for example, this field is required) and accordingly … -
How to fix 'ImportError: No module named search' error in django 1.8
I'm get an error when running "python manage.py makemigrations" Command in putty. please Help!!! thanks o lot from dslam.views import * File "/opt/PortMan/portman_web/dslam/views.py", line 16, in from django.contrib.postgres.search import SearchVector ImportError: No module named search when running "pip install django-contrib-postgres" Command, I,m Get This Message: "Requirement already satisfied: equirement already satisfied: /usr/local/lib/python2.7/dist-packages (0.0.1)" -
How to properly use django apphooks
below is my django cms apphook, its showing the app on the drop down but it doesn't hook the application to a page. the project is in django 2.1.11, python3.7.1 and django cms 3.6.0 I have tried to change the apphook file to cms_apps.py and cms_app.py . I I have tried this tutorial https://www.youtube.com/watch?v=Dj8dhgmzlFM&t=2903s. i would be happy if one can share a working manual for this procedure. from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool @apphook_pool.register # register the application class PeoplemanagerApphook(CMSApp): app_name = "peoplemanager" name = "People Application" def get_urls(self, page=None, language=None, **kwargs): return ["peoplemanager.urls"] the page loads but does not display the contents of the model -
Django Cookie Prefix to pass securityheaders.com
securityheaders.com fails my configurations with the following error: Set-Cookie There is no Cookie Prefix on this cookie. And this is the value of the cookie: Set-Cookie sessionid=123456789123456789123456789; expires=Thu, 12 Sep 2019 06:51:38 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=Strict; Secure I have tried to add the cookie prefix with in settings.py: CSRF_COOKIE_NAME = '__Secure-csrftoken' But it seems to be a different paramater. I have search the documentation and that is all I could find, and seems to not be applicable. securityheaders.com on cookie prefixes states that it needs to start with __Secure- or __Host- -
Django FileField's upload_to not being called during tests
I have a models.py module that looks like this: def get_path(instance, filename): try: # Something except Exception: raise ValidationError("A very specific error message.") return f"path/to/{instance.pk}_{filename}" class FinalDocument(models.Model): # ... file = models.FileField(upload_to=get_path) class TempDocument(models.Model): # ... file = models.FileField() I have an endpoint that, among other things, grabs a file from a TempDocument instance and assigns it to an existing FinalDocument instance. In real life, this endpoint is failing with "A very specific error message". During tests, however, I cannot for the life of me reproduce this error. I have placed a breakpoint in the upload_to function and it is simply not called. I am assuming this has something to do with different testing vs production settings, but I haven't been able to figure out what. Any idea what I could be missing? -
Django raw query - connection.cursor() data is not showed
When I use Table.objects.raw(raw query), I can see data. When I use connection.cursor(), cursor.execute(same raw query), data is not showed in a HTML page. What's the cause? oracle 11g cx-Oracle 7.2.2 Django 1.11.22 #ORM raw query - It's OK. class UserList(ListView): query = 'select user_id, user_name from user' queryset = USER.objects.raw(query) context_object_name = 'user_list' template_name = 'user_list.html' # Problem - data is not showed in screen. class UserList(ListView): with connection.cursor() as cursor: cursor.execute('select user_id, user_name from user') queryset = cursor.fetchall() context_object_name = 'user_list' template_name = 'user_list.html' #user_list.html <h2>User List(ListView Sample)</h2> <table border="1" align="center"> <tr> <th scope="col">User ID</th> <th scope="col">User Name</th> </tr> {% for user in user_list %} <tr> <th width="200"><a href="http://127.0.0.1:8000/sec/userlist/{{ user.id }}/">{{ user.user_id }}</a></th> <th width="200">{{ user.user_name }}</th> </tr> {% endfor %} </table> No error messages. But data is not showed in a HTML page -
Adding extra field from other Model into Modelform along with giving attr
I'm making Modelform for custom doors ordering platform and i would like to insert additional field from different Model into my Modelform in order to use it's value to insert it as new attribute. So, this is how it looks like: Models.py from django.db import models class Door(models.Model): title = models.CharField(max_length=200, blank=False, null=False) excluded = models.CharField(max_length=50, default="", blank=True, null=False) class Order(models.Model): title = models.CharField(max_length=200, blank=False, null=False) door = models.ForeignKey('Door', verbose_name=u"Type", on_delete=models.CASCADE, default=1, blank=False, null=True) ... forms.py from .models import Door, Order class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['door',] #adding additional class using widgets widgets = { 'door': forms.RadioSelect(attrs={ 'class': 'radioselect' }), ... index.html <form id="d_form" method="POST"> {% csrf_token %} {{ ord_form.as_p }} <input type="submit" value="Order" class="btn btn-danger"> </form> Rendered output: <li> <label for="id_door_1"><input type="radio" name="door" value="2" class="radioselect" required id="id_door_1">some option </label> </li> Everything renders properly, hovewer i would like to add extra new attr into radio input containing it's value, based on field excluded=ITS VALUE from Door model. Expected render: <li> <label for="id_door_1"><input type="radio" excluded='ITS VALUE' name="door" value="2" class="radioselect" required id="id_door_1">some option </label> </li> How to insert it? -
How to integrate voice with django
I wrote a program in python which converts from speech to text and text to speech it was working fine in the console but how to integrate with a Django application instead of writing in a todo app I need speech powered, How to do? -
Failed to connect django with MS sql Server database
i have a django project that need to connect with MS SQL server database the problem is that once i runs the server it display this error : djago.db.utils.operationalError:('08001','[08001] [microsoft][odbc sql server driver]neither dsn nor server keyword supplied (0) (sqldriverconnect); [08001] [microsoft][odbc sql server driver] Invalid connection string attribute (0)') that what i did in settings.py: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'testDB', 'HOST': 'DESKTOP-LPD1575\\SQLEXPRESS', 'OPTIONS': { 'driver':'ODBC Driver 13 for SQL Server', } } } views.py from django.shortcuts import render import pyodbc from .models import Artist Create your views here. def connect(request): conn = pyodbc.connect( 'Driver={ODBC Driver 13 for SQL Server};' 'Server=ip address;' 'Database=testDB;' 'Trusted_Connection=no;' 'UID=test;' 'PWD=test;' ) cursor = conn.cursor() c = cursor.execute('SELECT "first name" FROM t1 WHERE id = 3 ') return render (request,'connect.html',{"c":c}) -
How to call a API Auth function from templates in Django
Im new in django, but i know that if u have a function you have to set it up in the models.py(correct me if wrong), and then for it to show it you have to call it from the templates. Im trying to make a django cms that connect to the Google Analytics API and export information. The first step is the authentification which the code is provided by google in HelloAnalytics.py : import argparse from apiclient.discovery import build import httplib2 from oauth2client import client from oauth2client import file from oauth2client import tools def get_service(api_name, api_version, scope, client_secrets_path): .... def get_first_profile_id(service): ... def get_results(service, profile_id): ... def print_results(results): ... def main(): service = get_service('analytics', 'v3', scope, 'client_secrets.json') profile = get_first_profile_id(service) print_results(get_results(service, profile)) if __name__ == '__main__': main() So basically i want to call the main() function , that takes no parameters, from a template so i can retrieve the information, i dont know if it is necesary to create a Class or not. I have tried to set it in the views.py but i dont have any results. Thanks in advance i tried creating a random class Main(models.Model): that have all these functions inside and from the views.py create an … -
Unable to display login user full details?
I'm new to django i unable to display current login user full details by username. when i will try with Exam.objects.get(username=username) i will get error query not exist and i will try with Exam.objects.all() it will display username only.Please tell me how can i display current login user profile details forms.py -------- from django import forms from testapp.models import Exam from django.contrib.auth.models import User from django.core import validators class ExamForm(forms.ModelForm): password = forms.CharField(max_length=32, widget=forms.PasswordInput) rpassword=forms.CharField(label='Re Enter Password',widget=forms.PasswordInput) first_name = forms.CharField(max_length=40, required=True) last_name = forms.CharField(max_length=40, required=True) phone = forms.IntegerField() date_of_birth=forms.DateTimeField(help_text='DD/MM/YYYY H:M',input_formats=['%d/%m/%Y %H:%M']) gender = forms.CharField(max_length=10, required=True) location = forms.CharField(max_length=40, required=True) photo = forms.ImageField(help_text="Upload image: ", required=False) class Meta: model = Exam fields = ('username','password','rpassword','first_name','last_name', 'email','date_of_birth','gender','photo','location','phone') views.py -------- def maas(request,maas_username_slug): context_dict = {} try: maas = Exam.objects.get(slug=maas_username_slug) context_dict['maas_username'] = maas.username context_dict['maas_username_slug'] = maas_username_slug context_dict['maas_phone'] = maas.phone context_dict['maas_firstname'] = maas.firstname context_dict['maas_lastname'] = maas.lastname context_dict['maas_location'] = maas.location context_dict['date_of_birth'] = maas.date_of_birth context_dict['maas_gender'] = maas.gender context_dict['photo'] = maas.photo context_dict['maas'] = maas except Exam.DoesNotExist: pass print(context_dict) return render(request, 'testapp/profile.html', {'context_dict':context_dict}) urls.py ------- urlpatterns = [ url(r'(?P<maas_username_slug>\w+)/$', views.maas, name='profile'), ] profile.html ------------ {%extends 'testApp/base.html'%} {%block body_block%} <h1>Profile page:</h1> <h1>{{maas_lastname}}</h1> <h1>{{maas_username}}</h1> {%endblock%} -
Django. Rest Framework. Nested relationships empty result
Need some advice. I set up seralization. There are no errors. But at the output I get empty tags. I broke my head, what am I doing wrong? models.py: class kv(models.Model): title = models.CharField(max_length=200) price = models.IntegerField() address = models.CharField(max_length=200) property_type = models.CharField(choices=realty_type_choices_admin, default='kv', max_length=200, blank=True) country = models.CharField(default='Россия', max_length=200) region = models.CharField(max_length=200) state = models.CharField(choices=state_choices_admin, default='DGO', max_length=200, blank=True, null=True) locality_name = models.CharField(max_length=200, blank=True, null=True) address_xml = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) serializers.py from rest_framework import serializers from listings.models import kv class kvSerializerLocation(serializers.ModelSerializer): class Meta: model = kv fields = ['country', 'region', 'state', 'locality_name', 'address_xml', 'city'] class kvSerializer(serializers.ModelSerializer): category = serializers.CharField(source='get_property_type_display') url = serializers.CharField(source='get_absolute_url', read_only=True) country = kvSerializerLocation() class Meta: model = kv fields = ['title', 'price', 'address', 'category', 'url', 'country'] views.py from listings.models import * from rest_framework import viewsets from rest_framework_xml.renderers import XMLRenderer from .serializers import kvSerializer class KvXMLRenderer(XMLRenderer): root_tag_name = 'feed' item_tag_name = 'offer' def _to_xml(self, xml, data): super()._to_xml(xml, data) class kvViewSet(viewsets.ModelViewSet): queryset = Kvartiry.objects.all().filter(is_published=True) serializer_class = kvSerializer renderer_classes = [KvXMLRenderer] Result: <country> <state/> <locality_name/> <address_xml/> <city/> </country> It’s strange. Tags are empty, there is no region tag at all Thank! -
Django form data isn't saving to database
i'm trying to allow a user to update their user profile with a city, description, website address etc. Using Django 2.0, I have two forms in one view: EditProfileForm (EPF) = Form for email, first and last name and password The EditProfileForm seems to be able to save data. However, EditUserProfile seems to not. EditUserProfile (EUP) = Form for further user info such as city, description, website address etc. When entering the data and submitting the form, the data for EUP form doesn't appear to save or update the user information I've also tried methods such as: if form_EUP.is_valid(): obj = form_EUP.save(commit=False) obj.user = request.user obj.save() and trying to create a similar custom save method to the format used in RegistrationForm but i've had no luck I'm a bit of a beginner to the django framework so any ideas would be much appreciated, cheers. views.py def edit_profile(request): if request.method == 'POST': form_EPF = EditProfileForm(request.POST, instance=request.user) form_EUP = EditUserProfile(request.POST, instance=request.user) if form_EPF.is_valid(): form_EPF.save() return redirect(reverse('accounts:view_profile')) if form_EUP.is_valid(): form_EUP.save() return redirect(reverse('accounts:view_profile')) else: form_EPF = EditProfileForm(instance=request.user) form_EUP = EditUserProfile(instance=request.user) args = {'form_EPF': form_EPF, "form_EUP": form_EUP} return render(request, 'accounts/edit_profile.html', args) forms.py class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ( … -
Clear the page section link from url after redirect
I'm getting deeper into a django, and I've come across an issue I'm not sure how to solve. I've managed to make a popup box using just html and css for my forms, so both the create and update form load onto one page, and i can access them using page section links. The issue i have is that when I create a new post, or update a post, the page section link stays in the URL and the popup form remains visible. I've tried adding action="." to the form but that seems to break my update form, and stops working; it just redirects back to my list view with the create form filled in with the updated information. my views.py def list_view(request): block_query = Block.objects.all() new_form_query = BlockForm(request.POST or None) if request.method == 'POST': if new_form_query.is_valid(): new_block = new_form_query.save() new_form_query = BlockForm() return redirect('bulkapp:one_view', slug_id=new_block.slug) return render(request, 'bulkapp/list.html', {'block_list': block_query, 'new_form': new_form_query}) def single_view(request, slug_id): single_block_query = get_object_or_404(Block, slug=slug_id) new_form_query = BlockForm(request.POST or None) update_form_query = BlockForm(request.POST or None, instance=single_block_query) if request.method == 'POST': if new_form_query.is_valid(): new_block = new_form_query.save() new_form_query = BlockForm() return redirect('bulkapp:one_block', slug_id=new_block.slug) if update_form_query.is_valid(): update_form_query.save() update_form_query = BlockForm() return redirect('bulkapp:one_view', slug_id=slug_id) return render(request, 'bulkapp/single.html', {'one_block': single_block_query, … -
'MySQL server has gone away' for get_aggregation in django
I was noticed after some time that my application starts to fail on database call. File "/home/user/django/django_projects/m.py", line 64, in start_action user_exists = MyUser.objects.filter(player_id=user_id).count() != 0 File "/home/user/bin/python-2.7/lib/python2.7/site-packages/django/db/models/query.py", line 364, in count return self.query.get_count(using=self.db) File "/home/user/bin/python-2.7/lib/python2.7/site-packages/django/db/models/sql/query.py", line 499, in get_count number = obj.get_aggregation(using, ['__count'])['__count'] File "/home/user/bin/python-2.7/lib/python2.7/site-packages/django/db/models/sql/query.py", line 480, in get_aggregation result = compiler.execute_sql(SINGLE) File "/home/user/bin/python-2.7/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 899, in execute_sql raise original_exception OperationalError: (2006, 'MySQL server has gone away') The table is quite small (I had the same error with 0 or 10 records to aggregate). When I replace user_exists = MyUser.objects.filter(player_id=user_id).count() != 0 with user_exists = len(MyUser.objects.filter(player_id=user_id)) != 0 (move aggregation to python code) it starts to work fine. I have Django 1.11.9. So I was able to fix it with quick hack, but it is not good and I want to understand what is the reason why aggregation query fails. Any idea why it could happen? Thanks. -
Redirect To WebPage after Twilio SMS sent on website / but do not redirect if sms sent through phone
I am using a single twilio number to trigger an sms being sent through a django function. If person accesses my app through my website then app will parse sendphonenum from a post request from website If person accesses my app by sending sms to twilio number, it will parse sendphonenum from text message Problem occurs after twilio has sent message to sendphonenum. If message was triggered from website it should redirect to dashboard page for user who sent message. But don't do this if message was triggered through an initial sms. @csrf_exempt def sms_response(request): if request.method == "POST": # parse sendphonenum from text message sent from mobile phone to twilio number +14545552222 # or parse sendphonenum from a post request from website message_body = request.POST['Body'] sendnum_ary = re.findall('[0-9]+', message_body) sendnum = "".join(sendnum_ary) sendphonenum = "+1" + sendnum mytwilionum = "+14545552222" # put your own credentials here ACCOUNT_SID = "123434234234" AUTH_TOKEN = "abcsdasda" client = Client(ACCOUNT_SID, AUTH_TOKEN) client.messages.create( to= sendphonenum, from_= mytwilionum, body='someone told me to message you' ) ## there is no platform variable, just doing some mock code to show you what I'd want to happen ## note sms_response function url must be same for both website and … -
DateTime filter in django rest
I am creating an api which returns weather data of particular city for n number of days given.(api definition: weatherdata/city_name/ndays/).I have problem sorting out data for ndays. I sorted out the city name using simple icontains. similarly I want to sort out for ndays. previous ndays data needs to be shown. example: suppose today is 2019-08-29, on providing ndays to be 6, weather data of particular city has to be provided from 2019-08-24 to 2019-08-26. views.py class weatherDetail(APIView): def get_object(self, city_name, ndays): try: x = weatherdata.objects.filter(city_name__icontains=city_name) now = datetime.datetime.now() fromdate = now - timedelta(days=ndays) y = return x except Snippet.DoesNotExist: raise Http404 def get(self,*args,**kwargs): city_name = kwargs['city_name'] snippet = self.get_object(city_name,ndays) serializer = weatherdataserializer(snippet,many =True) return Response(serializer.data) models.py class weatherdata(models.Model): city_name = models.CharField(max_length = 80) city_id = models.IntegerField(default=0) latitude = models.FloatField(null=True , blank=True) longitude = models.FloatField(null=True , blank=True) dt_txt = models.DateTimeField() temp = models.FloatField(null = False) temp_min = models.FloatField(null = False) temp_max = models.FloatField(null = False) pressure = models.FloatField(null = False) sea_level = models.FloatField(null = False) grnd_level = models.FloatField(null = False) humidity = models.FloatField(null = False) main = models.CharField(max_length=200) description = models.CharField(max_length=30) clouds = models.IntegerField(null=False) wind_speed = models.FloatField(null = False) wind_degree = models.FloatField(null = False) urls.py urlpatterns = [ path('admin/', admin.site.urls), … -
Django: unique_together for foreign field
For next two models: class Foo(models.Model): parent = models.ForeignKey(Parent) name = models.CharField() class Bar(models.Model): foreign = models.ForeignKey(Foo) value = models.CharField(max_length=20) I need to have unique_together constraint for Bar model: class Meta: unique_together = ('value', 'foreign__parent') Which is impossible in Django. But is it possible to achieve this on database level (Postgresql) with some contraint or model level validation to omit possible case (lock table?) when simultaneously same value may be saved to different Bar instances? Django 2.2.4 No ModelForm or default validate_unique() -
What's the best way to handle service accounts in django?
I have a Django / REST framework application that needs to recieve logs from remote workers and store them as objects in the database so that they can be provided to users through the web interface. I am using the standard DRF token authentication and I was thinking the best way to do this would be to create a service account with permissions restricted to PUT on the log view, so that the workers could use this to send logs back to the django app. Is there a way I can have an account with token authentication but without password login? Is there any best practices / reading material around service accounts, or is there a better way of achieving this goal? I can't seem to find anything relevant. Is there an easy way of generating such an account on initial setup without having to use the admin interface so that it is ready to go on install? Thanks in advance -
django group by on annotated data
I have a result queryset which contains annotated data. I want to further group by on column hour and want to sum of another column number for hour. For example , i have a queryset:- <QuerySet [{'hour': 10, 'num_time': 101}, {'hour': 10, 'num_time': 1}, {'hour': 10, 'num_time': 2}, {'hour': 10, 'num_time': 4}, {'hour': 10, 'num_time': 1}, {'hour': 10, 'num_time': 13}, {'hour': 10, 'num_time': 6}, {'hour': 10, 'num_time': 2}, {'hour': 10, 'num_time': 3}, {'hour': 10, 'num_time': 8}, {'hour': 10, 'num_time': 4}, {'hour': 10, 'num_time': 6}, {'hour': 10, 'num_time': 1}, {'hour': 10, 'num_time': 3}, {'hour': 10, 'num_time': 18}, {'hour': 10, 'num_time': 3}, {'hour': 10, 'num_time': 19}, {'hour': 10, 'num_time': 3}, {'hour': 10, 'num_time': 14}, {'hour': 10, 'num_time': 4}, '...(remaining elements truncated)...']> I want below result:- [{'hour': 10, 'num_time' : 210},{'hour': 18, 'num_time': 30}] How can i achieve with django queryset? Here is my query for first queryset resullt:- table_name.objects.filter(id=id,created_time__isnull=False,day__range=[(date.today()-timedelta(days=30)),date.today()]).annotate(hour=ExtractHour('created_time'),num_time = Sum('A') + Sum('B') + Sum('C') + Sum('D')).values('hour', 'num_time').order_by('hour') Any help will be much appreciated!! -
Difference between two model fields
I have a model named 'CarAdd', and two other models are connected with a foreign key to this CarAdd model that are ShippingDetails, MaintenanceDetails. and each foreign key model has an item and price field." foreign key have more than 2 items under one id" I need to find the profit amount of each car profit = sold_amount - (purchased amount + total shipping cost + total maintenance cost) class CarAdd(models.Model): # Car Details name = models.CharField(max_length=60) purchased_amount = models.DecimalField() # there 3 choices in STATUS shipped, maintenance, sold status = models.CharField(max_length=12, choices=STATUS) sold_amount = models.DecimalField(max_digits=15, decimal_places=1) profit_amount = models.DecimalField(max_digits=15, decimal_places=1) class ShippingDetails(models.Model): car = models.ForeignKey(CarAdd, related_name='shipping_details', on_delete=models.CASCADE) item = models.CharField(max_length=60) price = models.DecimalField(max_digits=15, decimal_places=1,) class MaintenanceDetails(models.Model): car = models.ForeignKey(CarAdd, related_name='maintenance_details', on_delete=models.CASCADE) item = models.CharField(max_length=60) price = models.DecimalField(max_digits=15, decimal_places=1) class CarAdd(models.Model): def save(self, *args, **kwargs): if self.status == 'sold': sum_invested = self.purchased_amount + ShippingDetails.price + MaintenanceDetails.price profit = self.sold_amount - sum_invested self.profit_amount = profit super().save(*args, **kwargs) how do I calculate the profit amount and save to profit_amount field -
505 Error could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432?
0 This is my first project to publish with django on Google Cloud Console but it gives the error : could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? Other pages load but when I want to connect to the psql db this is the error message I get after i set debug to True -
Does ajax run on PythonAnywhere?
My page worked fine on localhost. I deployed my page on PythonAnywhere and it pop up a "500 Internal Server Error" when I tried to submit a form using POST method. The error point to jquery.min.js and my ajax code. $(document).on('submit', '#CustomerRequest', function(e){ e.preventDefault(); $.ajax({ <!--This line is where the error is--> type:'POST', url:'/create_request', data:{ ... Do I need to add anything for PythonAnywhere to run ajax? I read somewhere that a page need SSL for ajax to run, is it true?