Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
This field is required. Error with ImageField django
I'm getting 'This field is required' error while uploading image. I don't understand why I get this error, my model is very basic, but I don't know why and where i'm getting error. Some help would be apreciate. my models is class Post(models.Model): title= models.CharField(max_length=100) img = models.ImageField(upload_to='pics') content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author= models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('User-Posts-Details', kwargs={'pk': self.pk}) 'my views is' class PostCreateViews(CreateView): model = Post fields = ['title','img','content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) and html code <div class="blog_list"> <form method="POST"> {% csrf_token %} <h2 class="blog_heading">New Post</h2> <fieldset class="form-group" id="new"> {{ form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> can anyone plz help me with this????? -
whenever i go the next class hide id=q2 in multistep form it redirects me only when i click ctrl and press next it goes to the part in new tab
this is my code applyonline.html basically after the beneficicary part is completed the husband part should be shown but when i click next after filling up the form it redirects me back to beneficiary and only when i click ctrl+next it goes to the husband details but in a new tab <body ng-app=""> {% extends "pmmvyapp/base.html" %} {% load crispy_forms_tags %} {% load static %} {% block content%} <div class="col-md-8"> <form method="post" action="/personal_detail/" enctype="multipart/form-data"> <div class="group"> <div class="hide" id="q1"> {% csrf_token %} <div class="form-group"> <div class=" mb-4"> <!--Beneficiary Details--> <h6><u>(*Mandatory Fields)Please Fill up the details below </u></h6> </div> <legend class="border-bottom mb-4" ,align="center">1.Beneficiary Details</legend> <label for="formGropuNameInput">Does Beneficiary have an Adhaar Card?*</label> <input type="radio" name="showHideExample" ng-model="showHideTest" value="true">Yes <input type="radio" name="showHideExample" ng-model="showHideTest" value="false">No <!--logic for yes--> <div ng-if="showHideTest=='true'"> <div class="form-group"> <label for="formGropuNameInput">Name of Beneficiary(as in Aadhar Card)*</label> <input name="beneficiary_adhaar_name" class="form-control" id="formGroupNameInput" placeholder="Enter name of Beneficiary as in Aadhar Card" required> </div> <div class="form-group"> <label for="formGropuNameInput">Aadhaar Number(Enclose copy of Aadhaar Card)*:</label> <input name="adhaarno" class="form-control" id="aadhar" pattern="[0-9]{4}[0-9]{4}[0-9]{4}" placeholder="Enter Aadhar Card number with proper spacing" required> </div> <input type="file" name="adhaarcopy" /> <div class="form-group"> <div class="form-check"> <input class="form-check-input is-invalid" type="checkbox" value="" id="invalidCheck3" required> <label class="form-check-label" for="invalidCheck3"> Give consent to collect adhaar card data </label> <div class="invalid-feedback"> You … -
How to close a popup when another popup is open using JavaScript?
I'm working on a Python/Django web application, and I don't have much knowledge of JavaScript yet. The answers I've googled suggest a bit of a different approach, and I can't adjust those solutions to my code due to my yet little knowledge of JS. Will be grateful for helping me out. Thanks in advance! So, I have a few popup windows, which have different IDs and they're all opened and closed with the same two JavaScript functions by passing thir IDs as a $target variable. I also want to close any opened popup window if another popup is opened by the user, so only one can be opened at the same time, and also close a popup window if the user clicks a glyphicon button (the same that opened that popup window with the first click). Here's my code: html template <script> function popup($target) { document.getElementById($target).style.display = "block"; } function closepopup($target) { document.getElementById($target).style.display = "none"; } </script> Example of where these functions are called (same template): <a class="btn btn-default" onclick="popup('add')" style="position: absolute; right: 2%; bottom: 10%; padding: 6px;"><span class="glyphicon glyphicon-pencil"></span></a> <div class="form-popup popupfont" id="add-important"> <form action="{% url 'add-general' %}" method="post" class="form-container"> {% csrf_token %} <label for="task_text">Add a task:</label> <input type="text" … -
Need to make api in djnago , provided with json file
Provided the JSON structure of a search result for one the location, you are requested to make an API that will expect three mandatory parameters : a. Latitude b. Longitude c. Type of service (Business, Couples, Solo travel, Family, Friends getaway) Based on the provided inputs the API should return the hotels present in the radius of 100 Kms of provided latitude and longitude. Attachments area { "0-4": { "HotelSearchResult": { "no_of_nights": 5, "no_of_hotels": 71, "no_of_adults": 2, "more_results": false, "CheckInDate": "23/04/2020", "CheckOutDate": "28/04/2020", "NoOfRooms": 1, "TraceId": "5l4jwkkzoke3ls3l3tw5ihsnka", "CityId": null, "PreferredCurrency": "INR", "RoomGuests": [ { "ChildAge": null, "NoOfAdults": 2, "NoOfChild": 0 } ], "ResponseStatus": 1, "HotelResults": [ { "HotelPicture": "https://www.tratoli.com/grn_mask/?path=H!0144442/2fae1d4b89a5e336f63b64c9f6803b1f.jpg", "ResultIndex": 0, "Latitude": 25.10882966, "Longitude": 55.18319964, "TripAdvisor": { "address_obj": { "street1": "Sheikh Zayed Road", "street2": "", "city": "Dubai", "state": "Emirate of Dubai", "country": "United Arab Emirates", "postalcode": "450011", "address_string": "Sheikh Zayed Road, Dubai 450011 United Arab Emirates" }, "latitude": "25.1086", "rating": "4.0", "trip_types": [ { "name": "business", "value": "477", "localized_name": "Business" }, { "name": "couples", "value": "409", "localized_name": "Couples" }, { "name": "solo", "value": "294", "localized_name": "Solo travel" }, { "name": "family", "value": "238", "localized_name": "Family" }, { "name": "friends", "value": "265", "localized_name": "Friends getaway" } ], "longitude": "55.183365", "review_rating_count": { … -
How to get list from QuerySet[]
If I have a QuerySet [Language: fifty, Language: grey, Language: shade] in my console API,How do I get [Language: fifty, Language: grey, Language: shade] .. So that the QuerySet is remove and I get a list -
Authenticate a Django/Appengine project using Firebase
I currently have google and facebook authentication for my application. I would like to add firebase-auth as the backend for my Django/appengine backend. The tutorial i followed (https://cloud.google.com/appengine/docs/standard/python/authenticating-users-firebase-appengine) only show how to use it for a python Flask backend. Does anyone know how to set up firebase in a Django backend that uses appengine? -
Many_to_many --> FieldError: Related Field got invalid lookup: contains
I have a two two models: Doctor and Patient. Doctor is defined as follows: class Doctor(models.Model): patients = ManyToManyField('patients.Patient', related_name="%(class)ss", blank=True) I want to get all the doctors that have a specific patient. I tried: doctors = Doctor.objects.filter(patients__contains=patient) it doesnt' seem to work...any idea? -
"MultipleObjectsReturned" from db on template
if there are two db entries for "Anhang" or more then i get the ERROR: "all() takes 1 positional argument but 2 were given" views.py @login_required() def anhang_view(request, id=None): contextoo = {} item = get_object_or_404(Kunden, id=id) kontaktform_form = KontaktForm(request.POST or None, instance=item) creatorform_form = CreateANform() contextoo['creatorform_form'] = creatorform_form if Kunden.objects.filter(KN=item.KN).exists(): item14 = Kunden.objects.get(KN=item.KN) editkontakto_form = InfoKontaktoForm(request.POST or None, instance=item14) contextoo['editkontakto_form'] = editkontakto_form if Anhang.objects.filter(KN=item.KN).exists(): item15 = Anhang.objects.all(Anhang.objects.filter(KN=item.KN)) ANform_form = ANform(request.POST or None, instance=item15) contextoo['ANform_form'] = ANform_form if request.method == 'POST': creatorform_form = CreateANform(request.POST) if creatorform_form.is_valid(): cre = creatorform_form.save(commit=True) cre.save() return redirect('/Verwaltung/KontaktAnlegen') else: return render(request, 'blog/anhang.html', contextoo) ERROR: all() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://127.0.0.1:8000/Verwaltung/Anhang/10 Django Version: 3.0.1 Exception Type: TypeError Exception Value: all() takes 1 positional argument but 2 were given anhang.html . . . {% if ANform_form %} <table class="table" width="100%" border="0" cellspacing="0" cellpadding="0"> <thead class="thead-light"> <tr> <td width="11%" border="0" cellspacing="0" cellpadding="0"> <b> {% csrf_token %} {{ ANform_form.instance.Thema }} </b> </td> <td width="15%" border="0" cellspacing="0" cellpadding="0">Username</td> <td width="19%" border="0" cellspacing="0" cellpadding="0">Password</td> <td width="18%" border="0" cellspacing="0" cellpadding="0">E-Mail</td> <td width="37%" border="0" cellspacing="0" cellpadding="0">Anhang</td> <td> </td> </tr> </thead> <tbody> <td></td> <td> {% csrf_token %} {{ ANform_form.instance.Username }} </td> <td> {% csrf_token %} {{ ANform_form.instance.Password … -
Django saving a form with unique constraint
I have a simple Profile model linked to Djang user model that keep alias. Alias has a unique constraint in the model. To update the alias, I created a model form, but can't figure out how to exclude the unique constraint when the user just push the submit button with no change to the alias. The form raise an error because of unique constraint. Here's the model and form definition with part of the view that handle the form: models.py class Profile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) alias = models.CharField( "Alias", max_length=50, unique=True, null=True ) forms.py class ProfileForm(ModelForm): class Meta: model = Profile fields = ['alias', ] And the views.py def membership(request): if request.method != 'POST': profile = Profile.objects.get(user=request.user) form = ProfileForm(initial={'alias': profile.alias, 'user': request.user}) elif request.POST.get('profile_update', None) == 'profile_update': form = ProfileForm(request.POST) if form.is_valid(): form.save() -
How can i use loop to create list of fields
Recently, I start project using django 3 i face the problem with model I wanna create the modelform and the field is a list: Like answer1, answer2, ..., answer10,... ''' class Quiz(models.Model): question = models.CharField(max_length=30) def __str__(self): return self.question quiz = Quiz.objects.all() class Answer(models.Model): answer1 = models.CharField(max_length=20) answer2 = models.CharField(max_length=20) answer3 = models.CharField(max_length=20) ... answer10 = models.CharField(max_length=20) ... How i use loop or something to declare this answer field Can i set my table collum name of answer1 = qiz[0].question ''' -
Postgresql is not getting data from form
I'm learning django now, and i'm facing a problem, I create a form to submite data in my database, but the problem is when i click on submit button, postgres isn't receiving data, I cant understand the problem. This is my contact form This is my database This is my html code <form action="." method='post' class="p-5 bg-white"> <h2 class="h4 text-black mb-5">Contact Form</h2> {% csrf_token %} <div class="row form-group"> <div class="col-md-6 mb-3 mb-md-0"> <label class="text-black" for="fname">First Name</label> <input type="text" id="fname" class="form-control rounded-0"> </div> <div class="col-md-6"> <label class="text-black" for="lname">Last Name</label> <input type="text" id="lname" class="form-control rounded-0"> </div> </div> <div class="row form-group"> <div class="col-md-12"> <label class="text-black" for="email">Email</label> <input type="email" id="email" class="form-control rounded-0"> </div> </div> <div class="row form-group"> <div class="col-md-12"> <label class="text-black" for="subject">Subject</label> <input type="subject" id="subject" class="form-control rounded-0"> </div> </div> <div class="row form-group"> <div class="col-md-12"> <label class="text-black" for="message">Message</label> <textarea name="message" id="message" cols="30" rows="7" class="form-control rounded-0" placeholder="Leave your message here..."></textarea> </div> </div> <div class="row form-group"> <div class="col-md-12"> <input type="submit" value="Send Message" class="btn btn-primary mr-2 mb-2"> </div> </div> </form> This is my models.py from django.db import models class Form(models.Model): fname=models.CharField(max_length=300) lname=models.CharField(max_length=300) email=models.EmailField() subject=models.CharField(max_length=300) message=models.TextField() This is my views.py from django.shortcuts import render from .models import Form def test(request): if request.method == 'POST': request.POST.get('fname') request.POST.get('lname') request.POST.get('email') request.POST.get('subject') request.POST.get('message') … -
Error: expected pk value, received list for foreignkey field
I cannot save multiple values for the Foreignkey field when adding instances to the database. I don't understand exactly what the problem is: in my code or in the format of the JSON object being passed. models.py class VendorContacts(models.Model): contact_id = models.AutoField(primary_key=True) vendor = models.OneToOneField('Vendors', on_delete=models.CASCADE) contact_name = models.CharField(max_length=45, blank=True) phone = models.CharField(max_length=45, blank=True) email = models.CharField(max_length=80, blank=True, unique=True) class Meta: db_table = 'vendor_contacts' class VendorModuleNames(models.Model): vendor = models.OneToOneField('Vendors', on_delete=models.CASCADE, primary_key=True) module = models.ForeignKey(Modules, models.DO_NOTHING) timestamp = models.DateTimeField(auto_now=True) class Meta: db_table = 'vendor_module_names' unique_together = (('vendor', 'module'),) class Vendors(models.Model): COUNTRY_CHOICES = tuple(COUNTRIES) vendorid = models.AutoField(primary_key=True) vendor_name = models.CharField(max_length=45, unique=True) country = models.CharField(max_length=45, choices=COUNTRY_CHOICES) nda = models.DateField(blank=True, null=True) user_id = models.ForeignKey('c_users.CustomUser', on_delete=models.PROTECT) timestamp = models.DateTimeField(auto_now_add=True) class Meta: db_table = 'vendors' unique_together = (('vendorid', 'timestamp'),) serializers.py class VendorsSerializer(serializers.ModelSerializer): class Meta: model = Vendors fields = ('vendor_name', 'country', 'nda', 'parent_vendor',) class VendorContactSerializer(serializers.ModelSerializer): class Meta: model = VendorContacts fields = ( 'contact_name', 'phone', 'email',) class VendorModulSerializer(serializers.ModelSerializer): class Meta: model = VendorModuleNames fields = ('module',) views.py class VendorsCreateView(APIView): """Create new vendor instances from form""" serializer_class = (VendorsSerializer) def post(self, request, *args, **kwargs): vendor_serializer = VendorsSerializer(data=request.data) vendor_contact_serializer = VendorContactSerializer(data=request.data) vendor_modules_serializer = VendorModulSerializer(data=request.data) try: vendor_serializer.is_valid(raise_exception=True) \ and vendor_contact_serializer.is_valid(raise_exception=True) \ and vendor_modules_serializer.is_valid(raise_exception=True) \ vendor = vendor_serializer.save(user_id=request.user) vendor_contact_serializer.save(vendor=vendor) vendor_modules_serializer.save(module= … -
How to Save Slug Automatic in Django?
Here is my code for saving slug automatically. But it doesn't work and I don't know why! I can't be totally wrong. Help me to get out. from django.db import models from django.urls import reverse from django.template.defaultfilters import slugify class Article(models.Model): title = models.CharField(max_length=50) body = models.TextField() slug = models.SlugField(null=False,unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): # new if not self.slug: self.slug = slugify(self.title) return super().save(*args, **kwargs) But in django Admin panel I have to save slug manually But I want to save it automatically. Help me to understand this. Thanks Good People. -
Can I add a search function on a Django template to search all templates in the app
I have 100's of pages of templates within my app. I want to add a search bar on my home page so someone can search for something and it returns the URLs to potential results (or something similar). Is this possible? Any help whatsoever is appreciated. -
Django email subject "EMAIL_SUBJECT_PREFIX" is ignored
I'm using Django + Wagtail + Allauth and I want to change the subject when a user register or forget her/his password: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_SUBJECT_PREFIX = '[Django] ' While I set EMAIL_SUBJECT_PREFIX to '[Django] ', I'm having '[example.com] ' instead. web_1 | Content-Type: text/plain; charset="utf-8" web_1 | MIME-Version: 1.0 web_1 | Content-Transfer-Encoding: 7bit web_1 | Subject: [example.com] Password Reset E-mail web_1 | From: webmaster@localhost web_1 | To: me@me.com web_1 | Date: Wed, 26 Feb 2020 15:04:41 -0000 web_1 | Message-ID: <158272948175.190.1882653498152410368@69079ce78170> Do you know why ? And if there is another way to change the prefix ? -
Django: use on_delete on certain conditions
I have this model with a Foreign Key and three values that can be null, if I want to delete the Ind model, I would only be able to do it if these values are, in fact, null, if not, I can't delete it. I've searched a bit and couldn't find anything that would help me, is it doable? class Det(models.Model): ind = models.ForeignKey(Ind, on_delete=models.PROTECT) y_1 = models.CharField(max_length=80, null=True) y_2 = models.CharField(max_length=80, null=True) y_3 = models.CharField(max_length=80, null=True) -
Pycharm HTML syntax colour coded not working
Been following a tutorial on Youtube about building an app on Django. In pictures below you can see in his IDE that the same piece of HTML code is formatted, and I think this is why I'm running into issues when running my server. Anyone know how to fix this please? The code on the tutorial: My version: Would be really grateful for any help! -
Django get random objects from database
I have a database with a million+ columns and I want to return a 100 random objects from that database. After searching the web for a solution I saw that there is a big argument about the order_by['?'] approach and it's alternatives(Even in the Django official documentation!), In addition, most of the discussions about this issue are from 2010+-. So, I'm wondering what is the best practice to generate random objects from my Djando model. I saw in the Django documentation that it might based on the database itself, so is it matter if it MySQL or PostgreSQL or something else? or if it depends on the backend itself (AWS RDS or their competitors) Here's my model: class BasicPost(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) published = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=False) body = models.TextField(max_length=999) media = models.ImageField(blank=True) def get_absolute_url(self): return reverse('basic_post', args=[str(self.pk)]) def __str__(self): return self.title Thanks! -
django-tenant and django resframework testing
I'm trying to switch to test driven development. But for that I need to understand unit test :) I got the following problem. I'm using Django rest framework and django-tenants in combination. So far so good. However to test anything you need to make a tenant. class Test1(TenantTestCase): def setUp(self): super().setUp() self.client = TenantClient(self.tenant) Once you do so your tenant is setup. But if I was to test the API the client is the TenantClient and not the APIClient. The testcase is TenantTestCase. So my question. How do you combine the two? -
Celery Task not getting assigned through redis
Using Celery/redis i tried creating a task, But on checking the celery working info with the below code celery -A intranet_project worker -l info I am unable to get the task added there. Settings.py BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE init.py from __future__ import absolute_import # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'intranet_project.settings') app = Celery('intranet_project') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) my_task.py from celery.decorators import task from celery import shared_task @shared_task def add(a,b): d = a + b return d Below is the server log [tasks] . intranet_project.celery.debug_task [2020-02-26 19:38:59,051: INFO/MainProcess] Connected to redis://localhost:6379// [2020-02-26 19:38:59,160: INFO/MainProcess] mingle: searching for neighbors [2020-02-26 19:39:00,379: INFO/MainProcess] mingle: all alone -
Requested setting INSTALLED_APPS, but settings are not configured
I am working on a project for a while and now from nowhere I am getting this error: where the following seems to be the important part django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.co The error is coming when I am trying to use main.py The content (that is important for comprehension) of main.py is: I know about: export DJANGO_SETTINGS_MODULE=mysite.settings But this is not the solution for me. This problem only came when I add: from device.serializers.gcloud_device import GcloudDeviceSerializer If I do export the django_settings_module with the path to my settings.py then my error become: ImportError: cannot import name I do not have circular import. I already created a lot of apps in my project and this is the first time I see this error Thank you -
Utilizing django blob field to upload file to a blob column in Oracle
I want to upload files (images,pdf,ms word,etc) in the Oracle database (blob) using Django binary field. I need to store file name and file extension (e.g. png,jpeg,etc) and file size. However i can't figure out how to store in the blob field the binary data of the file. P.S. I know it's not best practise to store static files in the database but i have to do this. My Model: class File(models.Model): du_id = models.AutoField(primary_key=True) du_file = models.BinaryField() du_file_name = models.CharField(max_length=1000) du_file_extension = models.CharField(max_length=100) du_file_size = models.CharField(max_length=100) forms.py: from django import forms class UploadFileForm(forms.Form): file = forms.FileField(label='Upload document') html form: <form method="post" action="{% url 'images:upload' %}" enctype="multipart/form-data">{% csrf_token %} {{form}} <input type="submit" value="Upload file"> </form> view: from django.shortcuts import render from images.models import File from images.forms import UploadFileForm from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.urls import reverse from django.utils.timezone import datetime import datetime,base64 def file_upload(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): file_name = str(form.cleaned_data['file']) file_name_split = file_name.split('.') extension = file_name_split[-1].upper() test_string = "test string" res = bytes(test_string, 'utf-8') a = File.objects.create(du_file = res,du_file_name=file_name,du_file_extension=extension, du_file_size='1023') a.save() return HttpResponse(file_name) #return HttpResponseRedirect(reverse('images:home')) else: return HttpResponse('Form is not valid!') else: return HttpResponse('Failed') -
How to optimize deep nested foreignKeys in Django queryset
TLDR; Is there a better way to handle deep nesting in this Django queryset? File.objects.filter(folder__project__workspace__organization__in=user.organizations.all()) Detailed question: Here is an example scenario: An organization consists of multiple users and a user can be part of multiple organizations. class User(models.Model): pass class Organization(models.Model): members = models.ManyToManyField( User, through='OrganizationMembership', related_name='organizations' ) class OrganizationMembership(models.Model): member = models.ForeignKey(User) organization = models.ForeignKey(Organization) The nested relationship among models are defined as follows: class Workspace(models.Model): organization = models.ForeignKey(Organization, related_name='workspaces') class Project(models.Model): workspace = models.ForeignKey(Workspace, related_name='projects') class Folder(models.Model): project = models.ForeignKey(Project, related_name='folders') class File(models.Model): folder = models.ForeignKey(Folder, related_name='files') I wanted to filter all the files the requesting user has access to across organizations. Here is my queryset, is there a way to optimize this queryset? user = self.request.user organizations = user.organizations.all() File.objects.filter(folder__project__workspace__organization__in=organizations) -
Django Form Can't Filter Foreign Key on Dropdown
I have a "CustomUser" class that I got from an all-auth tutorial (Django All-Auth Tutorial) and I have user as a foreign key in each model, which works as intended, only showing records pertaining to the current logged in user to that specific user. For example: class Education(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) EducationInstitutionName = models.CharField(verbose_name=_('Institution Name'), max_length=100, default=None) EducationLevel = models.CharField(verbose_name=_('Education Level'), choices=EDUCATIONLEVEL, max_length=100, default=None) EducationStartDate = models.DateField(verbose_name=_('Education Start Date'), default=None) EducationEndDate = models.DateField(verbose_name=_('Education End Date'), default=None) EducationCaoCode = models.CharField(choices=CAO_CODE, max_length=100, default=None) EducationDesc = models.CharField(verbose_name=_('Education Description'), max_length=250, default=None) def __str__(self): return self.EducationInstitutionName This works perfectly and I am achieving what is needed. The issue arises when I have a table comprised of Foreign Keys which is the focal point of my application which takes the constituent parts of a CV and allows you to combine them to make a CV of interchangable sections. class Cv(models.Model): user = models.ForeignKey( CustomUser, on_delete=models.CASCADE, ) CvName = models.CharField(verbose_name=_('CvName'), max_length=100, default=None) CvEducation = models.ForeignKey(Education, on_delete=models.CASCADE) CvSkills = models.ForeignKey(Skills, on_delete=models.CASCADE) CvWorkExperience = models.ForeignKey(WorkExperience, on_delete=models.CASCADE) def __str__(self): return self.CvName This gives me... enter image description here Dropdown showing all users "Education" I've tried to filter this with init parameters but this breaks the "save" function. I'm really … -
Making a Django proxy for websocket (jupyter lab)
I'm having a problem with an application I'm trying to mount, I need to have a JupyterLab and notebook iframed in the django app, but I needed to proxy it through the Django app so I can use the Django authorization and authentication to access the notebooks, I used django-revproxy to proxy all the http routes to the Jupyter endpoint, and it works pretty easy, but I can't make the kernel of the Jupyter notebook to work, b/c it works through web sockets, I tried to use Django Channels and ProtocolTypeRouter/URLRouter to proxy the websockets routes, but I'm getting this error, "failed: Error during WebSocket handshake: 'Upgrade' header is missing", now I'm not sure if my approach of proxy the JupyterLab endpoints is the best, I got to a wall and I feel trap and don't know how to solve this problem, what do you recommend to handle this? thank you.