Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: cannot swicth to postgresql, django.db.utils.OperationalError: FATAL: no pg_hba.conf entry for host
I'm trying to deploy my app into elasticbeanstalk. But it's never successful at all.. I'm trying to switch sqlite3 into postgresql(elephantsql) but this error happens when I do python manage.py makemirations django.db.utils.OperationalError: FATAL: no pg_hba.conf entry for host "59.168.131.187", user "username", database "databasename", SSL on FATAL: no pg_hba.conf entry for host "", user "username", database "databasename", SSL off I set all environment variables on local and eb consoled. I deleted all virtual environment folder and migration folder but this error still happens. How can I fix this error? -
proxy set up for leaflet and geoserver
Hello guys I'm using this function getfeatureinfo but it is making an error: Failed to load http://localhost:8080/geoserver/geodjango/wms?REQUEST=GetFeatureInfo&SERVICE=WMS&SRS=EPSG%3A4326&STYLES=&TRANSPARENT=true&VERSION=1.1.1&FORMAT=image%2Fpng&BBOX=20.733341574668888%2C42.22036192020024%2C20.73929607868195%2C42.222745498029965&HEIGHT=600&WIDTH=1110&LAYERS=geodjango%3Alayer_ww_manholes&QUERY_LAYERS=geodjango%3Alayer_ww_manholes&INFO_FORMAT=text%2Fhtml&X=593&Y=219: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8000' is therefore not allowed access. I was trying to configure django cors headers but non of the configurations worked. I read that I should configure a proxy but till now I haven't found much success. Can somebody help me on this issue? -
SoftDelete in Django
Problem Statement I have created a base model: class CreateUpdateDeleteModel(models.Model): from django.contrib.auth import get_user_model from django.utils.text import gettext_lazy as _ from drfaddons.datatypes import UnixTimestampField create_date = UnixTimestampField(_('Create Date'), auto_now_add=True) created_by = models.ForeignKey(get_user_model(), on_delete=models.PROTECT) delete_date = UnixTimestampField(_('Delete Date'), null=True, blank=False) deleted_by = models.ForeignKey(get_user_model(), on_delete=models.PROTECT) update_date = UnixTimestampField(_('Date Modified'), auto_created=True) updated_by = models.ForeignKey(get_user_model(), on_delete=models.PROTECT) class Meta: abstract = True I want that in my system, all the elements are soft deleted i.e. whenever an object is deleted, it should behave as follow: Show error in any related object has set on_delete=models.PROTECT. Set delete_date Never show it anywhere (incl. admin) in any query. How do I do this? I am thinking to override get_queryset() which may solve problem 3. But what about 1 & 2? -
AttributeError: 'tuple' object has no attribute 'get' in Django
I want to add a multiple choice field to my project app. But I get an error. Before I added the multiple choice field, this part did not give any error. Where is my mistake? views.py def project_new(request): if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): project = Project() ... project.lang_choices = form.cleaned_data['select_lang'] project.save() return redirect('projects') else: form = ProjectForm() return render(request, 'blog/project_new.html', {'form': form}) @login_required(login_url='/login/') def project_details(request, pk): project = get_object_or_404(Project, pk=pk) return render(request, 'blog/project_detail.html', {'project': project}) models.py class ProgrammingLanguage(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Project(models.Model): ... select_langs = models.ManyToManyField(ProgrammingLanguage) ... slug = models.UUIDField(default=uuid.uuid4) ... forms.py class ProjectForm(forms.Form): ... select_lang = forms.ChoiceField( label='diller: ', widget=forms.CheckboxSelectMultiple() ) def __init__(self, *args, **kwargs): super(ProjectForm, self).__init__(args, kwargs) self.fields['select_lang'].choices = [(l.id, l.name) for l in ProgrammingLanguage.objects.all()] class Meta: model = Project fields = ( 'first_name', 'last_name', 'email', 'project_name', 'project_description', 'project_notes', 'select_langs') -
how to change data dymanically in chartjs
i am new to this technology so i dono how to do this Here i have mentioned My Html content i don't know how to change dynamically in labels.i get the data in dataset field but labels data cant change how to for loop using in label .i use the for loop nut its not working please help me to this.i have mentioned My Html content i don't know how to change dynamically in labels.i get the data in dataset i have mentioned My Html content i don't know how to change dynamically in labels.i get the data in dataset <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JS Bin</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> </head> <body> <div class="container"> {% for i in sale %} {{i}} {% endfor %} <div class="row"> <h1>Google Analytics</h1> </div> <div class="row"> <div class="col-md-3"> <label class="light">Month</label> <select id="monthid" class="form-control form-control-sm rounded"> <option selected="selected"> Choose Option </option> {% for i in month %} <option value="{{ i.id }}">{{ i.month }}</option> {% endfor %} </select> </div> <div class="col-md-6"></div> <div class="col-md-3"> <label class="light">Category</label> <select id="categoryid" class="form-control form-control-sm rounded"> <option selected="selected"> Choose Option </option> {% for i in chartTitle β¦ -
django python - How do I use c++ library in web python?
I have a c++ library that I call its function from my python app by follow command: from ctypes import * print("Step 1: Load Library") try: keyadll = windll.LoadLibrary(r"f:\Win32PKEClass.dll") except: print("Error in load Keya2DLL") windll.keyadll.sign("ehsan") my function load successfully. but in django python project (views.py), when I use this command so it occur follow error: OSError at / [WinError 126] The specified module could not be found Request Method: GET Request URL: http://localhost:54212/ Django Version: 2.1.1 Exception Type: OSError Exception Value: [WinError 126] The specified module could not be found Exception Location: C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\lib\ctypes\__init__.py in __init__, line 348 Python Executable: C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_86\python.exe Python Version: 3.6.6 Python Path: ['E:\\KeyA3 Git\\WebPythonPKE\\WebPythonPKE\\WebPythonPKE', '', 'E:\\KeyA3 Git\\WebPythonPKE\\WebPythonPKE\\WebPythonPKE', 'C:\\Program Files (x86)\\Microsoft Visual ' 'Studio\\Shared\\Python36_86\\python36.zip', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_86\\DLLs', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_86\\lib', 'C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\Python36_86', 'C:\\Program Files (x86)\\Microsoft Visual ' 'Studio\\Shared\\Python36_86\\lib\\site-packages'] Server time: Mon, 17 Sep 2018 06:40:26 +0000 Where do I change? -
django/celery multiple queues not consuming any task
I'm new to celery and django In my celery setup when I invoke tasks without any queues it working perfectly with multiple workers. But When I specify queues the workers don't consume anything I have a project called example here the structure βββ example β βββ celery.py β βββ __init__.py β βββ settings.py β βββ urls.py β βββ wsgi.py βββ mailer β βββ admin.py β βββ apps.py β βββ __init__.py β βββ migrations β β βββ __init__.py β β βββ __pycache__ β β βββ __init__.cpython-36.pyc β βββ models.py β βββ tasks.py β βββ tests.py β βββ views.py βββ manage.py In settings.py (Queue setting) # ============================== # CELERY SETTINGS # ============================== CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' CELERY_ROUTES = { 'example.mailer.tasks.first_task': {'queue': 'first_queue'}, 'example.mailer.tasks.second_task': {'queue': 'second_queue'}, } And my mailer/tasks.py @shared_task def first_task(): for i in tqdm(range(100000000)): pass return "First task finished" @shared_task def second_task(): for i in range(100000000): print(i,'Second Task') return "Second task finished" with this when I run workers like celery -A example worker -l info -c 4 -n worker1 celery -A example worker -l info -c 2 -n worker2 It's working perfect but when I try β¦ -
Regex of email works with decimal value as well. How do I fix it?
I have the following two regex patterns. url(r"^list/(?P<email>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})?/?", MyFunction_ListAPIView.as_view()), url(r"^list/(?P<id>[\d+])/$", OtherFunction_ListAPIView.as_view()), I wanted to have two separate functions for email and for id. If an email is passed MyFunction should be called however if a decimal value is passed then OtherFunction should be called. I just passed in a decimal value like so - Here 11 is a decimal value and not regex. Yet it is still calling the same function. Any suggestions on what I might be doing wrong ? http://127.0.0.1:8000/api/job/list/11/ -
Django disable cascade delete from settings file
i just noticed that deleting an object which has a relation to itself causes to delete the related object as well: class STH(models.Model): ... partner = models.ForeignKey(STH, blank=True, null=True) In [1]: sth = STH.objects.get(name = 'sth01') In [2]: sth.partner Out[2]: <STH: sth02> In [3]: sth.partner.partner Out[3]: <STH: sth01> In [4]: sth.delete() Out[4]: (2, {'app.Disk': 0, 'app.STH': 2}) . I' d like to change this behavious from setting.py that this won' t delete the partner, only the original object and set the relation to NULL . How can i achieve that? Django: 1.9.x Python: 3.4.5 Postgresql: 9.4.x Many thanks. -
Django - Login - Forbidden (CSRF token missing or incorrect.):
I am getting the Forbidden (CSRF token missing or incorrect.) error when I try to use login page. The scenario is as follows: An user has two tabs open. Both tabs are login pages. In tab 1, user successfully logged in, and was redirected to a new page where login is required. In tab 2, user hasn't refreshed the page, and is still in the login page. In the Django backend, user is already authenticated, but the front-end template hasn't noticed it yet. In tab 2, when I click on login button, I get Forbidden (CSRF token missing or incorrect.) error. I made sure that csrf_token is in the form. This error occurs only when I'm using two tabs. I'm using AJAX Why is this happening? How can I fix it? I don't know this would help, but here is my views.py for login class Login_View(LoginView): template_name = 'login.html' def post(self, request, *args, **kwargs): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) response_data = {} if user is not None: if user.is_active: login(request, user) response_data['result'] = 'success' else: return HttpResponse("Inactive user.") else: response_data['result'] = 'fail' return HttpResponse(json.dumps(response_data), content_type="application/json") -
how can i display average of time spent (in_time and out_time) in django? do i use aggregation?
I am new to django and i am facing a problem in displaying the average of time My database model is from django.db import models class Employee(models.Model): class Meta: db_table = 'Employee' emp_id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100, blank=True, null=True) department_id = models.IntegerField(blank=True, null=True) position = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.name class AttendanceRecord(models.Model): class Meta: db_table = 'AttendanceRecord' emp_id = models.ForeignKey(Employee, on_delete=models.CASCADE) # emp_id = models.CharField(max_length=100, blank=True, null=True) date = models.CharField(max_length=100, blank=True, null=True) miti = models.CharField(max_length=100, blank=True, null=True) day = models.CharField(max_length=100, blank=True, null=True) in_time = models.CharField(max_length=100, blank=True, null=True) out_time = models.CharField(max_length=100, blank=True, null=True) punch_count = models.IntegerField(blank=True, null=True) time_spent = models.FloatField(blank=True, null=True) difference_time = models.FloatField(blank=True, null=True) def __str__(self): return self.emp_id.name class Department: class Meta: db_table = 'Department' department_id = models.IntegerField(primary_key=True) staff_count= models.IntegerField() My Report view is: I want to average the in_time so that i can average it and display in the report template. i cant figure out how. from attendance.models import AttendanceRecord class Report: def get_all_employee_data(from_date, to_date): all_employee_list = AttendanceRecord.objects.filter(miti__gt=from_date, miti__lt=to_date).order_by( '-miti') return all_employee_list def get_specific_emp_data(from_date, to_date, e_id): specific_employee_list = AttendanceRecord.objects.filter(miti__gt=from_date, miti__lt=to_date, emp_id=e_id).order_by('-miti') return specific_employee_list -
webpack-stats.json not found in Django using Angular as frontend
Right now I am trying to follow up this blog where I need to set up angular as frontend and django as backend. When I do ng eject from angular side I am able to see webpack.config.js and there is was mentioned to edit that file and add: var BundleTracker = require('webpack-bundle-tracker'); /*...*/ module.exports = { /*...*/ plugins:[ /*...*/ new BundleTracker({filename: '../webpack-stats.json'}) ] } But right now I am not sure where to find this webpack-stats.json because it was not ejected when I did ng eject Same with Django we added this in settings.py: WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': '', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), } } But again Django is not able to find webpack-stats.json So can anyone help me with this file as if how to generate it and what's the role of it as I am not able to produce it or no proper instruction was given in the blog which I mentioned -
"The submitted data was not a file. Check the encoding type on the form." Error In RestFramework
I am making a student admission system for that i need to upload image ,When iam uploading image my models.py looks like this, models.py: def scramble_uploaded_filename(instance, filename): extension = filename.split(".")[-1] return "{}.{}".format(uuid.uuid4(), extension) class StudentAdmission(BaseModel): student = models.ForeignKey(Student,on_delete=models.CASCADE) admission_date = models.DateTimeField(auto_now_add=True) batch = models.IntegerField() course = models.ForeignKey(Course,on_delete=models.CASCADE) description = models.CharField(max_length=120) image = models.ImageField("Uploaded image", upload_to=scramble_uploaded_filename) And im using a planeSerializer imageField in serializers.py like this: serializers.py class StudentAdmissionBaseSerializer(serializers.Serializer): user = UserSerializer() user_detail = UserDetailSerializer() phone_detail = PhoneSerializer() address_detail = AddressSerializer() registration_no = serializers.IntegerField() batch = serializers.IntegerField() description = serializers.CharField(default='') image = serializers.ImageField() And My views.py looks like this: views.py: class StudentAdmissionViewSet(viewsets.ModelViewSet): queryset = StudentAdmission.objects.all() serializer_class = StudentAdmissionSerializer parser_classes = (NestedMultipartParser,) def get(self, request): return Response([]) def list(self, request): return Response([]) def create(self,request): print({**request.POST,**request.FILES}) serializer = self.get_serializer(data={**request.data,**request.FILES}) if serializer.is_valid(): data = serializer.data ud = data['user'] user,b = User.objects.get_or_create( email=ud['email'], defaults={ 'username':ud['email'], 'first_name':ud['first_name'], 'last_name':ud['last_name'], 'gender':ud['gender'], 'type':ud['type'] } ) if not b: raise serializers.ValidationError({ 'detail':["Email Already Exist"] }) c = ContentType.objects.get_for_model(user) Phone.objects.get_or_create(content_type=c, object_id=user.id, number=data['phone_detail']['number'], type=data['phone_detail']['type'] ) Address.objects.get_or_create( content_type=c,object_id=user.id, defaults={ 'province':data['address_detail']['province'], 'district':data['address_detail']['district'], 'city':data['address_detail']['city'], 'address':data['address_detail']['address'] } ) detail = data.get('user_detail', False) if detail: UserDetail.objects.get_or_create(user_id=user.id, defaults={ 'blood_group':detail.get('blood_group',''), 'nationality':detail.get('nationality',''), 'mother_tongue':detail.get('mother_tongue',''), 'religion':detail.get('religion',''), 'citizenship_no':detail.get('citizenship_no',''), } ) student,bval = Student.objects.get_or_create(user_id=user.id,registration_no=data['registration_no']) StudentAdmission.objects.get_or_create(student_id=student.id, defaults={ 'batch':data['batch'], 'course_id':data['course'], 'description':data['description'], 'image':data['image'] } ) return Response(data,status=status.HTTP_201_CREATED) β¦ -
Query an array in PyMongo
I am trying to query an array using PyMongo and I am getting all the values instead of just the one matching 'A A' import pymongo from pprint import pprint myclient = pymongo.MongoClient("mongodb://00.00.00.0:27017") mydb = myclient["dbName"] mycol = mydb["thePage"] for x in mycol.find({},{"_id": 0, "tags.tag.name": "A A"}): pprint(x) Result: [{'tag': {'name': 'A A'}}, {'tag': {'name': 'B B'}}, {'tag': {'name': 'C C'}}] Expected Result: {'name': 'A A'} I get the result I need using MongoDB: db.dbName.where("tags.tag.name").eq("A A") -
gaierror - [Errno -3] Temporary failure in name resolution
I created a Ubuntu instance with AWS EC2 where I run two docker containers: One to django (python) and another to postgreSQL. The python image contain a dependencie called xhtml2pdf to generate a PDF starting a HTML. Later of call a lot of petitions to generate a lot PDFs with this dependencie, ocurred a the following error when I want generate pdf http://XX.XXX.XXX.XXX:8000/presupuestos/1/generar_pdf/ This is my views.py where I created a function to generate PDF with xhtml2pdf urls.py To be honest, I dont know that is the issue. I search a lot in internet but I cant found the solution. Can someone help me please!? -
Django and ElasticBeanstalk: Internal server error, HTTP/2 protocol will be inactive
I'm trying to deploy my Django app in eb. I've created the environment on eb and even though all things seems good internal server error happens. I was just following the tutorial on official site. I already committed my requirements.txt and .ebextensions to my git. I set the environement variables on eb configuration. But there's an internal server error. And also eb open doesn't work. .ebextensions/django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: config/wsgi.py settings.py ALLOWED_HOSTS = ["*"] I'm still using sqlite3 on local. error.log is like this [Mon Sep 17 03:26:31.366607 2018] [mpm_prefork:notice] [pid 10621] AH00169: caught SIGTERM, shutting down [Mon Sep 17 03:26:32.520377 2018] [suexec:notice] [pid 11711] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Mon Sep 17 03:26:32.536121 2018] [so:warn] [pid 11711] AH01574: module wsgi_module is already loaded, skipping [Mon Sep 17 03:26:32.538258 2018] [http2:warn] [pid 11711] AH10034: The mpm module (prefork.c) is not supported by mod_http2. The mpm determines how things are processed in your server. HTTP/2 has more demands in this regard and the currently selected mpm will just not do. This is an advisory warning. Your server will continue to work, but the HTTP/2 protocol will be inactive. [Mon Sep 17 03:26:32.538272 2018] [http2:warn] [pid 11711] AH02951: mod_ssl does not β¦ -
Token Authentication Not Working on Django Rest Framework
I have a Django application, which I am using DRF for my API with Session, and Token authentication. I have rest_framework, and rest_framework.authtoken in my installed apps. I have migrated my database and can create tokens for users in the Django Admin. I know all of this is working because I am accessing rest_framework.auth_token's obtain_auth_token view for returning a token when user data is submitted in a POST request, and receive one back. When I try to make a GET request to a view function in my app that has TokenAuthentication on its viewset, it keeps returning. {"detail":"Authentication credentials were not provided."} Settings File INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # My Apps 'rest_framework', 'rest_auth', 'rest_framework.authtoken', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ], } URLS from django.urls import path, include from rest_framework.routers import DefaultRouter from rest_framework.authtoken import views from api.views.some_model import MyViewSet urlpatterns = [ path('', include(router.urls)), path('rest-auth/', include('rest_auth.urls')), path('api-token-auth/', views.obtain_auth_token) ] Viewset from rest_framework.viewsets import ModelViewSet from rest_framework.authentication import SessionAuthentication, TokenAuthentication from rest_framework.permissions import IsAuthenticated from some_app.models import SomeModel from api.serializers.exams import SomeModelSerializer class ExamViewSet(ModelViewSet): permission_classes = (IsAuthenticated,) authentication_classes = (TokenAuthentication, SessionAuthentication) queryset = SomeModel.objects.all() serializer_class = SomeModelSerializer Python Script to Get Response import β¦ -
Django- passing parameters/filtering question
I'm trying to rebuild a website that was written initially in php into django. I am new to django. I am stuck on some rather basic functionality, but I can't find the answer anywhere, so I'm asking here. I am building a fantasy baseball site. I have the following 2 models: class IbcDivisions(models.Model): division = models.AutoField(primary_key=True) div_abbr = models.CharField(unique=True, max_length=255) div_name = models.CharField(max_length=255) league = models.ForeignKey('IbcLeagues', models.DO_NOTHING, db_column='league') class Meta: managed = False db_table = 'ibc_divisions' class IbcLeagues(models.Model): league = models.AutoField(primary_key=True) league_abbr = models.CharField(max_length=255) league_name = models.CharField(max_length=255) class Meta: managed = False db_table = 'ibc_leagues' These tables provide the following data (what you would expect if you follow baseball): IbcLeagues: league league_abbr league_name 1 AL American League 2 NL National League IbcLeagues: division div_abbr div_name league 1 ALE AL East 1 2 ALC AL Central 1 3 ALW AL West 1 4 NLE NL East 2 5 NLC NL Central 2 6 NLW NL West 2 I've got this code in views.py: def homepage(request): ibc_leagues = IbcLeagues.objects.all() context = { 'ibc_leagues' : ibc_leagues, } return render(request, 'ibc_leagues/index.html', context) I have a layout page feeding index.html. Index.html has this code: {% extends 'ibc_leagues/layout.html' %} {% block content %} <h2>Rosters</h2> {% for β¦ -
python loop through JSON list with nested dicts matchbook data
Below is portion of data that I get from a json request. e.g one match of many matches schedules. tennis_event = [{"TIMESTAMP": "2018-09-17 00:09:21.499540", "id": 910569159990041, "name": "M Barthel vs S Soler-Espinosa", "sport-id": 9, "start": "2018-09-17T03:00:00.000Z", "in-running-flag": false, "allow-live-betting": true, "category-id": [9, 410468520880009, 456968853470009, 476301248050010, 595375589900009, 899462538790042], "status": "open", "volume": 260.57068, "event-participants": [{"id": 910569160130041, "event-id": 910569159990041, "participant-name": "S Soler-Espinosa", "number": 2}, {"id": 910569160130042, "event-id": 910569159990041, "participant-name": "M Barthel", "number": 1}], "markets": [{"live": false, "event-id": 910569159990041, "id": 910569160480042, "name": "Moneyline", "runners": [{"withdrawn": false, "prices": [{"available-amount": 24.23531, "currency": "EUR", "odds- type": "DECIMAL", "odds": 1.42016, "decimal-odds": 1.42016, "side": "back", "exchange-type": "back-lay"}, {"available-amount": 305.45076, "currency": "EUR", "odds-type": "DECIMAL", "odds": 1.41666, "decimal- odds": 1.41666, "side": "back", "exchange-type": "back-lay"}, {"available-amount": 224.93911, "currency": "EUR", "odds-type": "DECIMAL", "odds": 1.37593, "decimal-odds": 1.37593, "side": "back", "exchange-type": "back-lay"}, {"available-amount": 32.77704, "currency": "EUR", "odds-type": "DECIMAL", "odds": 1.49505, "decimal-o odds": 1.49505, "side": "lay", "exchange-type": "back-lay"}, {"available-amount": 244.6073, "currency": "EUR", "odds-type": "DECIMAL", "odds": 1.54946, "decimal-odds": 1.54946, "side": "lay", "exchange-type": "back-lay"}, {"available-amount": 134.66863, "currency": "EUR", "odds-type": "DECIMAL", "odds": 1.59881, "decimal- odds": 1.59881, "side": "lay", "exchange-type": "back-lay"}], "event- id": 910569159990041, "id": 910569160660041, "market-id": 910569160480042, "name": "M Barthel", "status": "open", "volume": 199.80652, "event-participant-id": 910569160130042}, {"withdrawn": false, "prices": [{"available-amount": 16.22626, "currency": "EUR", "odds-type": "DECIMAL", "odds": 3.02, "decimal-odds": 3.02, β¦ -
Django contect_object_name is not producing a contect dict in view
I am back with more django questions on CBVs. This is about context_object_name. I have the following: @method_decorator(verified_email_required, name='dispatch') class Create(CreateView): model = Profile context_object_name = 'profileForm' template_name = 'Members/template_includes/profile/form.html' form_class = ProfileForm success_url = '/Members' form_title = "New Login Profile Information" def get(self, request, *args, **kwargs): return render(request, self.template_name, { 'profileTitle': self.form_title, }) I am using PyCharm and can put a breakpoint in the template_name form and see what the environment knows about. I expect to see a dict named profileForm with all the form members in it plus profileTitle. Instead I see profileTitle as a standalone member. I do not see anything named profileForm or object_list and the expected form members are not being painted in the template. I suppose that I understand that the extra content in the return render will pass a "naked" profileTitle but I did expect that the default get behaviour would pull in the form info. Have I missed the point? -
How to add all foreign key relations in Django?
I have these two models : class Country(models.Model): Name = models.CharField(max_length=100) Population = models.CharField(max_length=100) Language = models.IntegerField() Total_persons= models.IntegerField() class Person(models.Model): Country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=100) contact = models.IntegerField() In country I have USA, CANADA, MEXICO, SPAIN, FRANCE...... In Person I have more than 1000 persons. How can I make the Total_persons increase as the Total number of Persons increase in that country. -
Django choices in Admin when Enum is used
I have a model where I am using Enum for choices: class Agreement(models.Model): class Category(enum.Enum): EULA = 0 PROVIDER = 1 created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) category = models.IntegerField( choices=[(choice.name, choice.value) for choice in Category]) title = models.CharField(max_length=128) content = models.TextField() I register it using simple admin site registration: admin.site.register(Agreement) When admin site renders the object it doesn't allow me to save it? Has anyone had a similar issue? -
Django getting ForeignKey objects in APIView
Hey so I am new to Django and I am writing a REST API with the following model . class Order(models.Model): order_name = models.CharField(max_length=10,unique = True, default = "") def __str__(self): return '{0}'.format(self.order_name) . class LineItem(models.Model): order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) class Meta: unique_together= ('order','product') def __str__(self): return '{} - {}'.format(self.order.order_name,self.product.product_name) . class OrderList(APIView): def get(self,request): orderlist = Order.objects.all() serializer = OrderSerializer(orderlist,many = True) return Response(serializer.data) def post(self, request): serializer = OrderSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class OrderDetail(APIView): def get_object(self, order): try: return Order.objects.get(order_name=order_name) except Order.DoesNotExist: raise Http404 def get(self, request, order_name): snippet = Order.objects.get(order_name=order_name) snippet=snippet.lineitem_set.all() serializer = OrderSerializer(snippet) return Response(serializer.data) . So I am trying to code the OrderDetail(APIView)'s get method so that at /api/order/OrderA/ I get JSON with all the lineitems in that order. I've been struggling for a while with this now. Any suggestions? -
Table Master and details with same foreign django
I am trying to create two models in django, Reservation and DetailsReservation, i need that models has a same userReservation .Example if i create a Reservation with id: 1 and User: 4, when create a Details with Reservation 1, should copy user in userbyReserva class Reservation(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) userReservation = models.ForeignKey(User, on_delete=models.CASCADE, default=1) class DetailsReservation(models.Model): Reservation = models.ForeignKey(Reservation, blank=False, on_delete=models.CASCADE, null=True) userbyReserva = #same user that do reservate -
How to generate oracle specific queries djang
How can I get Django to produce/submit the exact query below: SELECT "MESSAGE"."MSG_NO", "MESSAGE"."MSG_TYPE", "MESSAGE"."DIRECTION", "MESSAGE"."SESSION_NO", "MESSAGE"."SEQUENCE_NO", "MESSAGE"."REF_SESSION", "MESSAGE"."REF_SEQUENCE", "MESSAGE"."ACKTIME", "MESSAGE"."ACKNAKSTATUS", "MESSAGE"."PRIORITY", "MESSAGE"."DELIVMONITOR", "MESSAGE"."OBSOLESCENCE", "MESSAGE"."DISPOSITION", "MESSAGE"."TRAILER", "MESSAGE"."BYPASSED", "MESSAGE"."RESPONSE_QUEUE", "MESSAGE"."SOURCE_QUEUE", "MESSAGE"."QUEUE", "MESSAGE"."QUEUE_PRIORITY", "MESSAGE"."DATE_CREATED", "MESSAGE"."DATE_ROUTED", "MESSAGE"."INPUT_FILE", "MESSAGE"."OUTPUT_FILE", "MESSAGE"."STATUS1", "MESSAGE"."STATUS2", "MESSAGE"."STATUS3", "MESSAGE"."USERID", "MESSAGE"."TMSTAMP" FROM "MESSAGE" WHERE ("MESSAGE"."DATE_CREATED" >= (SYSDATE-3) AND "MESSAGE"."DIRECTION" = 0 AND "MESSAGE"."STATUS1" = 0) The below code produces a query that does not work: Message.objects.using(queue_db_env).filter(STATUS1=0, DIRECTION=0, DATE_CREATED__gte=time_threshold) Below is the query produced by the code above and it does not work when I run it manually: SELECT "MESSAGE"."MSG_NO", "MESSAGE"."MSG_TYPE", "MESSAGE"."DIRECTION", "MESSAGE"."SESSION_NO", "MESSAGE"."SEQUENCE_NO", "MESSAGE"."REF_SESSION", "MESSAGE"."REF_SEQUENCE", "MESSAGE"."ACKTIME", "MESSAGE"."ACKNAKSTATUS", "MESSAGE"."PRIORITY", "MESSAGE"."DELIVMONITOR", "MESSAGE"."OBSOLESCENCE", "MESSAGE"."DISPOSITION", "MESSAGE"."TRAILER", "MESSAGE"."BYPASSED", "MESSAGE"."RESPONSE_QUEUE", "MESSAGE"."SOURCE_QUEUE", "MESSAGE"."QUEUE", "MESSAGE"."QUEUE_PRIORITY", "MESSAGE"."DATE_CREATED", "MESSAGE"."DATE_ROUTED", "MESSAGE"."INPUT_FILE", "MESSAGE"."OUTPUT_FILE", "MESSAGE"."STATUS1", "MESSAGE"."STATUS2", "MESSAGE"."STATUS3", "MESSAGE"."USERID", "MESSAGE"."TMSTAMP" FROM "MESSAGE" WHERE ("MESSAGE"."DATE_CREATED" >= 2018-09-15 12:47:43.784709 AND "MESSAGE"."DIRECTION" = 0 AND "MESSAGE"."STATUS1" = 0) This is due to "MESSAGE"."DATE_CREATED" >= 2018-09-15 12:47:43.784709 , query only works when I swap out the DATE_CREATE clause with "MESSAGE"."DATE_CREATED" >= (SYSDATE-3) My views.py has the code of: class MessageList(APIView): def get(self, request, queue_db_env, queue_name, queue_id, format=None): # # time_threshold = datetime.now() - timedelta(hours=36) now = timezone.now() time_threshold = now - datetime.timedelta(hours=36) print(time_threshold.timestamp()) str_time_threshold = time_threshold.timestamp() # messages = Message.objects.using(queue_db_env).filter(STATUS1=0, DIRECTION=0, DATE_CREATED__gte=time_threshold) print(messages.query) serializer = MessageSerializer(messages, many=True) return Response({"Queue": β¦