Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djagno instagram/facebook/youtube Auto like/follow
Is it possible to make a system with php/python or django where i will put my account username and password and it will auto like/follow/subscriber from my account to whatever account i want of youtube/facebook/instagram -
How to stop python-social-auth and reverse a transaction during pipeline step?
I have a Django application which uses python-social-auth for authentication. I have this in my django settings: SOCIAL_AUTH_PIPELINE = ( ... 'my.app.my.custom.pipeline', ) How do I stop the whole user creation process in my custom pipeline? I have tried throwing various exceptions including ValueError and AuthException but the created users remain in the database. Doesn't throwing an exception reverse the database transaction? -
Display an unknown number of fields in Django template with field content of another record as the label
I have a Django app which I want to be able to use in multiple instances. One model (Listing) can have a variable number of fields (for the different instances) but will then always have exactly those extra fields for the instance. I want these extra fields added through admin so I've created models like this: class BespokeField (models.Model): name = models.CharField( max_length = 20, verbose_name = "Field Title" ) def __unicode__(self): return self.name class Listing (models.Model): name = models.CharField ( verbose_name = 'Listing', max_length = 30 ) slug = models.SlugField ( verbose_name = "Slug", allow_unicode = True, unique=True, blank=True, null=True ) class ListingBespokeField (models.Model): bespoke_field = models.ForeignKey(BespokeField) listing = models.ForeignKey(Listing) value = models.CharField ( max_length = 60 ) def __unicode__(self): return u'%s | %s' % (self.listing.name, self.bespoke_field.name) The theory is admin specifies the bespoke fields and these are then displayed to the user in forms. Within admin this is relatively simple as I can assume a modicum on intelligence from the users so my admin.py looks like: class ListingBespokeFieldInline(admin.TabularInline): model = ListingBespokeField extra = len(BespokeField.objects.all()) max_num = len(BespokeField.objects.all()) class ListingAdmin(admin.ModelAdmin): inlines = [ListingBespokeFieldInline] It does mean the admin user has to select one of each BespokeField from the dropdown … -
Open source video hosting patform with Django/Python
Can anyone redirect me to an open source web applications for posting and sharing videos using laptops webcam or smartphone cameras built with Django and Django Rest Framework ? -
Having an edit form and a detail view on the same page
I am currently trying to get an edit form working on the same page as a detail view in Django. I am currently trying out the way as recommended on the docs (i.e. using FormMixin). So, my view looks like this: class ProductiveMinutesDetail(FormMixin, DetailView): model = models.ProductiveMinutes pk_url_kwarg = 'productiveminutes_pk' form_class = forms.EditForm def get_success_url(self): return reverse_lazy('productiveminutes_list') def get_context_data(self, **kwargs): context = super(ProductiveMinutesDetail, self).get_context_data(**kwargs) context['form'] = forms.EditForm(initial={'post': self.object}) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.save() return super(ProductiveMinutesDetail, self).form_valid(form) And my form looks like this: from django import forms from . import models class EditForm(forms.ModelForm): class Meta: model = models.ProductiveMinutes fields = ('name', 'description',) The model I am using is this: class Scenario(models.Model): name = models.CharField(max_length=200) class ProductiveMinutes(models.Model): scenario = models.OneToOneField(Scenario) name = models.CharField(max_length=200) amount = models.DecimalField(max_digits=50, decimal_places=2) description = models.CharField(max_length=200) Using this I can get the form to render on the page but I know I am doing something wrong as the fields are empty when I would like them to be populated with the data that is already present. Another piece of complexity is that this form should not be editing the … -
Django Rollout to Apache2 server WSGI script load failure
This is the first time I have attempted to deploy a Django project. I am using Raspbian on a Pi3. The project works with the built in Django test server. The project root (where the manage.py file is) is: /datadisk/powermon/power The virtualenv is found at: /datadisk/powermon/pja The Django settings.py file is at: /datadisk/powermon/power/power I have added the following lines to /etc/apache2/sites-enabled/000-default.conf WSGIDaemonProcess power python-home=/datadisk/powermon/pja WSGIProcessGroup power WSGIScriptAlias /power /datadisk/powermon/power/power/wsgi.py WSGIApplicationGroup $(GLOBAL) <Directory /datadisk/powermon/power/power> <Files wsgi.py> require all granted </Files> </Directory> Apache restarted after the changes. The WSGI file is the default one that is created by Django. import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "power.settings") application = get_wsgi_application() When the browser attempts to access the website it gets a 500 Internal Server Error Apache reports the following in /var/log/apache2/error.log [Tue Oct 17 13:05:25.006487 2017] [wsgi:error] [pid 764] [remote 192.168.0.106:0] mod_wsgi (pid=764): Target WSGI script '/datadisk/powermon/power/power/wsgi.py' cannot be loaded as Python module. [Tue Oct 17 13:05:25.007679 2017] [wsgi:error] [pid 764] [remote 192.168.0.106:0] mod_wsgi (pid=764): Exception occurred processing WSGI script '/datadisk/powermon/power/power/wsgi.py'. [Tue Oct 17 13:05:25.008344 2017] [wsgi:error] [pid 764] [remote 192.168.0.106:0] Traceback (most recent call last): [Tue Oct 17 13:05:25.009152 2017] [wsgi:error] [pid 764] [remote 192.168.0.106:0] File "/datadisk/powermon/power/power/wsgi.py", line 24, in <module> … -
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