Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ReferenceError,with server's GET function
n1 Reference Error: n1 is not defined a = request.GET['n1'] # here is problem,HTML file has 'n1',but still giving Reference Error -
Get data from database to summernote in Django form
I've implemented summernote in Django. When I add a new item and add details using the summernote, I'm able to get it saved in the database. But when I try to edit the same item I'm not able to retrieve details that I've entered in the summernote. I'm using Django forms for this. I'm able to retrieve all the data but not able to display the data into the summernote. I've tried the following way $('.summernote').summernote('code', 'test string'); But not able to set it into the summernote. I'm using Django 2.2 -
How to declare and use global variables in Django (with Eclipse)
I'm developing an application that needs a global variable. Fortunately, it is working despite Eclipse complaining about the way I used the global variable. To use as an example in this question, I created an application (which works!) that uses a global variable as a page counter. Here is the code: My __init__.py file: counter = 0 My views.py from AccessCounter import counter from django.shortcuts import render def conterf(request): global counter counter +=1 context = { 'counter' : counter, } return render(request, 'AccessCounter/index.html', context) And Eclipse is complaining that I have a "Unsed import: counter" at line "from AccessCounter import counter", but if I remove this line, the counter does not work with this error: name 'counter' is not defined I don't think that the following information is relevant, but here they are... My index.html file <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> Access counter: {{ counter }} </body> </html> and my url.py file: from django.contrib import admin from django.urls import path from AccessCounter import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.conterf, name='counter'), ] -
How to embed Wowza Player into Django Website?
I am trying to embed a live stream( on wowza streamcloud) on my django website but it is not showing anything. I am a bit confused about the process. -
Utilising Djangi annotations with F fields to serialize properties
I have the following model property: @property def is_complete(self): if datetime.datetime.now() >= datetime.datetime.combine(self.date, self.ending_time): return True return False I was wondering, how could I convert this to an annotation, such that: MyObject.objects.annotate(is_complete=?).filter(is_complete=True) Would be equiavalent and valid? -
Django function as Charfield Choices
Consider the following models with the following fields: Powers: class Power(models.Model): ... half = models.BooleanField() micro = models.BooleanField() UseP: class UseP(models.Model): ... power_policy = models.ForeignKey(Power, on_delete=models.CASCADE) def use_types(): TYPES = () TYPES += ("F", "Full Use") if power_policy.half: TYPES += ("H", "Half Use") if power_policy.micro: TYPES += ("M", "Micro Use") return TYPES use_type = models.CharField(max_length=1, choices=use_types()) The function doesn't run. As you can see, when I try without the "self" arguments, it says that power_policy is not defined. If I do it like self.power_policy, it recognizes the power policy but then when I got and call the function like use_type = models.CharField(max_length=1, choices=self.use_types()), it says that the self keyword is not defined in this line. I think the code explains it all, but in case it doesn't I want to provide choices to my user after they choose the Power, according to the power option. For which, I created a function but it doesn't really seem to work. What am I doing wrong or is it not even possible like this? Thank You for your time, -
Finding if lastname exists in database
I'm trying to write a simple IF statement on checking if a lastname in a database exists before a user hits the submit button to create a new record. Here is my code so far, I'm new to Django and Python so the help is appreciated. I made a variable called lastname, the thought process here is when the user hits submit, it checks the database first before the commit to warn them with a popup if the lastname exists to prevent duplicate records. It would actually be really cool to have it when a person exits the field for it to run the script before they finish filling out the form to save time. #views.py from .models import StudentCheck from django.shortcuts import render from django.http import HttpResponse, Http404, HttpResponseRedirect from forms.forms import NewStudentForm def NewStudentFormCheckList (request): if request.method == 'POST': form = NewStudentForm(request.POST) lastname = StudentCheck.lastname if form.is_valid(): newstudent= form.save() else: form = NewStudentForm() return render(request, 'forms/newstudentcheck_form.html', {'form': form}) -
TypeError: __init__() missing 1 required positional argument: 'app_module' [05/Nov/2019 21:53:44] "GET /admin/login/?next=/admin/ HTTP/1.1" 500 90506
I am very new with python and Django and I'm trying to customize a Django project. Instead of using the standard sqlite database upon installing Django. I customized some codes and was able to connect it to a MySql Database. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mydb', 'HOST': 'localhost', 'PORT': '3306', 'USER': 'root', 'PASSWORD': 'mypassword', } } I was able to create models and migrate data's to my database. Example: class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=2083) I am also able to run server. Now, I believe Django has a default admin panel. Upon running the program and access http://127.0.0.1:8000/admin/login/?next=/admin/ I am getting an error of: TypeError: __init__() missing 1 required positional argument: 'app_module' 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 page generated by the handler for this status code. I tried to set DEBUG = True to False in my settings.py and ALLOWED_HOSTS = ['*']. But the problem still exist. I don't know where to go from here. I hope someone can help. -
Error when migrating Django models with custom type Unsigned BigInt
I have MySQL tables that use an Unsigned BigInt(20) as their primary key. Django doesn't support this natively so I created a custom class. This is for Django 2.2 with Python 3.6 and the latest version of MySQL all running on a Ubuntu 18.04 server. from models.py from django.db import models from .util import PositiveBigIntegerField class Label(models.Model): Label_Code = PositiveBigIntegerField(primary_key=True) Company_Name = models.CharField(max_length=30) from utils.py from django.db.models.fields import PositiveIntegerField class PositiveBigIntegerField(PositiveIntegerField): empty_strings_allowed = False def get_internal_type(self): return "PositiveBigIntegerField" def db_type(self, connection): # get db vendor ex.mysql, postgresql, sqlite... db_vendor = connection.vendor if db_vendor == "mysql": return "bigint UNSIGNED" else: # if db_vendor is not mysql, we should return None return None And attempting to use ./manage.py showmigrations yields the following error Traceback (most recent call last): File "./manage.py", line 21, in <module> main() File "./manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/ubuntu/.local/lib/python3.6/site-packages/django/core/checks/model_checks.py", line 32, in check_all_models errors.extend(model.check(**kwargs)) … -
Renovate Bot update CDN URLs
I have a Django project that uses Bootstrap and Jquery through their CDNs. Is there a way I can get Renovate Bot to keep an eye on these versions in my HTML code so they don't get forgotten and fall way behind? What are best practices here? Thoughts? -
How to get the second to last most recent timestamped record to update a field using Django/Python?
I have a form that keeps track of enter/leave times. I am trying to add constraints to make the data more accurate. Currently, when someone "Enters", it creates a record, saves the time in timestamp and then redirects. If the person then tries to enter again, it creates a new record with a new timestamp. What I'm trying to add now is that, if the person has a previous entry without an exit timestamp then that record (which would be the second to last most recent entry), would be flagged by updating the time_exceptions field to 'N'. Currently, it changes all the fields to 'N', regardless of whether there's an exit or not, as shown below. class EnterExitArea(CreateView): model = EmployeeWorkAreaLog template_name = "operations/enter_exit_area.html" form_class = WarehouseForm def form_valid(self, form): emp_num = form.cleaned_data['employee_number'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if 'enter_area' in self.request.POST: form.save() EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True) & Q(time_in__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_in=datetime.now()) if EmployeeWorkAreaLog.objects.filter(Q(employee_number=emp_num)).count() > 1: EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_exceptions='N') return HttpResponseRedirect(self.request.path_info) I tried the following, but I get a expected string or bytes-like object and while it still creates a new record before crashing, it does not update the time_exceptions of … -
Django Rest Framework Request AssertionError
Into my app, i'm using Django + Rest Framework. I got the following error : .venv/lib/python3.7/site-packages/rest_framework/request.py", line 160, in init .format(request.class.module, request.class.name) AssertionError: The request argument must be an instance of django.http.HttpRequest, not appname.views.AppViewSet. Class View Class AppViewSet(ModelViewSet): . .... function def list(self, request): pass Django 2.1.4 Helps -
calling stored procedure with parameters from django
I have a stored procedure in mssql spGetRowRackInfo, i am calling the procedure in my django application(using pyodbc) URL pattern: urlpatterns = [ path('ReportRacks/', views.ReportRacks, name="ReportRacks"), ] Code: id = request.GET["ID"] Type = request.GET["Type"] cursor = connection.cursor() cursor.execute("{call dbo.spGetRowRackInfo(?,?)}", [id,Type]) getting an error: ERR sql = sql % tuple('?' * len(params)) ERR TypeError: not all arguments converted during string formatting How do i resolve it? -
Errors: "Class ... has no 'objects' member" & "Instance 'Generator' has no ... member"
I'm currently using Python 3.7.4 & Django 2.2.5, but i'm facing the following problems, and i don't have any clue: Class 'Topic' has no 'objects' member pylint(no-member) Class 'Webpage' has no 'objects' member pylint(no-member) Class 'AccessRecord' has no 'objects' member pylint(no-member) And also... Instance of 'Generator' has no 'url' member pylint(no-member) Instance of 'Generator' has no 'date' member pylint(no-member) Instance of 'Generator' has no 'company' member pylint(no-member) File: first_project/populate_first_app.py (some part of it) import random from first_app.models import AccessRecord,Topic,Webpage from faker import Faker fakegen = Faker() topics = ['Search','Marketplace','Social','News','Games'] def add_topic(): t = Topic.objects.get_or_create(top_name = random.choice(topics))[0] t.save() return t def populate(N = 5): for entry in range(N): # Get the topic for the entry top = add_topic() # Create the fake data for an entry fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() # Create the new webpage entry webpg = Webpage.objects.get_or_create(topic = top, url = fake_url, name = fake_name)[0] # Create a fake access record for that webpage acc_rec = AccessRecord.objects.get_or_create(name = webpg, date = fake_date)[0] And the code I wrote in File: first_app/models.py from django.db import models # Create your models here. class Topic(models.Model): top_name = models.CharField(max_length = 264, unique = True) def __str__(self): return self.top_name class … -
Can you modify a a widget text field to filter the available options furter?
I created a form with a field in my models called employee_number, which is tied to a separate model, called Salesman, which holds all the data with all the employee names, numbers, dept, etc. Currently it works by only allowing submission of the form if the employee number entered is in Salesman. What I'm trying to do is also filter it further, so that only employees that are part of team "MM" and "OM" and whose employee_status is "A" are the only ones able to submit the form. I saw a suggestion for someone with a similar problem where they said to add more constraints in the “attrs”, but I am not sure if it would work in this case too, as I am not too familiar with Python. forms.py class WarehouseForm(AppsModelForm): class Meta: model = EmployeeWorkAreaLog widgets = { 'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}), } fields = ('employee_number', 'work_area', 'station_number') models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_name = models.CharField(max_length=25) employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False) station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True) def __str__(self): return self.employee_number alldata/models.py class Salesman(models.Model): id = models.IntegerField(db_column='number', primary_key=True) team = models.CharField(max_length=2) employee_status = models.CharField(max_length=1, blank=True) -
Ingress Nginx won't load resources of a Django Application
so I have a django application running in K8 but my resource, like .css, won't get loaded. I always receive a 404 on them. I use Ingress-Nginx to route incoming traffic. The ingress config looks like this: apiVersion: networking.k8s.io/v1beta1 kind: Ingress metadata: name: ingress-aboi annotations: kubernetes.io/ingress.class: nginx ingress.kubernetes.io/rewrite-target: / spec: tls: - secretName: tls-cert rules: #- host: dev.<ip>.xip.io - http: paths: - path: / backend: serviceName: django-service servicePort: 8000 For the index.html I tried with leading slashes and without. Because I found this information in this stackoverflow thread here. Kubernetes Ingress Nginx loading resources 404 Sadly, it doesn't solve my problem. Index.html <html lang="en"> <head> <title>Log in | Django site admin</title> <link rel="stylesheet" type="text/css" href="static/admin/css/base.css"> <link rel="stylesheet" type="text/css" href="static/admin/css/login.css"> <link rel="stylesheet" type="text/css" href="static/admin/css/responsive.css"> </head> <body> </body> </html> Before I was using a nginx with this config, but I don't want to use another pod if I can handle the traffic with a ingress-nginx component alone. nginx.conf server { listen 443 ssl; location /media { alias /website/media; } location /static { alias /website/static; } location / { uwsgi_pass django; include /etc/nginx/uwsgi_params; uwsgi_read_timeout 300; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $http_host; proxy_redirect off; } So to sum it up. I … -
django NodeNotFoundError Migration employee.0001_initial dependencies on ('auth', '0013_auto_20191031_1253')
i am getting error while migrating in deployment like django.db.migrations.exceptions.NodeNotFoundError: Migration employee.0001_initial dependencies reference nonexistent parent node ('auth', '0013_auto_20191031_1253') but my migration file working fine in local pc with mysql db like Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying auth.0012_auto_20190907_1107... OK Applying auth.0013_auto_20191031_1253... OK Applying employee.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying authtoken.0001_initial... OK Applying authtoken.0002_auto_20160226_1747... OK Applying sessions.0001_initial... OK but in linux server i am getting error and i am using custom User model from AbstractUser called User in the same models.py file and give to one to one link employee model like class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) and this is migration file import datetime from django.conf import settings import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0013_auto_20191031_1253'), ] operations = [ migrations.CreateModel( name='User', -
Why is the Amadeus traditional flight search (flight offers) API missing scheduled flights? e.g. EasyJet, Wizz Air, TUI?
I am using the test environment and checking on the results I get. On certain itineraries I get all scheduled flights. However, I can't seem to be able to output any EasyJet, Wizz Air, TUI flights. Those are only the ones I have noticed, I presume there's more missing. I double check my results against skyscanner.com. Therefore, if an itinerary only has an EasyJet scheduled flight, then I get no results. Here's an example; import requests from amadeus import Client, ResponseError amadeus = Client( client_id = 'xxxxx', client_secret = 'xxxxx', ) flight_list = [] try: response = amadeus.shopping.flight_offers.get( origin = 'LTN', destination = 'ATH', departureDate = '2020-02-13', adults = 1, nonStop = 'true', currency = 'GBP', ) for resp in response.data: for offer in resp['offerItems']: flt_data = { 'From' : offer['services'][0]['segments'][0]['flightSegment']['departure']['iataCode'], 'To' : offer['services'][0]['segments'][0]['flightSegment']['arrival']['iataCode'], 'Departure Date' : offer['services'][0]['segments'][0]['flightSegment']['departure']['at'][0:10], 'Departure Time' : offer['services'][0]['segments'][0]['flightSegment']['departure']['at'][11:19], 'Arrival Date' : offer['services'][0]['segments'][0]['flightSegment']['arrival']['at'][0:10], 'Arrival Time' : offer['services'][0]['segments'][0]['flightSegment']['arrival']['at'][11:19], 'Price' : offer['price']['total'][0:], 'Terminal' : offer['services'][0]['segments'][0]['flightSegment']['departure']['terminal'], 'Airline' : offer['services'][0]['segments'][0]['flightSegment']['carrierCode'], 'Flight No.' : str(offer['services'][0]['segments'][0]['flightSegment']['carrierCode']) + ' ' + str(offer['services'][0]['segments'][0]['flightSegment']['number']) } flight_list.append(flt_data) print(flight_list) except ResponseError as error: print(error) With the following output; [origin/destination/date(s) combination] No fare found for requested itinerary I can confirm that the script runs fine when none of the … -
How to make speficic validation of a django form
I have a form based on a model Randomization I want to add specific validation on a field I try to add a 'else' just after the if form.is_valid() because I understand that I must manage the case when the form is not valid but how? views.py: @login_required def randomisation_edit(request): if request.method == "POST": form = RandomisationForm(request.POST or None) if form.is_valid(): randomisation = form.save() # print('Patient code :',randomisation.ran_num) return redirect('randomization:confirmation', pk = randomisation.pk) else: #TODO else: form = RandomisationForm(initial = {'ran_num': request.GET['patient']}) preincluded = Preinclusion.objects.get(pat_num = request.GET['patient']) return render(request, 'randomization/randomisation_edit.html', {'form': form, 'preincluded': preincluded}) forms.py class RandomisationForm(forms.ModelForm): ... class Meta: model = Randomisation # Tous les champs sauf les champs de log et les champs TB treatment et Drug batch number fields = ('ran_num','ran_dat','ran_inv','ran_pro','ran_pro_per','ran_crf_inc','ran_tbc','ran_crf_eli','ran_cri','ran_sta','ran_vih',) def clean_ran_crf_inc(self): data = self.cleaned_data['ran_crf_inc'] if int(data) == 0: raise forms.ValidationError("Ce critère est obligatoire pour la randomisation") return data I have a error 'local variable referenced before assignment' because of my views: when a validation error raise, the context 'preincluded' is not yet defined whereas I try to render it -
Django Whitenoise with compressed staticfiles
I'm not able to get my django project to run with whitenoise and compressed staticfiles (including libsass). In links below, I read that it's only possible by offline compression of needed staticfiles. But when I started up the docker container, running compress command docker-compose -f production.yml run --rm django python manage.py compress gives me error: ValueError: Missing staticfiles manifest entry for 'sass/app.scss' While trying to request the site gives me following error (as expected?): compressor.exceptions.OfflineGenerationError: You have offline compression enabled but key "..." is missing from offline manifest. You may need to run "python manage.py compress" Settings are as follows (build with cookiecutter-django, see link for complete code base below): STATIC_ROOT = str(ROOT_DIR("staticfiles")) STATIC_URL = "/static/" STATICFILES_DIRS = [str(APPS_DIR.path("static"))] STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" STATICFILES_FINDERS += ["compressor.finders.CompressorFinder"] COMPRESS_PRECOMPILERS = [("text/x-scss", "django_libsass.SassCompiler")] COMPRESS_CACHEABLE_PRECOMPILERS = (("text/x-scss", "django_libsass.SassCompiler"),) COMPRESS_ENABLED = env.bool("COMPRESS_ENABLED", default=True) COMPRESS_STORAGE = "compressor.storage.GzipCompressorFileStorage" COMPRESS_ROOT = STATIC_ROOT COMPRESS_URL = STATIC_URL COMPRESS_OFFLINE = True So after searching the internet for 1 day; I'm stuck... Thx for any help or suggestion! Code base: https://github.com/rl-institut/E_Metrobus/tree/compress which is build with cookiecutter-django-foundation including the following changes to config/setttings/production.py: COMPRESS_STORAGE = "compressor.storage.GzipCompressorFileStorage" # Instead of pre-set "storages.backends.s3boto3.S3Boto3Storage" COMPRESS_ROOT = STATIC_ROOT # Just in case … -
Error from rest_framework.exceptions import ApiException ImportError: cannot import name 'ApiException' running python manage.py
''' I am not able to import from rest_framework.exceptions import ApiException ''' ''' This is my Exception.py: ''' class APIException(Exception): status_code = status.HTTP_500_INTERNAL_SERVER_ERROR default_detail = _('A server error occurred.') default_code = 'error' def __init__(self, detail=None, code=None): if detail is None: detail = self.default_detail if code is None: code = self.default_code self.detail = _get_error_details(detail, code) def __str__(self): return self.detail def get_codes(self): return _get_codes(self.detail) def get_full_details(self): return _get_full_details(self.detail) error while running : python manage.py makemigrations networscanners Traceback (most recent call last): File "manage.py", line 25, in <module> execute_from_command_line(sys.argv) File "D:\Python36-32\lib\site-packages\django\core\management\__init__.py", li ne 381, in execute_from_command_line utility.execute() File "D:\Python36-32\lib\site-packages\django\core\management\__init__.py", li ne 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Python36-32\lib\site-packages\django\core\management\base.py", line 3 23, in run_from_argv self.execute(*args, **cmd_options) File "D:\Python36-32\lib\site-packages\django\core\management\base.py", line 3 61, in execute self.check() File "D:\Python36-32\lib\site-packages\django\core\management\base.py", line 3 90, in check include_deployment_checks=include_deployment_checks, File "D:\Python36-32\lib\site-packages\django\core\management\base.py", line 3 77, in _run_checks return checks.run_checks(**kwargs) File "D:\Python36-32\lib\site-packages\django\core\checks\registry.py", line 7 2, in run_checks new_errors = check(app_configs=app_configs) File "D:\Python36-32\lib\site-packages\django\core\checks\urls.py", line 13, i n check_url_config return check_resolver(resolver) File "D:\Python36-32\lib\site-packages\django\core\checks\urls.py", line 23, i n check_resolver return check_method() File "D:\Python36-32\lib\site-packages\django\urls\resolvers.py", line 400, in check for pattern in self.url_patterns: File "D:\Python36-32\lib\site-packages\django\utils\functional.py", line 80, i n __get__ res = instance.__dict__[self.name] = self.func(instance) File "D:\Python36-32\lib\site-packages\django\urls\resolvers.py", line 585, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "D:\Python36-32\lib\site-packages\django\utils\functional.py", line … -
how to send json and images as django response?
currently, I send JSON data using Django rest API, now I have to add images to this data (60 images per request along with the other data) I thought about using sendfile to achieve that but I'm not quite sure that this is a possibility at all. I looked for other options but found nothing. @api_view(['GET']) def get_data(request): collage_list = [] try: for i in range(30): collage_list.append({"focal_brand":{"collage_id": 7,"brand_name":"name"}) except Exception as e: print(e) return JsonResponseNotFound() return JsonResponse(status=200, data=dict(respone=collage_list) can I send both (the JSON data and the files) together? what is the best way to do that? thanks -
Validate body of a POST request in django
I have a view in django that sign's up a client and I have a model for the client and a form that looks like this: from django.forms import ModelForm from api.models.client import Client class SignUpForm(ModelForm): class Meta: model = Client fields = ['first_name', 'last_name'] In my view I would like to validate the data in the request but my problem is that the paramters in the request are camelCase and not snake_case so when I try to validate the data it doesn't work. def sign_up(request): body = json.loads(request.body) form = SignUpForm(body) print(form.is_valid()) return HttpResponse('this is a test response') Is there a clean way of making this work? Also is this the correct way to do what I'm trying to do? -
How to add conditional fields programatically to a wagtail page type?
I’m trying to add a conditional field to a wagtail page type model, the conditional fields may look like as shown in the below image. There are two fields, Question and Answer. The Answer field values should be displayed with respect to the selection of the Question field If we select Toyota from Question then Camry and Land Cruiser should be displayed in the Answer drop down, if we select Honda then Civic and Accord should be displayed in the Answer. In blocks.py I have two classes which are responsible for Questions and Answers fields respectively class ConditionsQuestionBlock(blocks.ChooserBlock): widget = Select class Meta: icon = "question" @cached_property def target_model(self): return Question @cached_property def field(self): return forms.ModelChoiceField( queryset=Question.objects.all(), widget=self.widget, required=self._required, #validators=self._validators, help_text=self._help_text, ) def value_for_form(self, value): if isinstance(value, User): return value.pk else: print("selected q:",value) selectedqval=value print("selected qvalue:",selectedqval) return value class ConditionsAnswerBlock(blocks.ChooserBlock): widget = Select class Meta: icon = "question" @cached_property def target_model(self): return Choice @cached_property def field(self): choice=Choice.objects.all() return forms.ModelChoiceField( queryset=choice, widget=self.widget, required=self._required, ) def value_for_form(self, value): if isinstance(value, User): return value.pk else: return value Now irrespective of the Question selection I'm getting all the Answer options -
How to return custom JSON output in Django REST Framework
I am trying to return custom json with the following structure [ { 'yesterday': [{'teams': "team a -team b", 'start_time': "0: 11", 'pick': "X2", 'score': "1:4", 'odds': 1.25, 'won_or_lost': "won", 'date': "2019-01-8"}], { 'today': [{'teams': "team a -team b", 'start_time': "0: 11", 'pick': "X2", 'score': "1:4", 'odds': 1.25, 'won_or_lost': "won", 'date': "2019-01-8"}] { 'tomorrow': [{'teams': "team a -team b", 'start_time': "0: 11", 'pick': "X2", 'score': "1:4", 'odds': 1.25, 'won_or_lost': "won", 'date': "2019-01-8"}] ] The following is my code: serializer.py class GamesSerializer(serializers.Serializer): class Meta: model = AllGames fields = ('teams', 'start_time', 'pick', 'score', 'odds', 'won_or_lost', 'date') class GamesViewSet(viewsets.ModelViewSet): today_date = date_picker yesterday = AllGames.objects.filter( date=today_date(-1)).order_by('start_time', 'teams') today = AllGames.objects.filter( date=today_date(0)).order_by('start_time', 'teams') tomorrow = AllGames.objects.filter( date=today_date(1)).order_by('start_time', 'teams') queryset = [yesterday, today, tomorrow] serializer_class = GamesSerializer Current Output [ {}, {}, {} ] How can I modify my GamesSerializer to return the custom output as shown above.