Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django pre_save signal has to be saved twice from admin to take affect
Got Django 1.11 app. Everything is working fine, except a strange issue with a pre_save signal. In my model, I have two many to many fields that I'm using to calculate total cost in model in question (bandwidth and license). I created a pre_save signal to accomplish this, and it works, but from the admin I am having to click the "Save" options twice for the Sku cost to update correctly. Code snippet below. Thanks for looking. Note: I tried just doing this as a save override and the results are the same, so not sure if it is just an issue with Django admin or something I'm doing. class Sku(models.Model): name = models.CharField(max_length=50) bandwidth = models.ManyToManyField(Bandwidth, blank=True, null=True) license = models.ManyToManyField(License, blank=True, null=True) customer = models.ForeignKey(Customer, null=True, blank=True, related_name='sku') cost = models.DecimalField(max_digits=25, decimal_places=2, default=0.00) def list_bandwidth(self): return ', '.join([ b.vendor for b in self.bandwidth.all()[:3]]) def list_license(self): return ', '.join([ b.name for b in self.license.all()[:3]]) def __unicode__(self): return self.name def sku_receiver_function(sender, instance, *args, **kwargs): if instance.id: bandwidth_cost = 0 license_cost = 0 if instance.bandwidth: for b in instance.bandwidth.all(): bandwidth_cost = float(b.cost) + bandwidth_cost if instance.license: for l in instance.license.all(): license_cost = float(l.cost) + license_cost instance.cost = bandwidth_cost + license_cost pre_save.connect(sku_receiver_function, … -
Form Validation Error?
I'm trying to run and validate a form but having some problem. Instead of displaying the form it displays the HttpResponse I put to display when form is not valid. Here is my Model: class Preference(models.Model): CLASS_CHOICES = [('1', '1'), ('2', '2'), ('3', '3')] BOARD_CHOICES = [('C', 'CBSE'), ('I', 'ICSE'), ('S', 'State Board')] SLOT_CHOICES = [('M', 'Morning'), ('A', 'AfterNoon'), ('E', 'Evening')] SUBJECT_CHOICES = [('H', 'HINDI'), ('M', 'MATH'), ('E', 'ENGLISH')] LOCATION_CHOICES = [('M', 'My Home'), ('T', 'I am willing to travel')] GENDER_CHOICES = [('M', 'Male'), ('F', 'Female'), ('B', 'Both are Fine')] Class = models.CharField(max_length=2, choices=CLASS_CHOICES, default='1', blank=False) Board = models.CharField(max_length=2, choices=BOARD_CHOICES, default='C', blank=False) Subject = models.CharField(max_length=2, choices=SUBJECT_CHOICES, default='M', blank=False) Frequency = models.IntegerField(default=7) Slot = models.CharField(max_length=2, choices=SLOT_CHOICES, default='E', blank=False) Location = models.CharField(max_length=2, choices=LOCATION_CHOICES, default='M', blank=False) Gender = models.CharField(max_length=2, choices=GENDER_CHOICES, default='M', blank=False) Address = models.CharField(max_length=250, blank=True) Travel = models.IntegerField(default=5) Name = models.CharField(max_length=50, blank=True) Contact = models.IntegerField(default=100) Here is my form: class PreferenceForm(forms.ModelForm): class Meta: model = Preference fields = ['Class', 'Board', 'Subject', 'Frequency', 'Slot', 'Location', 'Gender', 'Address', 'Travel', 'Name', 'Contact'] widgets = { 'Board': forms.RadioSelect(), 'Subject': forms.CheckboxSelectMultiple(), 'Slot': forms.CheckboxSelectMultiple(), 'Location': forms.CheckboxSelectMultiple(), 'Gender': forms.RadioSelect() } And here is my view: def pref2(request): form = PreferenceForm(request.POST or None) if form.is_valid(): prefer = form.save(commit=False) prefer.save() return … -
net::ERR_INSECURE_RESPONSE in django ckeditor
When a want embed something in ckeditor i get net::ERR_INSECURE_RESPONSE in console GET https://ckeditor.iframe.ly/api/oembed?url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D9-fUQE1S7RI&callback=CKEDITOR._.jsonpCallbacks[95] net::ERR_INSECURE_RESPONSE I have SSH certificats both my domains. One main where is page and second for static files where ckeditor is. Also i create .htaccess with this code for tests. Header Set Access-Control-Allow-Origin "*" In my main page with certificat is ok. But mayby probles is with my static domain where Main Origin show This page is secure (valid HTTPS). But i have also Non-Secute Origins for chrome-extension://afgbccjghcnbcdjgogpckamibfkceahd and chrome-extension://feagifldllndbfnhojikhoafnbmheoha I dont know what it means. In localhost server everything work. If someone could help me, would be nice. -
XML2PDF Throwing Exception while URL starts with /
I got a Django HTML template with some harcoded CSS parts. @font-face { font-family:"Arial"; src: url(/static/fonts/Arial.ttf); } @font-face { font-family:"Arial_Black"; src: url(/static/fonts/Arial_Black.ttf); } When I wrote the URL's in CSS prepended with '/' xml2pdf throwing this error below: Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'startswith' at line /home/www/env/lib/python2.7/site-packages/xhtml2pdf-0.1b3-py2.7.egg/xhtml2pdf/util.py in init line: 621. if self.mimetype.startswith('text'): ... If I remove the '/' then xml2pdf begin to work but template unable to load font files. How can I make this work? -
What is the best way to pass a JSON array multiple times using Angular?
Super confused about this one. I have a website that asks the user to enter the courses they took in highschool, and based on that it retrieves a list of eligible careers from the database as JSON data. Later, the user selects their personality type, and that list of careers is supposed to be filtered further more in the backend to get the new eligible careers. Retrieving list of careers the first time based on courses: if(form.$valid) { $http({ method : 'POST', url : 'https://some-django-url/get-careers-first-round/', data : $.param($scope.formData), // pass in courses headers : { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data){ $scope.careers = $scope.$eval( careers ); }); } Sending list of careers again to the backend (Django) to do extra filtering. I am stuck here. I attempted to do the following: $http({ method : 'POST', url : 'https://some-django-url/ajax/get-careers-second-round/', data : $.param($scope.careers), // ??? headers : { 'Content-Type': 'application/x-www-form-urlencoded' } }) .success(function(data){ $scope.careers = $scope.$eval( data.careers ); }); But this is not sending the careers list properly. What's wrong with my code? And is that the recommended way to pass a previously retrieved array back to the backend?? (considering I am using Django as a backend framework) ? Thanks a bunch in … -
Internal server error apache2 django deployment
I am trying to deploy a django project using apache2 and mod-wsgi-py3. However I face Internal server error 500. Here is Virtual host: <VirtualHost *:80> ServerName tres1.chuv.ch ServerAdmin n_savic@...com <Directory /home/admin/TrexmoWeb/TrexmoWeb> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess trexmo python-path=/home/admin/TrexmoWeb WSGIProcessGroup trexmo WSGIScriptAlias / /home/admin/TrexmoWeb/TrexmoWeb/wsgi.py </VirtualHost> Here is my /etc/hosts 127.0.0.1 localhost 127.0.1.1 tres1 Anybody can help? -
Testing UserPassesTestMixin with django test client
I've protected a django class-based view with the UserPassesTestMixin. Its test_func takes a parameter called division and checks whether the current user is the head of that division. The view works perfectly in the site but I've been unable to write a successful test. It seems that between the client.get and the test_func, the user is disappearing. I've tried this with RequestFactory and Client. I've tried forcing login. Made sure the correct middleware is in place. The tests for the mixin didn't help me see the issue. ( https://github.com/django/django/blob/29f607927fe82e2c8baab171dfa8baf710cd9b83/tests/auth_tests/test_mixins.py ) Now I'm stuck with no way to test various roles against the views protected by UserPassesTestMixin. I'd appreciate any insight showing me what I'm missing about permissions testing in Django. def test_permissions_to_access_division_summary_view(self): """ This test ensures that only department chairs and the division director for the specific division detail can see the division summary. """ url = "/division1" client = Client() client.login(username='div1chair', password='basicpassword') # ipdb here confirms that div1chair is logged in response = client.get(url,follow=True) self.assertEqual(response.status_code, 200) # AssertionError: 404 != 200 Here is the view I'm testing. class DivisionDirectorView(UserPassesTestMixin, View): def dispatch(self, request, *args, **kwargs): user_test_result = self.get_test_func()(kwargs['division']) if not user_test_result: return self.handle_no_permission() return super(UserPassesTestMixin, self).dispatch(request, *args, **kwargs) def … -
How to switch Python versions in Terminal?
My Mac came with Python 2.7 installed by default, but I'd like to use Python 3.6.1 instead. How can I change the Python version used in Terminal (on Mac OS)? Please explain clearly and offer no third party version manager suggestions. -
Django error showing none type when it isn't none
I am using a library called PostCoder() in order to work out the distance between two UK postcodes. I am just getting started with this trying to test it out, unfortunately I can't get any further than the initial stage before I get the following error: 'NoneType' object has no attribute 'getitem' Here is the code in my view: origin_postcode = "W1 5PD" dest_postcode = "LS3 2GG" origin = str(pc.get('%s' % origin_postcode)['geo']['lat'])+','+str(pc.get('%s' % origin_postcode)['geo']['lng']) dest = str(pc.get('%s' % dest_postcode)['geo']['lat'])+','+str(pc.get('%s' % dest_postcode)['geo']['lng']) I don't understand how it can call this a NoneType when it has a hard coded value. Can anyone suggest what the problem might be here? -
Django-Fluent-Comments - NoReverseMatch at /rohit/post/new/
i tried every thing but i donot know how to remove this error. need help guys. i am using django-fluent-comments for comments and when i put this line {% render_comment_form for object %} to get form for comments. i got this error: NoReverseMatch at /rohit/post/new/ Reverse for 'comments-post-comment' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['(?P\w+)/post/(?P[\w-]+)/comments/post/$'] Environment: Request Method: GET Request URL: http://127.0.0.1:8000/rohit/post/new/ Django Version: 1.10.2 Python Version: 3.4.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'pagination', 'postman', 'pinax.notifications', 'fluent_comments', 'crispy_forms', 'django_comments', 'mailer', 'student', 'teacher', 'classroom', 'bootstrapform', 'posts', 'background'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'pagination.middleware.PaginationMiddleware'] Template error: In template C:\Users\rohit\Desktop\GBPEC\portal\lib\site-packages\fluent_comments\templates\comments\form.html, error at line 7 Reverse for 'comments-post-comment' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['(?P<username>\\w+)/post/(?P<slug>[\\w-]+)/comments/post/$'] 1 : {% load comments i18n crispy_forms_tags fluent_comments_tags %} 2 : 3 : {% if not form.target_object|comments_are_open %} 4 : <p>{% trans "Comments are closed." %}</p> 5 : {% else %} 6 : {% if not form.helper or not form.helper.form_tag %} 7 : <form id="comment-form-{{ form.target_object.pk }}" data-object-id="{{ form.target_object.pk }}" action=" {% comment_form_target %} " method="post" class="{% block form_class %}{{ form.helper.form_class|default:'js-comments-form comments-form form-horizontal' }}{% endblock %}" 8 : … -
show django errors when using ajax
I want to use ajax in my invitation form. It is a simple form which is about posting email. I did the invitation form with the ajax but i could not show django specific error. For example, if i try to post the same email address, it should throw an error saying this email already exist and also if i provide the email as abcd@gmail my ajax code says success. How could i validate for such condition when using ajax? $('.invitation-form').on('submit', function(event){ event.preventDefault(); // preventing from the brwoser default behavior for form submission console.log('event', event.target); requestInvitation(); }) function requestInvitation(){ console.log('request'); console.log($('.requested_email').val()); $.ajax({ url: '/invitations/request/', type: 'POST', data: {email: $('.requested_email').val(), csrfmiddlewaretoken: '{{ csrf_token }}'}, success: function(data) { $('.requested_email').text(''); $('.display').html("<div class='ui floating message'>Success</div>") console.log('data', data); }, error: function(xhr,errmsg,err){ $('.display').html("<div class='ui floating message'>Oops! We have encountered an error: "+errmsg+"</div>"); // want to show django specific error } }) } @csrf_exempt def requestInvitation(request): form = InviteForm(request.POST or None) response_data = {} if form.is_valid(): join = form.save(commit=False) email = form.cleaned_data.get('email') already_join, created = Invitation.objects.get_or_create(email=email) if created: already_join.invite_code = get_invite_code() already_join.save() response_data['result'] = "Thank you for your interest" response_data['email'] = email send_request_received_email.delay(email,already_join.email_tracker) return HttpResponse(json.dumps(response_data),content_type="application/json") # return HttpResponseRedirect('/') context = {"form": form} return render(request, 'invitation/invitation.html', context) -
How to test the django profile pattern?
I don't get how to write a test for the extended user model in django. Given the model for the profile pattern: from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) department = models.CharField(max_length=100) I tried the following tests.py: from django.test import TestCase from profiles.models import Profile class ProfileTestCase(TestCase): def setUp(self): Profile.objects.create(first_name='Robert', last_name='Mayer', email='rob@mayer.local', password='123456', department='bla') def test_profile_and_user_attributes(self): # exists for being a test stub pass This will fail with: TypeError: 'password' is an invalid keyword argument for this function or when commenting out password: TypeError: 'first_name' is an invalid keyword argument for this function I know I could create my own User class based upon AbstractUser, where the tests above most probably would work out of the box. But given the OneToOneFiled solution: how to test that ? -
Server-side local file upload in Django
I am building a web-page that performs a separate python calculation which returns a results file. I want to upload this results file into a Django model automatically so that I can save it in the database, create a url for it, etc. I have created a model: class Results_file(models.Model): results = models.FileField(upload_to="uploads/%Y/%m/%d") and then in my view I want to process it as follows: def results(request): r = Results_file(results = "/path_to_local_file.txt") r.save() # ... return reverse('results_file',kwargs={'pk': r.id}) class ResultsDetailView(DetailView): model = Results_file template_name = 'my_app/results_page.html' context_object_name = 'results' All I get when i do this is "/path_to_local_file.txt" Is there a way to do this all in the back-end so the user doesn't have to submit a form, go into request.FILES, etc. -
django download file using direct link in production
Recently I found the way to download a file using a direct link (like this: Django direct link to file). So I used it. Later I tried to deploy my project in the Internet (here). Naturally I changed the DEBUG option to False value in the project settings. Then I found that the files from MEDIA_ROOT can not be downloaded. I read the docs django.conf.urls.static. Well, now I know the static works just in debug mode. But, is there a way to do the same without debug mode? -
Django: upload image can't find uploaded image
I have already tried searching stackoverflow, but couldn't find anything. My problem is that I cannot seem to find the folder where the pictures I upload is supposed to be. Seems like everything else works? Here you can see my code: Settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Views.py @login_required(login_url="/login/") def model_form_upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES,instance=request.user) if form.is_valid(): form.save() print("Form is valid") return redirect('/questions/profile') else: form = DocumentForm(instance=request.user) return render(request, 'questions/model_form_upload.html', { 'form': form }) Urls.py url(r'^upload/$', views.model_form_upload, name='upload') Models.py import os def get_image_path(instance, filename): return os.path.join('users/', str(instance.id), filename) class Document(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) profile_image = models.FileField(upload_to=get_image_path, blank=True, null=True) Forms.py from questions.models import Document class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('profile_image',) model_form_upload.html {% extends 'questions/base.html' %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> <p><a href="{% url 'questions:profile' %}">Return to profile</a></p> {% endblock %} -
Back button on Django
I am trying to use HTTP_REFERER to create a link to the previous page. However, let's say I have a 'page1' that calls the 'page2' get method. It will show a form at the 'page2' where I can do a post request. When I post on the 'page2', the HTTP_REFERER is referencing the same page (page2), therefore I can't to back to the 'page1'. Is there anything I can do to go back to the 'page1'? -
show same form in multiple template
I have a form which needs to be shown in two different template. One is the main page i.e on the invitation page to show just the invitation form and another in the homepage. When a form is filled from the homepage, if there is error, the error should be shown from the main page of that form i.e invitation template. I could show the form in invitation template and error display is working perfectly either but if i fill the form from the homepage, i always get 'this field is required' error even if i pass the right value. Here is my code def requestInvitation(request): form = InviteForm(request.POST or None) if form.is_valid(): join = form.save(commit=False) email = form.cleaned_data.get('email') already_join, created = Invitation.objects.get_or_create(email=email) if created: already_join.invite_code = get_invite_code() already_join.save() send_request_received_email.delay(email,already_join.email_tracker) messages.success(request, "Thank you for your interest.") return HttpResponseRedirect('/') context = {"form": form} return render(request, 'invitation/invitation.html', context) def home(request): form = InviteForm(request.POST or None) context = {"form": form} if not request.user.is_authenticated(): return render(request, "home.html", context) else: return render(request, "home.html", context) url(r'^request/$', requestInvitation, name='request-invitation'), -
Overriding formfield_for_choice_field throw key error
Overriding formfield_for_choice_field in inline admin throw key error even though i change nothing ? def formfield_for_choice_field(self, db_field, request, **kwargs): super(ProfileInline, self).formfield_for_choice_field(db_field, request, **kwargs) Key Error: ProfileForm: class ProfileForm(forms.ModelForm): curr_street = Address._meta.get_field('street').formfield() curr_city = Address._meta.get_field('city').formfield() curr_province = Address._meta.get_field('province').formfield() curr_country = Address._meta.get_field('country').formfield() class Meta: model = Profile fields = '__all__' def __init__(self, *args, **kwargs): super(ProfileForm, self).__init__(*args, **kwargs) self.fields['birth_date'].input_formats = settings.DATE_INPUT_FORMATS if self.instance.pk is not None: self.fields['curr_street'].initial = self.instance.address.street self.fields['curr_city'].initial = self.instance.address.city self.fields[ 'curr_province'].initial = self.instance.address.province self.fields['curr_country'].initial = self.instance.address.country self.helper = FormHelper() self.helper.form_tag = False -
using "primary" field in django model
i have two models: Address and Phone. Inside each model, rests a "Default" boolean field. What I need it to do, is if I submit a True answer in a form, then all other records must be set to False for that user. How do I accomplish this? class Address (models.Model): User = models.ForeignKey(User) Primary = models.BooleanField(default=True) Street = models.CharField(max_length=500) City = models.CharField(max_length=50) State = models.CharField(max_length=40) Zip = models.CharField(max_length=20) County = models.CharField(max_length=20) Country = models.CharField(max_length=50, default="United States") Latitude = models.FloatField(null=True, blank=True) Longitude = models.FloatField(null=True, blank=True) class Meta: verbose_name_plural = "Addresses" def __str__(self): primary = 'PRIMARY Address for ' if self.Primary else 'Address for ' return primary + self.User.first_name + ' ' + self.User.last_name def save(self, *args, **kwargs): geolocator = Nominatim() location = geolocator.geocode("{} {}, {}, {}".format(self.Street, self.State, self.Zip, self.Country)) self.Latitude = location.latitude self.Longitude = location.longitude super(Address, self).save(args, *kwargs) class Phone (models.Model): User = models.ForeignKey(User) Primary = models.BooleanField(default=True) Country_Code = models.CharField(max_length=5, default="001") Area_Code = models.CharField(max_length=5, blank=True, null=True) Number = models.CharField(max_length=20, blank=True, null=True) def __str__(self): return self.Country_Code + "-" + self.Area_Code + "-" + self.Number -
Allowing User to Update Fields in Django
I've created a UserProfile model with several custom fields, including an image field for a profile picture. My goal is to have users sign up with the basic Django sign-up form, and when a user is created, I create a UserProfile object. Shown below is a screenshot of my code from models.py: Here is what the django admin page displays for one instance of UserProfile (in this case the name is "zane"): What I'd like to do is extract these fields (city, description, website, phone, and profile pic) and display them in an HTML form so that the user can edit these fields after he or she signs up. I don't want to have to go into the admin page to do this. Step-by-step w/code examples would be super helpful since I'm a noob. -
How to solve the error with migration django?
admin.py from django.contrib import admin from main.models import * from django.db.models import TextField from file_picker.wymeditor.widgets import WYMeditorWidget @admin.register(MainUser) class MainUserAdmin(admin.ModelAdmin): list_display = ('username', 'first_name', 'second_name') class BlogAdmin(admin.ModelAdmin): prepopulated_fields = {'slug':('title', )} list_display = ('title', 'time') formfield_overrides = {TextField: { 'widget': WYMeditorWidget({}) } } class Media: js = ('http://cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js', ) admin.site.register(Blog, BlogAdmin) class PostLecture(admin.ModelAdmin): list_display = ('title') admin.site.register(PostLecture) models.py class PostLecture(models.Model): title = models.CharField(max_length=200) pdf = models.FileField() time = models.DateTimeField(auto_now_add = True) def __unicode__(self): return self.title def __str__(self): return self.title def get_absolute_url(self): return reverse("posts:detail", kwargs={"id": self.id}) class Meta: ordering = ['-time'] I did migration with commands (makemigration and migrate). After running server in Admin panel there is no my migration. And I have error like this: File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/nursultan/projects/diplomproject/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Users/nursultan/projects/diplomproject/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/Users/nursultan/projects/diplomproject/env/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/nursultan/projects/diplomproject/env/lib/python2.7/site-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/Users/nursultan/projects/diplomproject/env/lib/python2.7/site-packages/django/contrib/admin/apps.py", line 23, in ready self.module.autodiscover() File "/Users/nursultan/projects/diplomproject/env/lib/python2.7/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "/Users/nursultan/projects/diplomproject/env/lib/python2.7/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/nursultan/projects/diplomproject/diplomproject/main/admin.py", line 22, in <module> admin.site.register(PostLecture) File "/Users/nursultan/projects/diplomproject/env/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 86, in register for model in model_or_iterable: TypeError: … -
Use FormMixin/FormView along with dynamically created forms
While playing with Forms dynamically created (let's say, in order to have a multiple choice field filled up at runtime), is there a clean and programmatic way to use such Form along with FormView class? class MultipleChoiceForm(forms.Form): def __init__(self, options, *args, **kwargs): super(MultipleChoiceForm, self).__init__(*args, **kwargs) self.fields['calendars'] = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple, choices=[(o['id'], o['summary']) for o in options], required=True) As per now I managed to overload the get_form() method of my FormView: def get_form(self, form_class=None): """ Returns an instance of the form to be used in this view. """ if form_class is None: form_class = self.get_form_class() return form_class(self.options, **self.get_form_kwargs()) But I feel it's a bit hacky and that I will face many more issues with this approach, as the field has been generated dynamically. Probably this question has already been asked, but is it a cleaner and easier solution to this basic scenario? -
Authentication with Kong
I'm looking at Kong to replace my current hand-rolled NodeJS API gateway. Currently I have a user service that handles authentication (written in Django) by providing a JWT back upon login, which the client then passes in through a header. My current API gateway then intercepts any calls, does a validation call back to the user service, and replaces the JWT Header with X-User-Id and X-User-Email. As far as I can tell, Kong can do roughly the same thing. I'm trying to figure out the flow of how this should work in a perfect world. I still have the opportunity to replace much of the infrastructure, so rewriting some services is not completely out of the question. So, in my mind, what would happen is the following: User registers on my site. I then create a new consumer with their username/id on Kong User logs in. This is where I get stuck. Do I log in (or in this case, simply authenticate the user as being said user), ask Kong for the JWT for this consumer, and return that? What if I wanted some more data in the payload of the JWT? What happens on Kong's side when the JWT … -
Django Cloudinary Options
Is there a way to upload images with a specific size like width: 300, height:320 Using this in my model: image = CloudinaryField('image') I think is important to say I am working with the default admin site. image upload is working properly. -
Django JSONField and Q object
I would need to do something similar: # models.py from django.contrib.postgres.fields import JSONField, class MyModel(): *** ** admin_fields = JSONField(_('admin fields'), blank=True, null=True, help_text=admin_fields_help_text) my_instances = MyModel.objects.filter((Q(my_model_id=pk) & Q(children__isnull=True)) & ~Q(admin_fields__status__contains='deleted')) Or get all records with id=pk and children__isnull=True and JSONField admin_fields must not contain status==deleted Currently admin_fields = {'status': 'deleted'} Instead it returns only the record that has admin_fields = {'status': 'deleted'} Is ~Q() not working with JSONField? Ideas? Thanks, D