Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django how to go about using npm modules with static/ templates
I have recently added npm to my project in order to keep better track of my js dependencies. Previously I have just been git cloning to my static/vendor folder. I've also added gulp , but have only got it doing hello world things right now. It seems simple enough - it can watch files, minify assets, compile Sass. Eventually I will probably switch to Webpack, but gulp is simple and working for now. I don't want to use django-compressor or django-pipeline. So let's say I run npm install vis to pull in visjs. It gets added to node_modules and a record is added to package.json dependencies. A) Do I reference vis/dist right where it is in node_mods in my template scripts? <script src="/node_modules/vis/dist/min-vis.js' %}"></script> # right now it's <script src="{% static 'vendor/min-vis.js' %}"></script B) Should gulp be listening for changes to package.json dependencies and replicating vis/dist to static/vendor or static/js when it sees changes there? I keep seeing people talking about handling STATICFILE_DIRS when they talk about npm and gulp. Right now mine is just set to the following. Will this change? STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) -
How to stop my pandas data table from splitting in two?
Current Output My dataframe keeps splitting into two, delimited by the '/' symbol. I then tried printing just the top row "top = out.ix[:1, :17]" but the splitting still occurs. top row Full code: import string from os import path import pandas as pd pd.set_option('display.max_columns', None) #prevents trailing elipses pd.set_option('display.max_rows', None) import os.path BASE = os.path.dirname(os.path.abspath(__file__)) file1 = open(os.path.join(BASE, "samp.txt")) sampInput=file1.read().replace('\n', '') file2 = open(os.path.join(BASE, "ref.txt")) refInput=file2.read().replace('\n', '') sampArray = [word.strip(string.punctuation) for word in sampInput.split()] refArray = [word.strip(string.punctuation) for word in refInput.split()] out=pd.DataFrame(index=sampArray,columns=refArray) for i in range(0, out.shape[0]): #from 0 to total number of rows for word in refArray: #for each word in the samplearray df1 = out.iloc[0, 0:16].copy() top = out.ix[:1, :17] out.ix[i,str(word)] = out.index[i].count(str(word)) #print(out) print(top) #print(df1) -
Elasticsearch bulk operation failing for large dataset
I want to insert my database details into elasticsearch db.The problem is that my table contain a large number of records (15537) and i am not able to insert and it appears to be very slow.The code i used is given below>i am using bulk api of elasticsearch bulk(client=es, actions=(b.indexing() for b in City.objects.using('qoe').all().iterator())) -
Storing a function call in a Django model
Currently I am storing a series of objects as a dictionary of dictionaries, and within this I store calls to functions defined outside of the dictionary. These functions are specific to the objects, and cannot be generalised. In the dictionary I can refer to the function directly eg: 'some_property': function_name, and when I call that later on dictionary['some_property'](arg_1, arg_2)and the function gets called. I am looking migrate this dictionary of dictionaries to a django model, but I cannot see how I can replicate this functionality from a model. What I currently have: dictionaries.py def year_camel_month(filename, **kwargs): month = kwargs['month'].title() return filename.format(str(kwargs['year']), month) def year_month(filename, **kwargs): month = kwargs['month'] return filename.format(str(kwargs['year']), month.lower()) data_source_families = { 'dataset_1': { 'source_url': 'https://example.org/url/subfolder', 'slug': 'slug_that_changes_predictably_over_time{}-{}', 'slug_treatment': year_camel_month }, 'dataset_2': { 'source_url': 'https://example2.org/url/subfolder', 'slug': 'slug_that_changes_predictably_over_time{}-{}', 'slug_treatment': year_month }, } Which then gets called when combined with a user-defined time frame later on: get_data.py from .dictionaries import data_source_families slug = data_source_families[selected_dataset]['slug'] processed_slug = data_source_families[selected_dataset]['slug_treatment'](slug, some_kwargs) url = data_source_families[selected_dataset]['source_url'] + processed_slug And this is working fine. I am looking to develop functionality to improve consistency (and make these data available to another programme) by creating a django model that replicates this, something like this: models.py def year_camel_month(filename, **kwargs): … -
How To Edit ManyToManyField In Django Admin list Display Page?
I want to add Many2Many fields editable in Django admin list_display page. The model structure as below, class Genre(models.Model): name = models.CharField(max_length=250, unique=True) class Movie(models.Model): name = models.CharField(max_length=250) genre = models.ManyToManyField(Genre) And I tried as, class MovieAdmin(admin.ModelAdmin): list_display = ['name', 'genre'] list_editable = ['genre'] Above is troughs an error. -
django : unable to call a python function by clicking submit button
Trying to call Installation function when we click a submit button on HTML Page and taking the data from HTML only,i am new to django. Help me out..! Views File: from .forms import Details from django import forms from django.shortcuts import render from django.http import HttpResponseRedirect from . import installation def output(request): if request.method == 'POST': details=Details(request.POST) if details.is_valid(): Obj=details.cleaned_data path=Obj['Path'] device_type=Obj['Device'] image_version=Obj['Version'] return installation() else: raise TypeError App/urls.py File: from django.conf.urls import url from django.contrib import admin from . import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'',views.output,{'template_name':'home_page.html'}), ] Forms.py File : from django import forms class Details(forms.Form): Device=forms.CharField(required=True, label='Device_Type', max_length=32) Path=forms.FileField(required=True, label='Path_to_install_build') Version=forms.CharField(required=True, label='Version_type',max_length=32) -
Catch the form and the formsets erors in one statement/conditions
I have a form in the form I have multiple inline formsets. I want to catch the form and formsets errors in one statement/condition so I can let the user a message at top to check for errors: 'You have errors see the marked fields bellow" I tried: {% if form.errors or form.non_field_errors %} but it doesn't catch formsets errors. I know I can get the formset errors: formset.errors and/or loop thru form in formsets for errors, but I want the message at the top of the form, plus something that I can use generic, indifferent of the the names of the formsets. -
how can i be gain reputation when automatically see a post on a net site
How do I earn reputation? The primary way to gain reputation is by posting good questions and useful answers. Votes on these posts cause you to gain (or sometimes lose) reputation. Please note that votes for posts marked “community wiki” do not generate any reputation. You gain reputation when: question is voted up: +5 answer is voted up: +10 answer is marked “accepted”: +15 (+2 to acceptor) suggested edit is accepted: +2 (up to +1000 total per user) bounty awarded to your answer: + full bounty amount one of your answers is awarded a bounty automatically: + half of the bounty amount (see more details about how bounties work) site association bonus: +100 on each site (awarded a maximum of one time per site) You can earn a maximum of 200 reputation per day from the combination of upvotes, downvotes and suggested edits. But Bounty awards, accepted answers, and association bonuses are not subject to this daily reputation limit. If you are an experienced Stack Exchange network user with 200 or more reputation on at least one site, you will receive a starting +100 reputation bonus to get you past basic new user restrictions. This will happen automatically on all … -
Change form/formset error messages
How can I change the 'error' messages that I get when using a formset. For example: 'Please submit 1 or more forms.' -
Why my Records in Overriding,i want to store in column format
when i try that logic it show only last record of my file means all records are overriding in django. with open('persons.csv', 'wb') as csvfile: filewriter = csv.writer(csvfile, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL) filewriter.writerow(['Name', name],) filewriter.writerow(['emailAddress', emailAddress]) filewriter.writerow(['password', NewcheckPassword]) -
How to reload some constants defined in settings.py(Django) after every time period?
I have a trained model which is stored in redis(cache). For minimising response time I am loading it in settings.py while server is started. Model is changing(training) after every 2 hours so I need to re-fetch that in constant. MODEL = pickle.loads(redis_connection.get('model')) How to get this constant updated basically re-fetch the model from redis while settings.py remains unaltered? -
Rendering Foreign Key Elements from Django Rest Framework
I have the standard django polls models class Poll(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.question_text class Choice(models.Model): poll = models.ForeignKey(Poll, null=True, blank=True) choice_text = models.CharField(max_length=200) vote_count = models.IntegerField(default=0) In the serialisers I have added a reference to foreign key as follows : class PollSerializer(serializers.ModelSerializer): choices = ChoiceSerializer(many=True, read_only=True, required=False) class Meta: model = Poll fields = ('id', 'question_text', 'pub_date', 'choices') I have created the choices specific to the questions by the django admin. In the poll list from django rest framework, I expect to see the list of choices associated with the poll. It only shows the Poll objects as follows. Can someone guide me, as to what has gone missing, and how can I see the choices associated with the Poll? -
django templates : table with a formset and a query set
So I work on a projet where I have to insert in a template a table with fields from a formset and fields from a queryset. So I have coded this view : def test (request): testFormSet = modelformset_factory(Scelle,fields=('dateRapport',)) L = Scelle.objects.values_list('numOrdre', flat=True).order_by('numOrdre') i = L[0] if request.method == 'POST': formset = testFormSet(request.POST) if formset.is_valid(): formset.save() else: formset = testFormSet() return render(request, 'AffichageScelles/test.html', locals()) As you can see, the formset is based on the model which I want to use in the template I also have this templates : <form method="post"> {{ crsf_token }} {{ formset.management_form }} <table> <tr> <th>Date Rapport</th> </tr> {% for form in formset %} <tr> {% for field in form %} <td> {{ field }}</td> {% endfor %} {% for value in L %} <td> {{ L.value}}</td> {% endfor %} </tr> {% endfor %} </table> <input type="submit" value="Rechercher" /> </form> But this doesn't work because for each form in formset I have all the L values. Does someone know how to combine both loops ? -
Django generating the form tags instead of hardcoding them
I am having issues with having to hardcode the tags into the templates in Django. The reason I have issues is that I need to have the forms generated dynamically based on a framework I am working on. That framework (written in Python) has a webinterface (hence Django) that requires forms for each module in the framework, depending on the data that needs to be submitted to that module. So I am trying to get the form information (which fields, type of fields, labels etc.) from the module, which I currently am trying like so: #framework/module.py def form(): forms = '"upload": {"filename": "file","directory": "text"}' return forms The reason it is constructed like that, at this moment, is because I try to pass this information to the forms.py from Django so it can then be translated into what Django needs to create the output for the template. Now I have tried a couple of ways on how to get it onto the template. The only problem is, that I have to create the form tags hardcoded into the template. I am trying to figure out how to get the form tags also generated dynamically based on the information supplied by the … -
Apache with SSL configuration not working with WSGI configuration for Django app
This is a follow-up on the following issues on github : https://github.com/certbot/certbot/issues/1820 and https://github.com/certbot/certbot/issues/2546 Letsencrypt cannot deal with apache's WSGI configuration I am running apache2 with the following config <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost # DocumentRoot /var/www/html ServerName mywebsitedomain.com ServerAlias www.mywebsitedomain.com DocumentRoot /var/www/html/mywebsitedomain-com Alias /static/ /home/ubuntu/Sites/mywebsitedomain-com/myproductionfolder/static/ <Directory /home/ubuntu/Sites/mywebsitedomain-com/myproductionfolder/static> Require all granted </Directory> # adjust the following line to match your Python path <Directory "/home/ubuntu/Sites/mywebsitedomain-com/myproductionfolder"> <Files wsgi.py> AllowOverride all Options FollowSymLinks Require all granted </Files> </Directory> WSGIDaemonProcess mywebsitedomain.com processes=2 threads=15 display-name=%{GROUP} user=www-data group=www-data python-path=/home/ubuntu/Sites/mywebsitedomain-com:/home/ubuntu/Sites/mywebsitedomain-com/venv/lib/python3.5/site-packages WSGIProcessGroup mywebsitedomain.com WSGIScriptAlias / /home/ubuntu/Sites/mywebsitedomain-com/myproductionfolder/wsgi.py process-group=mywebsitedomain.com application-group=%{GLOBAL} Alias /phpmyadmin /var/www/html/phpmyadmin <Location /phpmyadmin> </Location> # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # … -
getting a job as back end developer [on hold]
Hi I've been learning python and django for a few months now ,but when I looked for jobs I couldn't find anything for beginners .Do you think is possible to get a job as a beginner?same way front end developpers have junior front end developer -
can someone help me to understand this function in django source code (db.backends.base)
def autoinc_sql(self, table, column): """ Return any SQL needed to support auto-incrementing primary keys, or None if no SQL is necessary. This SQL is executed when a table is created. """ return None I don't know what this function is for,can someone explain it for me ? thanks -
How to implement a cart system in django
I'm stuck on the logic of implementing a cart system for my Application. I have tried using Sessions but I can't seem to make it work. Please any answer would be well appreciated. Thanks -
Adding a next/previous button in blog posts
On my page all the blog posts will be showing up. So I wanted to implement a next/previous button to better my page. def PostLists(request): num = request.session.get('num',-5) request.session['num'] = num num = num + 5 exp = Post.objects.order_by('-date').all()[num:(num+5)] context = { 'object_list': exp } if (request.user.is_authenticated): return render(request, 'dashboard/postlist.html', context=context) else: return redirect('login') I added a next button in my html code which will redirect me to my the same views.py function as shown above and the variable(num) shall increment by 5 thus showing me my next 5 posts. However this seems not to be working as I see the same 5 posts always. Is there a better way to implement a next/previous button? If so could you please specify that? Thanks a lot! -
Django admin: How to make a button to behave as an action?
I've added a custom button to the admin change_list template for one of my models. How can I make this button to perform and action operation on the selected rows? -
How to send additional data using mailgun in python?
I want to create a new ticket object in my django project backend whenever I get reply to my email address. To do that I've created route in my mailgun account. But I have to embed some hidden data in that mail so that I can process. The Mailgun Documentation says API: Pass the following parameter, “v:my-custom-data” => “{“my_message_id”: 123}”. However it is unclear where to set the variables (header, body) and exactly how to write them in code. -
How does reverse method build URL?
I am new to Django,learning frorm Django by Example book This is the get_absolute_url method from Post class def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) I am looking at source code reverse def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None): if urlconf is None: urlconf = get_urlconf() resolver = get_resolver(urlconf) args = args or [] kwargs = kwargs or {} Arguments part is clear to me. But how will the urlconf be resolved? -
How to style my python code correctly on Django webpage?
My Python code reads in two strings, removes the punctuation and then compares the words in them within a matrix table which it prints to the console. ORIGINAL PYTHON OUTPUT I've managed now to get it to display on a django webpage, but it is printing all the values as a single string. How do I style it correctly? DJANGO WEBPAGE OUTPUT My eventual goal is to have two text areas that allow you to either: enter text manually or upload two .txt files. Then I want to compare them utilising this code. function checkSimilarity(){ var str1 = document.getElementById("sampInput").value; var str2 = document.getElementById("refInput").value; document.getElementById("output").innerHTML = similarity(str1, str2); } function similarity(s1, s2) { var longer = s1; var shorter = s2; if (s1.length < s2.length) { longer = s2; shorter = s1; } var longerLength = longer.length; if (longerLength == 0) { return 1.0; } var result = (longerLength - editDistance(longer, shorter)) / parseFloat(longerLength); var percentage = result * 100; return (percentage.toFixed(2) + "%"); } function editDistance(s1, s2) { s1 = s1.toLowerCase(); s2 = s2.toLowerCase(); var costs = []; for (var i = 0; i <= s1.length; i++) { var lastValue = i; for (var j = 0; j <= s2.length; … -
List in QueryDict retrieved as string
I re-construct my code as minimal as: <form action="#" method="post"> {% csrf_token %} <input type="text" name="title"> <textarea name="content" id="" cols="30" rows="10"></textarea> <input type="text" name="tags"> <input type="submit"> </form> I print the POST data from views.py print(self.request.POST) print(self.request.POST["title"]) print(self.request.POST["content"]) print(self.request.POST["tags"]) print(type(self.request.POST["tags"])) Come by with <QueryDict: {'csrfmiddlewaretoken': ['r4QIefk3YNSU0EivHwq8dwmHUNPFK4WwcvJyt5FK6gAQUdTl6IJ2m8V1Z71OZ1kU'], 'title': ['list'], 'content': ['display'], 'tags': ['as,string']}> list but as,string <class 'str'> Within QueryDict, they are lists of ['list'] ['display'] ['as,string'] but is retrieved as string. What's happening here? -
django iot multi topics
At me the project is implemented on Django. There is a task to listen simultaneously to several topics that clients write using iot technology. Is there any possibility in Django to subscribe to all topics at once and listen to messages from these topics? Thanks.