Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Requested JSON parse failed with multiple data
I'm stuck: I'm trying to submit a django form using AJAX, but I can't find a way to send multiple data fields via my AJAX call. $(document).ready(function() { $("#dental").click(function() { $.ajax({ url: " ", type: "POST", dataType: "json", data: { left:leftList, right:rightList, bottom:bottomList, center:centerList, top:topList, csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value }, success : function(json) { alert("Successfully sent the URL to Django"); }, error: function(jqXHR, exception){ var msg = ''; if (jqXHR.status === 0) { msg = 'Not connect.\n Verify Network.'; } else if (jqXHR.status == 404) { msg = 'Requested page not found. [404]'; } else if (jqXHR.status == 500) { msg = 'Internal Server Error [500].'; } else if (exception === 'parsererror') { msg = 'Requested JSON parse failed.'; } else if (exception === 'timeout') { msg = 'Time out error.'; } else if (exception === 'abort') { msg = 'Ajax request aborted.'; } else { msg = 'Uncaught Error.\n' + jqXHR.responseText; } $('#messages').html(msg); console.log(msg); }, }); }); }); It only shows Requested JSON parse failed. The individual values of leftList, rightList, bottomList, centerList is good when I tried to show it individually. What's the correct syntax to call multiple data in my AJAX call? I formatted my data using this **UPDATE … -
django-smart-selects not working on load the instance create page, but work after click save with validation errors
I have four models: class AgeGroups(models.Model): title = models.CharField('title', max_length=20) .... class Command(models.Model): title = models.CharField('title', max_length=50) age = models.ForeignKey( AgeGroups, verbose_name='age', related_name='command_ages' ) ... class Tournament(models.Model): date_begin = models.DateField('Begin date of tournament') date_end = models.DateField('End date of tournament') .... class Game(models.Model): tournament = models.ForeignKey(Tournament) age = models.ForeignKey(AgeGroups, verbose_name='Age') team1 = ChainedForeignKey( Command, verbose_name = 'First team', chained_field="age", chained_model_field="age", auto_choose=True, related_name='first_team_games') .... And in admin.py in TournamentAdmin use GameAdmin as inline: class GameInline(admin.StackedInline): model = Game extra = 0 @admin.register(Tournament) class TournamentAdmin(admin.ModelAdmin): inlines = (GameInline,) When I open the admin page for adding new Tournament and add new Game in Tournament, when I choose age, smart_selects must add the commands, wich are related with this age. But this is not happening. But, if I click to Save button (I did not fill in any fields). I take the validation errors and after this the smart_selects begin to work properly. Why is this happening? I noticed that in the moment when smart_selects not working, he not sends a request to get list for select. This is visible in the browser tools. -
Django queryset unique related objects
I have the model structure like below. class Subscription(models.Model): title = models.CharField(max_length=250) class SubscriptionChangeEvent(models.Model): subscription = models.ForeignKey(Subscription, related_name='subscription_change_events') changed_date = models.DateTimeField(auto_now_add=True) notes = models.TextField() I am trying to find out the latest SubscriptionChangeEvent of all the dogs. I have tried SubscriptionChangeEvent.objects.order_by('-changed_date').distinct('subscription') This did not work and got the error 'SELECT DISTINCT ON expressions must match initial ORDER BY expressions'. What query can i use to achieve this ? -
allauth with crispyform : signup not working
I try to enhance my all auth's signup form with Crispy-form but it's not working :) I modify the allauth form in the forms.py to hide the labels and add the button My current problem is that the "self.helper.layout = Layout" in the forms.py makes the fields to disappear in the template, but if I comment the self.helper.layout = Layout, I don't have a button to validate my form x( I would like to have my fields and a working submit button for my form, Thanks for your help! details below forms.py from django import forms from allauth.account.forms import SignupForm from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, ButtonHolder, Submit,Field from crispy_forms.bootstrap import FormActions class MySignupForm(SignupForm): def __init__(self, *args, **kwargs): super(MySignupForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False self.helper.layout = Layout( FormActions( Submit('submit', 'Sign-up', css_class = 'btn-primary') ), ) I also define in my settings.py that I was using a custom form as signup # CUSTOM : Allauth Setup part AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ) ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = False SOCIALACCOUNT_QUERY_EMAIL = ACCOUNT_EMAIL_REQUIRED #Since users … -
How do I send Jquery variable to my views.py using $.post(), and how do i retrieve them without refreshing the page
what im tryng to do is a step form inside a modal. the content for my step 1 are treatments or services looped from my database. and when i click one of these (".alert")(i used BS alerts as a button), the treatments id will be stored inside a hidden input in the next step's fieldset. what i want to happen is to send that id back to my views.py and retrieve it so i could get the information about the treatment's duration. the function in my js where the magic should happen $(".alert").click(function(){ service_id = $(this).find("input").val(); current_fs = $(this).parents("fieldset"); next_fs = $(this).parents("fieldset").next(); $("#nav li").eq($("fieldset").index(next_fs)).addClass("active"); $("#nav li").eq($("fieldset").index(current_fs)).removeClass("active"); current_fs.hide(); next_fs.show(); next_fs.find("div").find("input").val(service_id); $.post("{% url 'calendarium:data' %}",{id: service_id}); }); my views.py @csrf_exempt def time(request): data = request.POST.get('id','') treatment = get_object_or_404(Services, pk = data) return render(request,'calendarium/calendar_msform.html', {'treatment':treatment}) my calendar_msform.html <fieldset id="#step-2" style="display: none"> <div style="display:block; border-style:solid; border-color:#aa9977; border-radius: 5px; box-shadow: 0 0 15px 1px rgba(0, 0, 0, 0.4); padding: 5px"> <input type="hidden" value=""> {% if treatment.duration == 30 %} <div class="alert alert-default" style="padding: 2px"> 10:00 - 10:30 am <label style="float: right; margin-right: 10px"> <small>{{ s.duration }} mins</small></label> </div> {% else %} {% endif %} </div> <input id="backStep1" type="button" name="previous" class="previous action-button-previous" value="Previous"/> <input id="toStep3" type="button" … -
How the best way to verify if exist a record in database in Django 1.11.x?
I want verify if exist a integer number of order before save. How I do this? My Model: class Board(models.Model): name = models.CharField(...) curriculum = models.TextField(...) order = models.IntegerField(...) def save(self, *args, **kwargs): try: # HOW DO I GET THE VALUE COMING FROM THE FORM, AND CHECK IF IT EXISTS IN THE DB? super(Board, self).save(*args, **kwargs) except ObjectDoesNotExist: pass -
Django CMS - Aldryn Bootstrap broken grid system
I have recently started to develop a website using Django CMS. Everything is going perfectly fine apart from the broken grid system whilst using Alrdyn Bootstrap. All other components seem to be working fine, but the grid system will not comply with the settings I am inputting within the CMS, for example. If I state col-lg-4 col-xs-6 within a class, the component will comply with the first class only, and will not shrink when in mobile. If anyone has any insight I'd very much appreciate it. -
Django Django model “doesn't declare an explicit app_label” because of project's init.py file
I have a django 1.11 project with some rest_framework related apps. Writing tests for new app, I have suddenly gotten the issue 'RuntimeError: Model class core.myApp.models.query_record doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS' I do have this listed in installed_apps, and in the end, the reason I have this issue is because I have an __init.py__ file in the top level of the project that loads some config for some related celery tasks. I'm unaware why I haven't seen this issue in other app tests, as there is nothing particularly special about this app or it's model. But, this is causing all tests to fail for this app. So, my question is, is there a way I can run these unit tests and ignore the projects top level __init.py__ ? Or maybe I should ask, is there a non-hacky way to do it? -
Extend the list of validators in a subclass
Let's say, I have a superclass class Super(models.Model): f = models.CharField(validators=[relaxed_validator, ], ...) and a subclass class Sub(Super): ... For the Sub, I would like to make the f-field validation more strict and run validators=[relaxed_validator, strict_validator,]. What is the "proper" way to do it? I can create a clean() method, but that's typically used for multi-field validation. Can I maybe somehow extend the list of validators in the subclass? -
Django makemigrations No changes detected in app
I have trouble with my makemigrations command. Note: I have successfully make migrations till now, so it is not the first time I try to make migrations on this project. Problem: For some reason project stop detecting any changes in my models. Inside my project models.py I have: from myproject.myfolder import myModel1 from myproject.myfolder import myModel2 from myproject.myfolder import myModel3 if a add new models as myModel4 class and import it inside models.py and I try to python mamange.py makemigrations environment=local I get No changes detected I know there are a lot of posts of making the initial migrations, so I even try python manage.py makemigrations myProjectLabel environment=local I even try to delete all files in __pycache__ but it doesn't work for me. I even try to delete database and create new one, and it doesn't work either. -
Parameter send from JsonRespond doesnt pass to HTML page , Python django
I have a webapp build in Python 2.6 and Django. I am trying to send parameters to the HTML page but it seems that the HTML page is refreshing to the default values all the time. Meaning i can see that movetobi is being called but it looks like the moment movebi return the value the page is reloaded again View.py def adminoperation(request): return render(request,'app/adminoperation.html',{'some_flag':'999999'}) def movetobi(request): if 'check' in request.POST and request.POST.get('check'): data= {'newtest':3} return JsonResponse(data, safe=False) adminoperation.html {% extends "app/layout.html" %} {% block content %} <p>Adminstration site for FTMS 2017</p> <h2> {{mssg}}</h2> <p>{{ mssg2 }} </p> <p>{{ mssg3 }} </p> <form id="data_form" method="post" enctype="multipart/form-data"> {% csrf_token %} <button id="run_reports" type="submit" name="action" value="commit">Run Reports For BI</button> <br> <br> <button id="Rollback" type="submit" name="action" value="commit">Rollback</button> input type="hidden" id="commitok" name="commitok" value="{{ some_flag }}" /> </form> {% endblock %} {% block scripts %} <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css"> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script> <script> $(function () { $('#run_reports').click(function () { $.ajax({ type: "POST", url: 'movetobi', data: { 'check' : '1', 'csrfmiddlewaretoken': '{{ csrf_token }}' }, success: function (data){ if (data['newtest']==3) { confirm("You are trying to run a month that allready exist"); }}, error: function(data){ if (data['newtest']==5) { confirm("test"); }} }); }); }); … -
How to use django debug toolbar improve response
Ive recently migrated my app to docker, and my DB to MySQL. I keep experiencing huge load times on random browses of the app. ive installed and run debug tool bar which is showing me that I have around 24 second load time of the page. however im not sure how to diagnose what is the issue and how to resolve it? -
How to redirect the Django Form after getting the result from Database
I am trying to get the input from user after that i am doing a search operation using those parameters. Individually i am able to fetch the result populate in index.html View.py def index(request): form2 = storedprocedure(request.POST) cursor=connection.cursor() if form2.is_valid(): companyname=form2.cleaned_data['companyname'] Year=form2.cleaned_data['companyname'] sql="EXEC [SP_Competitor_Extract]" cursor.execute(sql+companyname+","+str(Year)) while cursor.nextset(): try: results={'results':cursor.fetchall()} break except: continue return render(request,'index.html',results) else: print(form2.errors) form=storedprocedure() return render(request,'test.html',{'form':form}) Urls.py urlpatterns = [ # url(r'^webapp/', include('webapp.urls')), url(r'^DS_LAB_4/', include('DS_LAB_4.urls')), url(r'^admin/', admin.site.urls), ] -
How to create ajax request on geodjango with leaflet?
I am new to leaflet and developing an application using wms layers (geoserver), postgis and geodjango. I am curious can we do following on it In WMS layer (geoserver) with leaflet build the click function on a point,line/polygon layer. Pass that parameter to the django (know which point is clicked like ID). Then respond with customized identification pop-up with charts. -
Changing default field validator in Django ModelForm
I have custom clean_* form method, which does verify uploaded image type and file extension. class TableModelForm(ModelForm): def clean_image(self): img_err = 'Unsupport image type. Please upload png, jpg or gif.' img_formats = ['png', 'jpeg', 'gif'] img = self.cleaned_data.get('image') if not img: return img img_fmt = img.image.format.lower() img_ext = splitext(img.name)[1][1:].lower() if any([x not in img_formats for x in [img_fmt, img_ext]]): raise ValidationError(ugettext_lazy(img_err), code='invalid_image') return img It works well until the image of the appropriate format but without a file extension is attempted to upload, in which case default_validator kicks in and I see the default FileExtensionValidator error message: File extension '' is not allowed. Allowed extensions are: 'bmp, bufr, cur, pcx, dcx, dds, ps, eps, fit, fits, fli, flc, fpx, ftc, ftu, gbr, gif, grib, h5, hdf, png, jp2, j2k, jpc, jpf, jpx, j2c, icns, ico, im, iim, tif, tiff, jfif, jpe, jpg, jpeg, mic, mpg, mpeg, mpo, msp, palm, pcd, pdf, pxr, pbm, pgm, ppm, psd, bw, rgb, rgba, sgi, ras, tga, webp, wmf, emf, xbm, xpm'. Is there a way to replace the default_validator of the ModelForm field without re-declaring the field? -
Django Wagtail adding classname to structblock
I have a structblock as below: image = StructBlock([ ('file', ImageChooserBlock()), ('caption', RichTextBlock( classname='caption' )), ]) But on the frontend template {{item.value.caption}} produces a div with class 'rich-text'. Am I missing something? I am using wagtail 1.13 with django 1.11.6 ( python 3.6 ) -
Python, Django LDAP: detecting Authentication failed reasoning
I am working on a project to integrate LDAP authentication in an existing Django app. Using this site and others I have finally been able to configure everything correctly using the django_auth_ldap backend. Including: AUTH_LDAP_REQUIRE_GROUP = "CN=myGroup,CN=groups [...] " So only users in group "myGroup" can log in. Everything is configured correctly now in the settings.py and within the user_login view there is just: ... user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return redirect('index') else: message = "Your account is disabled." else: message = "Invalid username or password supplied." ... Now the last step has to be a notification to the user why his login had failed. right now the fail message will always be: "Invalid username or password supplied." This should be either: - Wrong username/password - Not in the right group Something like: if user: ... else: if (LDAP auth failed reason == user does not satisfy AUTH_LDAP_REQUIRE_GROUP): message = "You are not in the right user group." else: message = "Invalid username or password supplied." ... How can I know, in my user_login view the reason for LDAP Authentication failed? P.S.: in the django_auth_ldap log I DO see "DEBUG Authentication failed for username: user … -
Static files not showing with nginx on django server
I have problem getting the static files with nginx. This is the settings of my file in /etc/nginx/sites-available/app location /static/ { alias /home/username/projects/website/static/; } And on my server I checked that my files acctually exist in this directory /home/username/projects/website/static/ I see that files are being called in the wepage from http://xxx.xxx.xx.xx/static/app/images/image.png This file exist on server in directory /home/username/projects/website/static/app/images/image.png My settings file have defines STATIC_ROOT like this STATIC_ROOT = '/home/username/projects/website/static' STATIC_URL = '/static/' I'm really confused. Reading and searching for typos or mismatches. I really need a new set of eyes and pointers. -
Django ORM error: FieldError: Cannot resolve keyword XXX into field
When I typing comds = Purchased.objects.filter(category_id = '1'), it thrown a error like this FieldError: Cannot resolve keyword 'category_id' into field. Choices are: comd_expire, comd_img_type, comd_name, id, player, player_id, purchase_time, status, and my table's fields are: my models is: I don't know why there has no category and category_id -
Is there any function in Django that tests if a field instance of a model is primary key?
In Django, is there a way (function) to test if a model field is primary key (pk)? For instance, my model is: class Gender(models.Model): name = models.CharField(max_length=50, primary_key=True) def __str__(self): return self.name Is there a function to test for name being primary key? -
Custom validation for formset in Django
I can't figure out how to make a custom validation for my formset. I'm trying to prevent users to select more than 12 times the same year, but when I print it, the cleaned_data comes in as a different dictionary for each form. I would like to have all forms grouped into 1 dictionary to check if one year appears more than 12 times, or to write this in a better way. My code: forms.py class SellerResultForm(forms.ModelForm): class Meta: model = SellerResult fields = ('month', 'year', 'result',) widgets = { 'month': forms.Select(attrs={'class': 'form-control',}), 'year': forms.Select(attrs={'class': 'form-control',}), 'result': forms.TextInput(attrs={'class': 'form-control',}), } def has_changed(self): #used for saving data from initial changed_data = super(SellerResultForm, self).has_changed() return bool(self.initial or changed_data) def clean(self): cleaned_data = super(SellerResultForm, self).clean() print(cleaned_data) # prints a set of dictionaries # {'month': 4, 'year': 2017, 'id': 1, 'result': 1000} # {'month': 5, 'year': 2017, 'id': 1, 'result': 1000} # {'month': 6, 'year': 2017, 'id': 1, 'result': 1000} views.py def seller_result(request, user_id): SellerResultFormSet = modelformset_factory(SellerResult, form=SellerResultForm, extra=1, max_num=1) queryset = SellerResult.objects.filter(seller=user_id,).order_by('year', 'month') formset = SellerResultFormSet(request.POST or None, queryset=queryset, initial=[ {'month': datetime.now().month, 'year': datetime.now().year, 'result': 1000,}]) if formset.is_valid(): instances = formset.save(commit=False) for instance in instances: instance.seller_id = user_id instance.save() context = { 'formset': … -
Extending Django filer image model by category field
I recently had problems with extending django filer, probably my knowledge about django is not sufficient yet. Basically what I would like to achieve is to extend django filer image model to be able to add category to images. Of course would be nice to have manytomany relation to category model. Could someone help me with this topic? my code (all in myPlugins app): models.py from filer.models.abstract.BaseImage class CustomImage(BaseImage): category = models.CharField(max_length=20, blank=True, null=True,) class Meta: app_label = 'myPlugins' admin.py from django.contrib import admin from filer.admin.imageadmin import ImageAdmin from myPlugins.models import CustomImage class CustomImageAdmin(ImageAdmin): pass CustomImageAdmin.fieldsets = CustomImageAdmin.build_fieldsets( extra_main_fields=('author', 'default_alt_text', 'default_caption', 'category'), extra_fieldsets=( ('Subject Location', { 'fields': ('subject_location',), 'classes': ('collapse',), }), ) ) admin.site.unregister(ImageAdmin) admin.site.register(CustomImage, CustomImageAdmin) in settings.py I've added: FILER_IMAGE_MODEL = 'myPlugins.models.CustomImage' and I'm getting an error: File ".../mysite/myPlugins/admin.py", line 27, in admin.site.unregister(ImageAdmin) File ".../venv/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 118, in unregister for model in model_or_iterable: TypeError: 'MediaDefiningClass' object is not iterable -
Extremely high CPU usage in Django
I am helping to develop a fairly complex web application with Django. However some pages are taking 10+ seconds to render. I can't seem to get to the bottom of why this is so slow. The Django Debug Toolbar shows that the bottleneck is clearly CPU, rather than the database or anything else, but it doesn't go into any further detail (as far as I can see). I have tried running a profiler on the system, but can't make head or tail of what is going on from this either. It only shows deep internals as taking up the vast majority of the time, especially <method 'poll' of 'select.poll' objects>, and other such functions as builtins.hasattr, getmodule, ismodule, etc. I've also tried stepping through the code manually, or pausing execution at random points to try to catch what's going on. I can see that it takes quite a long time to get through a ton of import statements, but then it spends a huge amount of time inside render() functions, taking especially long loading a large number of model fields--something in the order of 100 fields. None of what is happening looks wrong to me, except for the insame amount … -
Django ORM how to use datetime_trunc_sql
I am trying to truncate a datetime field to a date and afterwards use that filed for aggregation operations. I managed to that with date_trunc_sql function like this: truncate_date = con inner_query = "mytable.datetime AT TIME ZONE '%s'" % 'Europe/Amsterdam' truncate_date = conection.ops.date_trunc_sql('day', inner_query) queryset = queryset.extra({'day': truncate_date}) Now i saw that there is also a function datetime_trunc_sql that takes the timeozone as paramater but could not make that work. I tried: truncate_date = conection.ops.datetime_trunc_sql('day','mytable.datetime','Europe/Amsterdam') queryset = queryset.extra({'day': truncate_date}) It fails with the error StopIteration at api/v3/... and closes the connection at the second line: queryset = queryset.extra({'day': truncate_date}) Any ideas why? Thanks -
Django Rest Framework Browsable Api Specify display/value pair for foreign key field dropdown
My model is as (only pseudocode) class Country(models.Model): Name = models.CharField(max_length=255, unique=True) Code= models.CharField(max_length=3, unique=True) def label(self): return self.Name + " - " + self.Code def __unicode__(self): return str(self.label()) def __str__(self): return str(self.label()) class Mountain(models.Model): Country = models.ForeignKey(Country, related_name='mountain') I have successfully created a custom foreign key serializers.RelatedField that displays "Name - Code" on read but only accepts the Code on write. This works fine using Postman. However in my Browserble api I see a dropdown of countres displayed as "Name - Code" but when i post it posts the Name field of the model. I need send the Code field from the browsable api. How do I specify this and where. Primarily how do i specify what the display/value pair should be for a foreign key dropdown field in the browsable api