Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ChartJs Radar customisation in django
I am trying to make charts work in my Django Application using chart.JS But I am having some difficulties to make it look great ! here it how it looks: I would have two questions: 1) How can I add a bottom margin in the chart label 'Team Test" 2) How can I center verticaly the right chart 3) How can I increase the space of the chart and the labels ? Here is my code : //graph 2// var info_process = new Chart(ctx2,{ type: 'radar', data: { labels: labels_info, datasets: [{data: info_data, label: team_name, backgroundColor: "rgba(102, 187, 158, 0.2)", borderColor: "rgba(102, 187, 158, 0.9)", pointBackgroundColor: "black", pointBorderColor: "#fff", pointHoverBackgroundColor: "yellow", pointHoverBorderColor: "rgba(179,181,198,1)", }] }, options: { scale: {display: true, ticks: { beginAtZero: true, } }, responsive:true, maintainAspectRatio: true, } }); //end graph 2// //graph 3// var info_process = new Chart(ctx3,{ type: 'radar', data: { labels: label_action, datasets: [{data: action_data, label: team_name, backgroundColor: "rgba(102, 187, 158, 0.2)", borderColor: "rgba(102, 187, 158, 0.9)", pointBackgroundColor: "black", pointBorderColor: "#fff", pointHoverBackgroundColor: "yellow", pointHoverBorderColor: "rgba(179,181,198,1)", }] }, options: { scale: {display: true, ticks: { beginAtZero: true, } }, responsive:true, maintainAspectRatio: true, } }); //end graph 3// -
How to edit Django form into a bootstrap modal?
My situation: urls.py url(r'^edit/(?P<pk>[0-9]+)/$', views.edit, name='edit'), views.py def edit(request): if request.method == 'POST': form = EditForm(request.POST) if form.is_valid(): form.save() else: pass return redirect('home') template.html {% extends 'base.html' %} {% load staticfiles %} <div class="container"> {% for x in context %} [...] <button class="btn btn-warning" role="button" data-toggle="modal" data-target="#modalEdit">Edit</button> [...] {% endfor % </div> {% include 'modal.html' %} modal.html <div class="modal fade" id="modalEdit" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <h3 class="text-center">Edit form</h3> <form method="POST" action="{% url 'edit' object.pk %}">{% csrf_token %} {% render_field edit_form.title class="form-control" %} <button type="submit" class="btn btn-bold btn-primary">Save</button> </form> </div> </div> </div> </div> In this case, and if I want to show context element info too, I can't see it into bootstrap modal. How can I pass x.pk into modal to edit it or see information like x.title? -
Django keeps adding ' character to first cell of my data so it can't store it in the model
I'm going nuts. Whatever I do, Django adds a ' character to the start of the first field of my data. I have a df that looks like so: Year JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV \ 0 1910 6.1 7.2 8.9 9.6 14.5 17.1 17.3 16.9 15.6 12.5 6.9 1 1911 5.8 6.5 7.5 9.7 16.2 17.8 21.7 21.4 17.3 12.4 8.2 2 1912 6.0 7.5 9.1 12.5 14.4 16.0 18.4 15.0 13.7 11.6 8.4 3 1913 6.7 7.2 8.5 10.4 13.8 16.5 17.6 18.5 16.5 13.5 10.6 4 1914 5.6 8.7 8.4 13.2 13.8 17.6 18.5 19.1 17.0 12.9 9.1 5 1915 5.9 6.4 7.7 10.8 15.1 18.0 16.9 17.7 17.0 11.9 6.0 6 1916 9.2 5.7 5.5 11.1 14.1 14.5 18.3 19.2 16.0 12.9 8.8 7 1917 2.7 3.8 6.1 8.4 16.3 17.5 19.3 17.1 16.2 10.7 9.9 8 1918 6.4 8.4 8.7 10.1 16.2 16.6 18.4 18.3 14.3 11.5 8.5 ... I have a function that puts it into a model: def add_to_db(weatherstats_df): print(weatherstats_df) for row in weatherstats_df.itertuples(): # print(row) year = int(str(row.Year).strip('\'')) print(year) measurement = row.Measurement location = row.Location ikey = 0 for key, month_or_season in WeatherStatistics.MONTH_OR_SEASON: ikey += 1 … -
self excluding excecution of functions in django
i have a django model that has values stored in a json field. but some of the values have to be unique, for that i have a function check_unique(). but this check fails if two users try to save the same value at the same time since when check_unique() runs neither of the values is stored in the database and then they are individually correct. There is a way to avoid this behavior? i tried avoiding this using trheadeing.Lock but apache runs in different processes and it does'nt work in that case. Besides, i would like that the check would be at application level (in python) and not at database level. the code looks like this: semaphore.claim() try: uniques = check_unique(self.answers) if not uniques: self.go_save() semaphore.release() return Response("All OK") except Exception as e: semaphore.release() return e -
Linking outer html page to the reverse_lazy() of signup page
I have written code to develop a social media clone site using django. In that, after signup, i have to move to homepage instead of login page. The homepage html code is present in another folder outside of this current folder. I am unable to access the url of the html page from this. The code is: from django.contrib.auth import login, logout from django.core.urlresolvers import reverse_lazy from django.views.generic import CreateView from . import forms class SignUp(CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy("login") template_name = "accounts/signup.html" Instead of "login", the url should be "base". The path of "login.html" is: "project/accounts/templates/accounts/login.html". And the path of "base.html" is: "project/templates/project/base.html". Please suggest me a method to modify this. -
install python package on heroku without pypi support
I am trying install a Django app on Heroku. My app needs pyke3. The recommended way for installing pyke3 is to download pyke3-1.1.1.zip https://sourceforge.net/projects/pyke/files/pyke/1.1.1/ and then install (into a virtualenv if desired) using the instructions on http://pyke.sourceforge.net/about_pyke/installing_pyke.html. How do I install pyke3 on heroku? Is there a way to add this to the requirements.txt, and how will heroku know where to get the pyke3 zip file? -
Making a dynamically generated list mutually exclusive
I have an unordered list that appears as part of an autocomplete dropdown and that is being dynamically generated, by a plugin, that only appears in the DOM after a user interaction. On the page in question, this list can be rendered multiple times. I want to make the list mutually exclusive so that when one item is selected, it can no longer be selected in a new list. The main problem I am having is that I am struggling to get access to the element that I actually need to perform the event on. The code that is generated for the list is like so: <span class="select2-container select2-container--default select2-container--open" style="position: absolute; top: 310px; left: 523.172px;"> <span class="select2-dropdown select2-dropdown--below" dir="ltr" style="width: 144px;"> <span class="select2-search select2-search--dropdown"> <input class="select2-search__field" type="search" tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" role="textbox"> </span> <span class="select2-results"> <ul class="select2-results__options" role="tree" id="select2-id_eventconfigstepkeycharacteristicfield_set-0-key_characteristic-results" aria-expanded="true" aria-hidden="false"> <li class="select2-results__option" role="treeitem" aria-selected="true">Depot</li> <li class="select2-results__option select2-results__option--highlighted" role="treeitem" aria-selected="false">Month</li> <li class="select2-results__option" role="treeitem" aria-selected="false">bdfdf</li> </ul> </span> </span> </span> I basically want to make so that when a li has select2-results__option--highlighted in its class it will be removed from the list when it is rendered again. So far I can get access to this by adding a jQuery event … -
Slow Django Model Formset Rendering
I have a Django Model Formset that is rendered with a crispy-forms in a custom table inline formset template. The formset is a list of alerts with entities, logic, and comments. Entity and logic are populated in each form, and the user writes a comment prior to submitting the form. The formset currently has 140 forms (i.e. 140 records in the Alert model), and it will need to handle more than that number. It takes 2 minutes for alerts.html to render. I can use Django-based pagination to limit the queryset and reduce rendering time, but this precludes me from using something like jQuery datatables to paginate and quickly add JS functionality. I used django-debug-toolbar to review. The queries are definitely funky and duplicated per form (i.e. the query grabbing entity information is duplicated for each form and also includes duplicate where statements). However, it only takes 3-4 seconds for the queries to run, so the problem must be elsewhere. I used Chrom dev tools to record the performance, but I didn't see anything helpful. Why is the render taking so long? Is there anything in my code below that could be optimized? I know caching is an option, but I … -
save unknown number of images in django
a post may have no image or may have 10 images in the request so i dont know how to save them and here is my models models.py class Post(models.Model): owner = models.ForeignKey(User) birthday = models.DateTimeField() class PostImages(models.Model): owner = ForeignKey(Post) image = ImageField() im going to save all of the images that are uploaded in POST.FILES so i tried: for file in POST.FILES: PostImages.objects.create(owner=post, image=file) but file gives me a string and when i save it it have no filename extension i mean i cant use the file anymore because it has no type.i would like to use formsets but i don't know how to use it in this case or maybe i can't, i have no idea. -
How to create a user and its corresponding profile object in django shell
I have a Profile model which has OneToOneField to User model(django.contrib.auth.models).I have a custom Signup form in which apart from default user fields, I use 2 other custom fields(type and organisation).I use post_save signal to automatically create or update the profile for the user instance that is being saved. All this works completely fine in admin and through a view.But when I try to create a user through django shell using User.objects.create_user(username='..',password='..'), I get an Integrity Error which is because of the 2 custom fields being non-nullable.How can I create the user in django shell. forms.py class UserRegistrationForm(forms.ModelForm): password = forms.CharField(label='Password',widget=forms.PasswordInput) password2 = forms.CharField(label='Repeat Password', widget=forms.PasswordInput) class Meta: model = User fields = ('username','first_name','last_name','email') def clean_password2(self): cd = self.cleaned_data if cd['password'] != cd['password2']: raise forms.ValidationError('Passwords don\'t match.') return cd['password2'] class SignUpForm(UserRegistrationForm): organisation = forms.ModelChoiceField(label='Your Organisation',queryset=Organisation.objects.all()) type = forms.ChoiceField(label='You are a ', choices=TYPE_CHOICES) class Meta: model = User fields = ('username','first_name','last_name','email','institute','category','password','password2') def save(self, commit=True): user = super(SignUpForm, self).save(commit=False) # add attribute to user model for access in signal user._type = self.cleaned_data['type'] user._organisation = self.cleaned_data['organisation'] if commit: user.save() return user -
Auto Populate Field if PK/FK exists in another model
I'm really struggling with this issue. As a newbie if my logic or thought process is incorrect please help direct me. I'm attempting to auto populate a field in my custom user model with a 1 or a 0 if the formattedusername exists in another model/pre-existing database table with the following signal, but i can't seem to get it to work correctly: @isthisflag def is_this(self, is_this): if cfo.ntname is user.formattedusername: return 1 else: return 0 I have a custom User model like the following: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=7, unique=True) formattedusername = models.CharField(max_length=11, unique=True, primary_key = True) is_this = models.BooleanField(default=False) USERNAME_FIELD = 'username' I then have another model we'll call cfo that has a list of formattedusernames with the ntname field as a FK to formattedusernames. class cfo(models.Model): ntname = models.OneToOneField(settings.AUTH_USER_MODEL,db_column='CFO_NTName',primary_key=True, serialize=False, max_length=11) class Meta: managed = False db_table = 'cfo' If ntname exists as the User who logs with their LDAP authentication I want to place a 1 in the User.is_this field. -
Django - concatenate form fields before validation
There is a Person model in models.py: class Person(models.Model): ... tel = PhoneNumberField(blank=True, default='') ... Where phone is of type PhoneNumberField Now, in my forms I have something like this: class PersonForm(forms.ModelForm): # Some code... class Meta: model = Person fields = [..., 'phone',...] phoneprefix = ChoiceField(choices=phone_prefixes) Where phone_prefixes is list that maps, well, phone prefixes so user can choose from dropdown list phone code for his desired country, for example +44 for UK. What I want to achieve is to make Django concatenate value of phoneprefix to phone in form, and then run any validation to check if phone number is possible/valid. django-phonenumber-field library has some nice functions for validation, but I want them to be run on +44 1632 960741, not just 1632 960741. How can I do that? -
How to install xhtml2pdf in Cloud9 using python 2.7?
I have tried to install xhtml2pdf for render pdf from html.I have followed the instructions bellow. Installation For python2.7: pip install xhtml2pdf To obtain the latest experimental version that has Python 3 support, please use a prerelease: pip install --pre xhtml2pdf but in this process , C9 shows me this error. How can I solve this problem? Thanks -
Django save blank value
I have a number of unknown values in a df, where the cells are filled with the chars '---' I would like to tell Django that, if it finds something that is not a number of any kind (int / decimal / floating point) to leave the value of that field blank. I also want the default to be blank, but it does not seem to allow this either. My model looks like this: value = models.FloatField( # default=blank, null=True, validators=[MinValueValidator(0)], ) My view calls a function like this: if (value == "---"): value = None MyModel( value=value, ).save() My form looks like this: from django import forms from .models import WeatherStatistics class WeatherStatisticsForm(forms.ModelForm): class Meta: model = WeatherStatistics fields = [ "value", ] How can I post a blank value to the db? -
Where to store user's media
I have a web-service google cloud. It consists of: load balancer; group of instances (django code); sql service; But I don't know where to store user's files. Should I use separate media server, or google cloud storage? How do you usually solve such problems? -
How to get the average of every 5 minutes from database in django?
I have a django project where i created a template that shows the result of a database. models.py: ... class Transdutor(models.Model): data_instalacao = models.DateTimeField('Data instalacao') numero_serie = models.CharField(max_length=255) chave_api = models.CharField(max_length=25, default='', blank=False) #T TODO: precisamos verificar se KEY cadastrado existe em algum equipamento id_cliente = models.ForeignKey(User, on_delete=models.CASCADE) id_classificacao = models.ForeignKey(Classificacao, on_delete=models.CASCADE) parametro_a = models.CharField(max_length=255) parametro_b = models.CharField(max_length=255) hora_ponto_inicio = models.TimeField('Hora inicio') hora_ponto_fim = models.TimeField('Hora fim') nome_io6 = models.CharField(max_length=255) nome_io7 = models.CharField(max_length=255, blank=True) nome_io8 = models.CharField(max_length=255, blank=True) nome_io9 = models.CharField(max_length=255, blank=True) nome_io10 = models.CharField(max_length=255, blank=True) nome_io11 = models.CharField(max_length=255, blank=True) nome_io12 = models.CharField(max_length=255, blank=True) def __str__(self): return (self.numero_serie) class Coleta(models.Model): data_leitura = models.DateTimeField(null=True) # TODO: MUdar isso depois io6 = models.CharField(max_length=255, null=True) io7 = models.CharField(max_length=255, null=True) io8 = models.CharField(max_length=255, null=True) io9 = models.CharField(max_length=255, null=True) io10 = models.CharField(max_length=255, null=True) io11 = models.CharField(max_length=255, null=True) io12 = models.CharField(max_length=255, null=True) id_transdutor = models.ForeignKey(Transdutor, on_delete=models.CASCADE) ... Views.py: def printa(request): teste = Coleta.objects.all().order_by('-id') transdutores = Transdutor.objects.filter(chave_api="hab0001") #io6_name = Transdutor.objects.values_list('nome_io6', flat=True).filter(chave_api="hab0001") parametros = Transdutor.objects.all().filter(chave_api="hab0001").order_by('-id') parametro_a = Transdutor.objects.values_list('parametro_a', flat=True).filter(chave_api="hab0001").order_by('-id')[0] parametro_b = Transdutor.objects.values_list('parametro_b', flat=True).filter(chave_api="hab0001").order_by('-id')[0] parametro_a_float = float(parametro_a.replace(',','.')) parametro_b_float = float(parametro_b.replace(',','.')) # io6 = Coleta.objects.values_list('io6', flat=True).filter(id_transdutor=1).order_by('-id')[:10] data = Coleta.objects.values_list('data_leitura', flat=True).filter(id_transdutor=1).order_by('-id')[:10] context = { 'transdutores': transdutores, 'parametro_a_float': parametro_a_float, 'parametro_b_float': parametro_b_float, 'teste': teste, #'io6_name': io6_name, 'data': data, } return render(request, 'dashboard/print.html', context) template … -
Django suppress form errors
If I have a bound form in Django 1.12, can I suppress the errors? def index(request): myform = MyForm(request.POST) myform.errors = None # <-- this doesn't work, "can't set attribute" I do not want to suppress the errors in the template, only in the view. Is this possible? -
FIle handling and delivery in a Django ELastic Load Balancer deployment
So I have a Django app deployed in AWS Elastic Beanstalk that generates a web page and collects user data for various tables when the user loads the page, clicks a link, etc. All this data is currently recorded on an RDS database. At periodic intervals, the data for the day is collected (potentially several million rows) and stored in a series of CSV files. The data is then sent to an FTP server to be analysed later. There are also cleaning operations ran to delete data a few days old from the database as well. I'm thinking that I can potentially remove some overhead and complexity from the project by removing the DB aspect altogether. I shall instead write out the data to files located on the instance, gzip them and send the file over. A few potential issues occur to me though: If my load balancer scales up to more than one instance (currently just one), how can I make sure that each instance receives a command at X hour in the day to get the current file, zip it and send to the FTP? How can I uniquely identify which instance the file came from? They have … -
Unable to install pycrypto on ubuntu 14.04 with python3
I'm trying to install stream package with pip install stream_django which has pycrypto dependency. So while installing pycrypto dependecy it returns me RuntimeError: autoconf error error. How can i install pycrypto on ubuntu 14.04 with python3 -
Django thread don't read valor updated
In my models.py I hace a class how control the thread life: class Repartidor(models.Model): thread_active = models.BooleanField(default=False) def launch_thread(self): self.thread_active = True self.save() def kill_thread(self): self.thread_active = False self.save() def get_thread_state(self): if self.thread_active: return True else: return False In repartidor.py I declare the thread: class RepartidorThread(threading.Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None): super(RepartidorThread, self).__init__() self.target = target self.name = name def run(self): repartidor = Repartidor.objects.get(pk=1) while True: condition = repartidor.get_thread_state() print(condition) if condition: do_something() time.sleep(1) else: pass time.sleep(1) And launch the thread in wsgi.py from printers.repartidor import RepartidorThread thread_repartidor = RepartidorThread(name='Thread_Repartidor') thread_repartidor.start() But I have a problem, I read the condition in repartidor.py with get_thread_state() and it return True or False. If I change the condition through the django_admin or through my frontend, the value of the database is updated, and all my project read the new valor, except the thread, which always reads the first one. If I stop and start the server, the thread read the new valor. Why is this happening? -
Django wagtail 1.9 API V2
I am new to Wagtail and i have managed to follow the documents here and here. I am able to get page information, however how do i return images (their path)? All the solutions online seem to be amended for V1. { id: 46, meta: { type: "wagtailimages.Image", detail_url: "http://192.168.0.38:8002/api/v2/images/46/", tags: [ ] }, title: "a", width: 409, height: 307 } How do i get the URL? -
are django model queries cached?
Let's say I have a model_a that has foreign key to model_b and I am accessing model_b's properties like so: model_a = ModelA.objects.get(id=id) x = model_a.model_b.x y = model_a.model_b.y z = model_a.model_b.z Is Django going to the DB and joining the tables to get x, y, and z fields on each line? Or does Django store the result of the first join and then no more joins are needed? Is this in any way, performance-wise? model_b = model_a.model_b # only one join x = model_b.x y = model_b.y z = model_b.z Just curious -
Django blog post view
What is the best to create class based post view with post details, comments, comment form? I tried somethink like that: class PostView(DetailView, FormView): ... and in the post method if required.post is form, I create comment in the view. What you think about? Do you have any examples blog post + comment form in one view in class based views? -
[Django]: How can i read next entry from MySql upon clicking a button from HTML form.
I am new to Django as well as HTML, I have 5 entries in database (MySql) x.objects.all returns all in one go but as per requirement i want to read each row upon clicking of a button from HTML form. Tried x.object.get(pk=var) by changing var on each click but somehow not able to do it. Any pointer will be helpful here, thanks in advance. Madhur -
filter using a many to many (through) field django model
I have this definitions into models.py: class Group(models.Model): created = models.DateTimeField(auto_now_add=True) products = models.ManyToManyField(Product, through='ProdGroup') class ProdGroup(models.Model): groups= models.ForeignKey(Group, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) is_prd_main = models.BooleanField(default=False) class Product(models.Model): id = models.CharField(primary_key=True, default='', max_length=12) I want to check if I already have a Group with the same products in the database. (and also check if the prd_main is the same). I don't know if it's a problem with the through option but this doesn't work: group = Group.objects.all()[0] # an instance already in the db Group.objects.filter(products__exact=group.products) <QuerySet []> it's there a way, given an object group to check of its already in the db?, it's there a way to obtain all the products and filter all the Groups with the same unique set of products?