Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Saves dont occur after editing permissions
I created a custom user model along with admin. Everything works great, however when I try to edit permissions for a user in admin I get an error relating to a password variable. I'm unsure of the root of the problem and would appreciate any help I get. Thank you for your help. The error traceback along with my code is posted below. Environment: Request Method: POST Request URL: http://localhost:8000/admin/accounts/user/9/change/ Django Version: 2.0.5 Python Version: 3.6.5 Installed Applications: ['accounts', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] 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.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/contrib/admin/options.py" in wrapper 574. return self.admin_site.admin_view(view)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/contrib/admin/sites.py" in inner 223. return view(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/contrib/admin/options.py" in change_view 1556. return self.changeform_view(request, object_id, form_url, extra_context) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 62. return bound_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func 58. return func.__get__(self, type(self))(*args2, **kwargs2) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/contrib/admin/options.py" in changeform_view … -
Why does my django ajax_select not work? 'core_user_add' is not a valid view function or pattern name
I am trying to user django-ajax-selects to add autocomplete pulldowns in my admin change_forms. I have a model that looks like this: class ApprovalControl(models.Model): status = models.CharField(max_length=50, default='Active') added = models.DateField(default=datetime.date.today, blank=True, null=True) risk = models.IntegerField(default=0) owner = models.ForeignKey('core.User', related_name="approval_control_owner") ... I was to set up a admin change form where potential "owners" will show up in an autocomplete widget. Here is the lookups.py file: from ajax_select import register, LookupChannel from .models import ApprovalControl @register('owner') class ApprovalControlsLookup(LookupChannel): model = ApprovalControl def get_query(self, q, request): return self.model.objects.filter(name=q) # return self.model.objects.filter(owner__person_type__in=[]) def format_item_display(self, item): return u"<span class='tag'>%s</span>" % item.name Here is the admin.py: @admin.register(ApprovalControl) class ApprovalControlAdmin(AjaxSelectAdmin): #form = make_ajax_form(ApprovalControl, {'owner': 'owner'}) form = make_ajax_form(ApprovalControl, { 'owner': 'owner', # }) def can_add(self, user, model): return True def get_form(self, request, obj=None, **kwargs): form = super(ApprovalControlAdmin, self).get_form(request, obj, **kwargs) autoselect_fields_check_can_add(form, self.model, request.user) return form Here's the forms.py: from django import forms from core.models import User from .models import ApprovalControl from ajax_select.fields import * class ApprovalControlForm(forms.ModelForm): class Meta: module = ApprovalControl owner = AutoCompleteSelectField( 'owner', required=False, help_text='help me!') When I go to my ApprovalControl list in the admin console I see this: But when I click on any of those links I get this error: NoReverseMatch … -
Django Channels 2 websockets multiple AuthMiddlewareStacks
Trying to make some app using websockets with django channels. I have 2 websocket clients - one is a web interface/js app, other - python application. I want a different authorization requirements for them (their consumers) (preferably a way to use AuthMiddlewareStacks) How can i implement this? can't find an answer in the doc https://channels.readthedocs.io/en/latest/topics/routing.html Here is a 'sketch'. (routing.py not gonna work this way). I use DRF, DRF-JWT, django channels 2, if it's relevant. appmain.routing.py application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( app.routing.websocket_cli_urlpatterns ) ), "websocket_0": TokenAuthMiddlewareStack( URLRouter([ app.routing.websocket_web_urlpatterns ]), ) }) app.routing.py websocket_cli_urlpatterns = [ path('ws/app/<str:var1>/<str:var2>/', consumers.CliConsumer), ] websocket_web_urlpatterns = [ path('ws/app/<str:var1>/', consumers.WebConsumer), ] Thank you! -
django-taggit: name versus slug lookup issues
I've got a Concert object with a genres field using django-taggit's TaggableManager(). I have a genres index page that lists all the genres and links to them: genres.html: {% extends 'base.html' %} {% block content %} <h1>Genres</h1> {% for genre in genres %} <ul class="genres"> <a href="{% url 'concerts:genre_filter' genre=genre.slug %}"> <li> {{ genre }} </li> </a> </ul> {% endfor %} {% endblock %} Each genre links to a new view that should show all concerts tagged with that particular genre. calendar.html heading: {% elif request.resolver_match.url_name == "genre_filter" %} <h1>Upcoming Events: <em>{{ genre }}</em></h1> <p class="center"> <a href = "{% url 'concerts:genre_filter_past' genre=genre %}"> Click here to see past events under genre <em>{{ genre }}</em> </a> </p> {% elif request.resolver_match.url_name == "genre_filter_past" %} <h1>Past Events with <em>{{ genre }}</em> Tag</h1> <p class="center"> <a href = "{% url 'concerts:genre_filter' genre=genre %}"> Click here to see upcoming events under genre <em>{{ genre }}</em> </a> </p> {% endif %} Here are the views for all of these: def genre_filter(request, genre): now = datetime.datetime.now() concerts = Concert.objects.filter(genres__name__in=[genre])\ .filter(date__gte=now).order_by('date') return render(request, 'concerts/calendar.html', {'concerts': concerts, 'genre': genre}) def genre_filter_past(request, genre): now = datetime.datetime.now() concerts = Concert.objects.filter(genres__name__in=[genre])\ .filter(date__lt=now).order_by('-date') return render(request, 'concerts/calendar.html', {'concerts': concerts, 'genre': genre}) def genre_index(request): … -
How can i generate a dynamic div id in django
How can i generate a dynamic div id using django . For example i have the following code {% for product in products %} {{product.nam}} <button id="{{product.id}}">like</button> {% endfor %} so my question is how can i generate a dynamic id for button using django. -
how can I summarize checked column with django-tables2
I have a table with some columns. One column is a checkboxcolumn. So, how can I summarize the "quantity" columns that checkboxcolumn is checked? I appreciate if someone can help me. -
How to write/read from a table in Django/Wagtail?
I'm working in a Django/Wagtail project. While saving an article I also need to write something in another table of the same DB. def save(self, *args, **kwargs): postToTable(self) super(ArticlePage, self).save(*args, **kwargs) The function postToTable should add some extra information to ANOTHER table (not the one I am saving to articles to) in the same DB. But I don't know what code I have to write to achieve that. The docs don't cover something so "manual", as I understand could go against good practices. Still, is it possible to do this? -
module 'Crypto.Random' has no attribute 'OSRNG'
I have a django app which uses pycrypto(2.6.1). When I do the following: from Crypto import Random Random.OSRNG.posix.new().read(block_size) I get a module 'Crypto.Random' has no attribute 'OSRNG' . However on inspecting site-packages, Crypo.Random does have a OSRNG file inside it. I'm not sure as to why I have this error. -
Django REST Framework validation error: 'Enter a valid URL.'
In my Django REST Framework project, I have a model class for saving services that the Django app will crawl in a background task: class Service(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=250) root_url =URLField(unique=True) Earlier on, I had both these services and the Django application running on my local machine. Now I containerized both the services and the Django application and have them running on Docker. So now I have a problem adding a dockerized service, because of its root URL: http://sensor-service:8080/. The error that is thrown is: 'Enter a valid URL.'. The problem occurs both when making a POST to my Django REST API, and when adding the Service via the GUI that the Django REST Framework provides. So, based on https://stackoverflow.com/a/49262127/5433896 and http://www.django-rest-framework.org/api-guide/serializers/#field-level-validation I tried the following: models.py: class DockerServiceDNSUrlsCompatibleURLValidator(URLValidator): def __init__(self, schemes=None, **kwargs): self.host_re = '(' + self.hostname_re + self.domain_re + self.tld_re \ + '|localhost|' \ + self.hostname_re + ')' # <=== added: "hostname not followed by a domain and/or TLD is acceptable" self.regex = _lazy_re_compile(r'^(?:[a-z0-9\.\-\+]*)://' # scheme is validated separately r'(?:\S+(?::\S*)?@)?' # user:pass authentication r'(?:' + self.ipv4_re + '|' + self.ipv6_re + '|' + self.host_re + ')' r'(?::\d{2,5})?' # port r'(?:[/?#][^\s]*)?' # resource path r'\Z', re.IGNORECASE) … -
django ajax_select newbee getting AttributeError: 'NoneType' object has no attribute 'model'
I am experimenting with Django Ajax Selects and I am following the Install documentation. Here is the code I have so far: approvalcontrol/lookups.py from ajax_select import register, LookupChannel from .models import ApprovalControl @register('approvalcontrol') class ApprovalControlsLookup(LookupChannel): model = ApprovalControl def get_query(self, q, request): return self.model.objects.filter(name=q) def format_item_display(self, item): return u"<span class='tag'>%s</span>" % item.name approvalcontrol/forms.py from django import forms from .models import ApprovalControl from ajax_select.fields import * class ApprovalControlForm(forms.ModelForm): class Meta: module = ApprovalControl # status is a field in the ApprovalControl model. status = AutoCompleteSelectField( 'status', required=False, help_text='help me!') approvalcontrol/admin.py from __future__ import unicode_literals from django.contrib import admin from ajax_select import make_ajax_form from ajax_select.admin import AjaxSelectAdmin ... from .models import ApprovalControl from .forms import ApprovalControlForm ... @admin.register(ApprovalControl) class ApprovalControlAdmin(AjaxSelectAdmin): # form = ajax_select.make_ajax_form(ApprovalControl, {'status': 'status'}) form = ApprovalControlForm When I start up my django server and go to /admin things work. If I click on 'Approval Controls' I get a list of that looks like: If I click on one of those links I get this error message: File "/opt/so/so_dev/env/lib/python2.7/site-packages/ajax_select/fields.py" in autoselect_fields_check_can_add 447. form_field.check_can_add(user, db_field.remote_field.model) Exception Type: AttributeError at /admin/sorequests/approvalcontrol/41/change/ Exception Value: 'NoneType' object has no attribute 'model' -
django ForeignKey Choice Model
I´m new to django and I want to create models with the following logic: class ExerciseCardio(models.Model): pass class ExerciseWeights(models.Model): pass class Exercise(models.Model): name = models.CharField(max_length=100, default='') EXERCISE_TYPE_CHOICES = ( (1, 'cardio'), (2, 'Weights'), ) exercise_type = models.PositiveSmallIntegerField( choices=EXERCISE_TYPE_CHOICES, default=2) if exercise_type == 1: exercise_model_type = models.ForeignKey(ExerciseCardio, on_delete=models.CASCADE, default=0) elif exercise_type == 2: exercise_model_type = models.ForeignKey(ExerciseWeights, on_delete=models.CASCADE, default=0) def __str__(self): return self.name I know it looks ugly But there has to be a way to do this -
django-taggit : filtering by slug rather than tag name
I seem to have backed myself into a corner. I'm trying to filter by genres defined using django-taggit, but I stupidly set this up using genre names, not slugs, and this screws things up when the name and slug don't match, which is fairly often. views.py: def genre_filter(request, genre): now = datetime.datetime.now() concerts = Concert.objects.filter(genres__name__in=[genre])\ .filter(date__gte=now).order_by('date') return render(request, 'concerts/calendar.html', {'concerts': concerts, 'genre': genre}) urls.py: ... url(r'^genre/(?P<genre>[\w-]+)/$', views.genre_filter, name="genre_filter"), ... template where the genre filter is linked: <a href="{% url 'concerts:genre_filter' genre=genre.slug %}"> So I understand conceptually that I am passing the genre name in my urls.py but that I'm linking to the slug in my template, which is leading to no data being retrieved when the slug is not the same as the link. I've tried to update my files like this: def genre_filter(request, slug): now = datetime.datetime.now() concerts = Concert.objects.filter(genres__name__in=[slug])\ .filter(date__gte=now).order_by('date') return render(request, 'concerts/calendar.html', {'concerts': concerts, 'slug': slug}) url(r'^genre/(?P<slug>[\w-]+)/$', views.genre_filter, name="genre_filter"), Error: NoReverseMatch at /concerts/genre/visual-arts/ Reverse for 'genre_filter_past' with keyword arguments '{u'genre': ''}' not found. 2 pattern(s) tried: [u'concerts/genre/past/(?P<genre>[\\w-]+)\\.(?P<format>[a-z0-9]+)/?$', u'concerts/genre/past/(?P<genre>[\\w-]+)/$'] (I have a mostly identical view named genre_filter_past that filters dates before today.) Any ideas? I suspect my problem is in the .filter(genres__name__in[slug]), but I don't know for sure. … -
Using Django jQuery plug in for formset
I want to use formset library and it says add jquery.formset.js to your MEDIA_ROOT; don't forget to include the jQuery library too.. How do I configure jquery.formset in my settings or urls to use jQuery library? I already read the doc and got some confusions about MEDIA_ROOT and STATIC files.. This is the link for the plug in doc https://github.com/elo80ka/django-dynamic-formset/blob/master/docs/usage.rst settings.py Django settings for ctb72 project. Generated by 'django-admin startproject' using Django 2.0.5. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ #overall setting for my website import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'aeq57x7v=!2kf(^$yskosz4&qyd8ex5%ic_o)&ekl_322pdq=o' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #custom apps 'niro.apps.NiroGeneratorConfig', ] 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.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ctb72.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': … -
How to delete a Django model without deleting the table
How can I delete a Django model without effecting the table it works with. Previously we've used the model and table normally but have since moved the models functionality to a microservice which still operates on the same table. -
Twilio RequestValidator always returns false
I have had an app up and running for a while, but it recently stopped working, and I am unsure why. I assumed that it might be possible that Twilio deprecated something that I hadn't kept up on, so I decided to update to their latest library, and try again, but no matter what I do, Twilio won't validate that the requests came from them. On my local environment, I am using ngrok, but I am using the http link, not the https link. When I debug and check what request.build_absolute_uri() is producing, it is the correct link that I have put as the webhook link. I am receiving lots of POST data, and I do receive and resend HTTP_X_TWILIO_SIGNATURE. In fact, I copied and pasted the code I will post below from this link. It only slightly varies from my code, but I figured that if I use their exact code, it should work. It doesn't. def validate_twilio_request(f): """Validates that incoming requests genuinely originated from Twilio""" @wraps(f) def decorated_function(request, *args, **kwargs): # Create an instance of the RequestValidator class validator = RequestValidator(TWILIO_AUTH_TOKEN) # Validate the request using its URL, POST data, # and X-TWILIO-SIGNATURE header request_valid = validator.validate( request.build_absolute_uri(), … -
Django signals > right approach?
In my signals.py I am doing the import for the function unique_order_reference_generator within the function reserveditem_create_order_reference. I wonder if that is the right approach, or is there a better solution? utils.py from lumis.utils import get_random_string from .models import Order, ReservedItem def unique_order_reference_generator(): new_id = get_random_string(length=10) reserved_item = ReservedItem.objects.filter( order_reference=new_id ).exists() order = Order.objects.filter(order_reference=new_id).exists() if reserved_item or order: return unique_order_reference_generator() # TODO Marc: Test else: return new_id signals.py # Generate order reference def reserveditem_create_order_reference(sender, instance, **kwargs): from .utils import unique_order_reference_generator if not instance.order_reference: instance.order_reference = unique_order_reference_generator() app.py class OrdersConfig(AppConfig): name = 'orders' def ready(self): #Pre save signal for ReservedItem model reserved_model = self.get_model('ReservedItem') pre_save.connect( reserveditem_create_order_reference, sender=reserved_model, dispatch_uid="my_unique_identifier" ) -
Python-Django run server error! pre-migrations, how can I fix this?
I'm having a hell of a time figuring out what I'm doing wrong. Two weeks ago, I was able to operate a django server from my windows powershell, following the exact path below. First time I got the error, I uninstalled/re-instaled virtuenv, I re-installed django, I created everything with a brand new directory and I still get the error "ImportError: DLL load failed: %1 is not a valid Win32 application." which occurs at the end of this code block. Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. PS C:\WINDOWS\system32> cd c:/ PS C:\> Set-ExecutionPolicy Unrestricted Execution Policy Change The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose you to the security risks described in the about_Execution_Policies help topic at https:/go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy? [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "N"): y PS C:\> py -V Python 3.6.5 PS C:\> pip -V pip 10.0.1 from c:\users\jlamantiaiv\appdata\local\continuum\anaconda3\lib\site-packages\pip (python 3.6) PS C:\> pip freeze alabaster==0.7.10 asn1crypto==0.24.0 astroid==1.6.1 astropy==2.0.3 attrs==17.4.0 Babel==2.5.3 backports.shutil-get-terminal-size==1.0.0 beautifulsoup4==4.6.0 bitarray==0.8.1 bkcharts==0.2 bleach==2.1.2 bokeh==0.12.13 boto==2.48.0 Bottleneck==1.2.1 certifi==2018.1.18 cffi==1.11.4 chardet==3.0.4 click==6.7 cloudpickle==0.5.2 clyent==1.2.2 colorama==0.3.9 … -
I wanna create model which Before adding it must be accepted
I would like to create a model which must be accepted by the moderator before adding, after which every change in eg the title in this model must also be accepted class MangaRequest(models.Model): title = models.CharField(max_length=191) type = models.CharField(max_length=30,choices=TYPE, blank=True, default='', null=True) status= models.CharField(max_length=30, choices=STATUS, blank=True, default='', null=True) date_start = models.DateField(blank=True, null=True) data_end = models.DateField(blank=True, null=True) age_restrictions = models.ForeignKey(OgraniczenieWiekowe, null=True, default='', blank=True) volumes = models.SmallIntegerField(null=True, blank=True, default=0) chapter = models.SmallIntegerField(null=True, blank=True, default=0) is_accept = models.BooleanField(default=False) delete = models.BooleanField(default=False) This is my model and I have done it def save(self, *args, **kwargs): if self.is_accept == True: manga = MangaAccept.objects.create(...) super(MangaRequest, self).delete() return manga else: super(MangaRequest, self).save() And the same way is about deletes My question is how can ACCEPT or REJECT for model and everyone field in this model ? Any sugestion ? -
Django signals dispatch_uid
I have a question regarding the usage of dispatch_uid for signals. Currently, I am preventing multiple usage of the signal by simply adding if not instance.order_reference. I wonder now if dispatch_uid has the same functionality and I can delete if not... signals.py def reserveditem_create_order_reference(sender, instance, **kwargs): if not instance.order_reference: instance.order_reference = unique_order_reference_generator() app.py class OrdersConfig(AppConfig): name = 'orders' def ready(self): #Pre save signal for ReservedItem model reserved_model = self.get_model('ReservedItem') pre_save.connect( reserveditem_create_order_reference, sender=reserved_model, dispatch_uid="my_unique_identifier" ) -
How to avoid MySQL + Django TimeField shooting itself in the foot at midnight?
MySQL 5.7.22 (but this happened with earlier versions) too. Happened with Django 1.8, now with Django 1.11, so wide range of MySQL and Django versions. class ShootFootAtMidnight(models.Model): time = models.TimeField(blank=True, null=True) time_source = models.ForeignKey(TimeSource) def save(self, *args, **kwargs): if self.time_source: self.time = self.time_source.time super(ShootFootAtMidnight, self).save(*args, **kwargs) Now, if there are a ton of these created around midnight time, sooner or later I'll face this: ValueError: hour must be in 0..23 If I look at the database with MySQL prompt, I see the object is created honky and dory and has a time of 24:00:00. This value did not come from an auto_now field. Django actually created an object what it cannot read back (?!?!?). If I manually correct the time to 23:59:59 the ValueError: hour must be in 0..23 goes away, but how can I prevent this from happening? -
OuterRef not allowed in an annotation?
I'm trying to annotate a queryset of Entity objects with the distance between two related polygons; each entity has its own set of related polygons, stored in the shape attribute of foreign-key-related EntityFeature objects. EntityFeatures are named, and I need to find the distance between two named features for each entity: Entity.objects.all().annotate( distance = ExpressionWrapper( Subquery( EntityFeature.objects.get( entity__id = OuterRef('id'), name = 'feature_a' ).shape.centroid.distance( Subquery( EntityFeature.objects.get( entity__id = OuterRef(OuterRef('id')), name = 'feature_b' ).shape.centroid ) ) ), output_field = DecimalField() ) ) As soon as it reaches the first OuterRef, I get ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. I've tried removing the first subquery and using F('id'), but then I think id refers to the EntityFeature's id instead and it throws DoesNotExist: EntityFeature matching query does not exist. Am I going about this the wrong way? What's the best method to find the distance between two related objects for each thing in a queryset? [python 2.7.15 / django 1.11] -
How to build a tree in html?
I have hierarchy of tasks. I want to build a tree. Now I can build tree, but I have duplicates of task. How can I check if the task was already shown? Now I have this code: template.html <ul> {%for task in tasks %} {%include "tree.html" %} {%endfor%} </ul> tree.html <li>{{task.name}}</li> <ul> {%for ch in task.children.all %} {%with task=ch template_name="tree.html" %} {%include template_name%} {%endwith%} {%endfor%} </ul> </li> Model of class Task class Task(models.Model): name = models.CharField(max_length=200) parent = models.ForeignKey('self', null=True, blank=True, related_name='children') -
django-cors-headers CORS_ORIGIN_WHITELIST tuple vs string issue
I'm trying to use django-cors-headers for my project. It appears when I set CORS_ORIGIN_WHITELIST as a string it works fine. But when I use it as a tuple it doesn't work. Any idea why? I can't find anything specific in the documentation about the difference between using a tuple or string. To load the JSON I'm using jQuery $.getJSON() $.getJSON( "http://127.0.0.1:8000/accounts/api_r/44234138/?format=json", function( data ) { var items = []; $.each( data, function( key, val ) { items.push( "<li id='" + key + "'>" + val + "</li>" ); }); $( "<ul/>", { "class": "my-new-list", html: items.join( "" ) }).appendTo( "#foo" ); }); -
How to do form handling in Django Generic CBV?
I'm trying to do the same thing below in Django Generic CBV. Function Based View def form_handling(request): if request.method == "POST": form = SimilarStore(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('...') else: form = SimilarStore() ... Class Based View class SimilarStoreCreateView(CreateView): model = SimilarStore form_class = SimilarStoreForm template_name='cms/similarstore_new.html' success_url=reverse_lazy('cms:similarstore') def form_valid(self, form): form = SimilarStoreForm(request.POST, request.FILES) form.save() return redirect(self.get_success_url()) def form_invalid(self, form): form = SimilarStoreForm() ... I'm confused about how I can check if request.method is POST or GET in Django Generic CBV. I know Django regular CBV supports get() and post(). However, in Generic views, there's no post(). What should I do to handle POST requests in Django Generic? -
Django and mustaches (using index from laravel)
I did earlier some laravel site(sass,jquerry,angular) which now I want to use in django but seems not so easy, got errors at the very beginning. 2 <html lang="PL"> 3 <head> 4 <meta charset="utf-8"> 5 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 6 <meta name="viewport" content="width=device-width, initial-scale=1"> 7 <link href="https://fonts.googleapis.com/css?family=Cinzel:400,700,900&amp;subset=latin-ext" rel="stylesheet"> 8 <title>@yield('title')</title> 9 10 11 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script> 12 {{--jquery--}} error at line 12