Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Passing Custom Form Parameters to modelfactory
I have a Django ModelForm like this: class ContactPhoneForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ContactPhoneForm, self).__init__(*args, **kwargs) #.... ...and a view where I try to get a respective formset: ContactPhoneFormSet = modelformset_factory(ContactPhone, ContactPhoneForm, extra=1, can_delete = True) Now, I want an additional parameter to be passed to the __init__method of the form: class ContactPhoneForm(forms.ModelForm): def __init__(self, contact_id, *args, **kwargs): self.contact_id = contact_id super(ContactPhoneForm, self).__init__(*args, **kwargs) #.... I tried to the rewrite my view according to this post: ContactPhoneFormSet = modelformset_factory(ContactPhone, wraps(ContactPhoneForm)(partial(ContactPhoneForm, contact_id=contact_id)), extra=1, can_delete = True) but I end up with TypeError: the first argument must be callable error. Any help on this? -
Scheduler in django python, Server does not start
I am trying to make a scheduler in django, using packages like sched and apsscheduler in both of the the program goes into an infinite loop as per their documentations, so the server does not get started, if I remove the loop the scheduler doesn't work, I am providing a sample code please help: import schedule import time def job(): print("I'm working...") schedule.every(10).minutes.do(job) schedule.every().hour.do(job) schedule.every().day.at("10:30").do(job) schedule.every().monday.do(job) schedule.every().wednesday.at("13:15").do(job) while True: schedule.run_pending() time.sleep(1) I have read many question on stack overflow but couldn't find any apt solution to it, please help. -
# linking across two sibling pages doesn't scroll to the right part
I'm developing a page using Bootstrap and Django. I have two pages: Pets and Cats. Both are in the nav bar. Pets have several sections, including Cats. When I click on Cats in the navbar, I want it to load the Pets page and scroll down to the Cats section. My Pets page has the following code: <div class="section" id="cats"> <div class=" centred auto"> <h1 class="h1"> Cats </h1> <p>Here you can find pictures of cats </p> </div> </div> Cats part of the navbar has the following code: <li class="active"> <a class="dropdown-item" href="{% url 'pets' %}#cats">CATS</a> </li> Now, when I'm on the Pets page and click Cats in the navbar, it scrolls down to Cats. When I'm any other page on my website, click Cats in the navbar, it takes me to the Pets page, but does not scroll down. I'm running a test server and I have tried this on Chromium, Chrome, and Firefox. Any idea why / how to fix this? -
Django. Manipulate the same object from many requests at the same time
I am wondering what kind of approach I should use to be able to manipulate the same model instance at the same time from multiple requests -
Putting the mysql statement in django python shell
guys. I hope that someone of you can help me in that problem. How can I express this MySQL statement: SELECT AES_DECRYPT(column, (SELECT AES_DECRYPT(column2, 'aeskey') FROM table2)) FROM table WHERE id=1; in django python shell (you know, with interactive shell)? Thank you, have a good day. -
Django CMS get_previous_sibling not working
I'm using Django CMS and wonder of anyone has come up with this problem too. My get_next_sibling works but get_prev_sibling doesn't. I've also tried get_previous_sibling. Works: {{ request.current_page.get_next_sibling.get_page_title }} Doesn't work: {{ request.current_page.get_prev_sibling.get_page_title }} -
Pass one queryset as parameter for exclude() in django
I have the following three models: class Student(models.Model): name=models.CharField(max_length=10) class Task(models.Model): name=models.CharField(max_length=10) class StudentTask(models.Model): student=models.ForeignKey(Student) task=models.ForeignKey(Task) Now what I want is to show the list of tasks he is assigned to and the list of activities that he is not taking: my_tasks=StudentTask.objects.annotate(act_id=F('id'),act_name=F('task__name')).values('act_id','act_name').filter(student_id=id) tasks=Task.objects.exclude(id__in=my_tasks).values('id','name') Which gives the error "Cannot use multi-field values as a filter value.". I googled and realized annotate got something to do with the error (but i didnt yet try without it). Is it even worth trying to use my_tasks given any given student cant have more than three tasks? The following query works fine: tasks=Task.objects.exclude(id__in=StudentTask.objects.filter(student_id=id).values('task_id') But it is querying the same thing twice. What is the proper way to do this, considering the first query will fail as it is? -
Django Wagtail/Haystack Search with Heroku
I uploaded my project to heroku and I have a Search engine which works on local development and I would like to make it work in production as well. I used Wagtails Search since it was super easy to install and configure but it seems not to be a proper solution for production. This was my configuration: WAGTAILSEARCH_BACKENDS = { 'default': { 'BACKEND': 'wagtail.wagtailsearch.backends.elasticsearch5', 'URLS': [u'http://localhost:9200'], 'INDEX': 'wagtail', 'TIMEOUT': 5, 'OPTIONS': {}, 'INDEX_SETTINGS': {}, "ATOMIC_REBUILD":True } } Heroku can't connect to Port 9200 and when I stated to read into the the configurations it seemed to be easier to use Haystack/Solr. This Heroku Article suggests to use the add-on "SearchBox Elasticsearch" but I cannot add any addons at the moment. So my Questions are: Can I run the normal Haystack/Wagtail search without the Heroku add-on? How do I make the 9200 Port accessible for Heroku? Would it make sense to upgrade to Haystack? Is Wagtail scalable in production? anybody made any experience in production? Im quite happy with Wagtail since everything works as it should and I don't want to change something that does the job. Hope somebody can enlighten me. -
openstack-dashboard-ubuntu-theme Error while installing package
I'm trying implement elastic search in my Django application. For that i need to install open JDK-7 in my ubuntu 16.04 system. While installing i'm getting the following error. Reading package lists... Done Building dependency tree Reading state information... Done The following additional packages will be installed: libatk-wrapper-java libatk-wrapper-java-jni openjdk-7-jre Suggested packages: openjdk-7-demo openjdk-7-source visualvm icedtea-7-jre-jamvm sun-java6-fonts fonts-ipafont-gothic fonts-ipafont-mincho fonts-indic The following packages will be REMOVED: openstack-dashboard-ubuntu-theme The following NEW packages will be installed: libatk-wrapper-java libatk-wrapper-java-jni openjdk-7-jdk openjdk-7-jre openjdk-7-jre-headless 0 upgraded, 5 newly installed, 1 to remove and 28 not upgraded. 2 not fully installed or removed. Need to get 0 B/55.9 MB of archives. After this operation, 77.7 MB of additional disk space will be used. Do you want to continue? [Y/n] y (Reading database ... 515256 files and directories currently installed.) Removing openstack-dashboard-ubuntu-theme (2:9.1.0-0ubuntu1) ... Collecting and compressing static assets... Traceback (most recent call last): File "manage.py", line 25, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 302, in execute settings.INSTALLED_APPS File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 55, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) … -
Python tox and py.test: how to run just a single test rather than the whole test suite
I'm new to Django and testing so please bear with me. Trying to run on the terminal a new test for code I developed in a Django project, but unfortunatly I inherited several test failures (already confirmed that by analyzing commits prior to mine). I'm trying to run/fix just my test/code. Not fix all the failling tests (at least not right now). Today we run the tests by just running tox in the main project folder, and tox ends up calling py.test, with a different database (in development/production we use Postgresql, but for tests we use SQLite). Here is the tox.ini configuration [tox] envlist = unit skipsdist = True [testenv:unit] deps = -rrequirements/test.txt commands = bash -c 'TESTING_DB=db.sqlite3 python manage.py initdb --settings telessaude.settings.test' py.test -n 4 passenv = * setenv = DJANGO_SETTINGS_MODULE=telessaude.settings.test whitelist_externals = /bin/bash [flake8] max-line-length = 110 [pytest] setenv= DJANGO_SETTINGS_MODULE=telessaude.settings.test python_files = **/tests.py **/tests/*.py **/tests.py norecursedirs = requirements .tox media And here is my test, located at ~/project_name/servicos/tests.py # encoding: utf-8 from fluxos.tests import BaseFluxoTestCase from core.tests import BaseTestCase from servicos.models import Estomatologia class EstomatologiaTestCase(BaseTestCase): def testa_formata_campos(self): estomato = Estomatologia() return_value = estomato.formata_campos() self.assertEquals(return_value['comorbidades_paciente'], '') ... What should I do with either tox or py.test to run just … -
Trying to implement django smart selects with django mptt
I was trying do implement smart select with django mptt in the admin page by using the smart select widget. The problem is that the form field appears blank in all field selections and I can't figure out the problem. models.py (irrelevant fields hidden) class Estimate(models.Model): name = models.CharField(max_length=150) class EstimateCategory(MPTTModel): estimate = models.ForeignKey(Estimate, on_delete=models.CASCADE) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) This is how I'm trying to implement in the admin.py from smart_selects.widgets import JqueryMediaMixin, ChainedSelect class EstimateCategoryForm(forms.ModelForm): subject = forms.ChoiceField(widget=ChainedSelect('orcamento', 'EstimateCategory', 'estimate', 'estimate', 'orcamento', 'EstimateCategory', 'estimate', auto_choose = 'False', show_all = 'False' )) class Meta: model = EstimateCategory fields = ['estimate'] @admin.register(EstimateCategory) class EstimateCategoryAdmin(admin.ModelAdmin): form = EstimateCategoryForm -
Best tool for making website
I am making a website for the first time and have basic knowledge of HTML. I am confused of which tool should I use for making website? Django or D3 js or HTML+CSS+JQuery ? -
unsupported operand type(s) for /: ‘map’ and 'int’
##models.py from django.db import models from django.contrib.auth.models import User import numpy as np class Wine(models.Model): name=models.CharField(max_length=200) def average_rating(self): all_ratings = map(lambda x: x.rating, self.review_set.all()) return np.mean(all_ratings) def __unicode__(self): return self.name Why is this error showing?What is wrong at line 7? -
Display a message when the cursor is ON the button
<h1>JavaScript</h1> $(function(){ $('.select-another-button').each(function(){ $(this).bind('click', function(e){ $('.select-another-button').css('pointer-events', 'none'); $('#message').show() setTimeout(function(){ $('#message').hide() }, 300000); e.preventDefault(); fileBrowser(this); return false; }); }); }); HTML <a href="#" title="{% trans "Send email - rejected file(s)" %}" class="btn btn-icon select-another-button" data-url="{% url "messaging:send" request_id=object.pk %}"> <i class="material-icons">assignment_late</i> <div class='alert alert-success' id='message'> The message was sent to the client. Please wait 5 minutes before sending the message again. </div> </a> Django app_name = 'messaging' urlpatterns = [ ... url(r'^send/(?P<request_id>[0-9]+)/$', send, name='send'), ] and @staff_member_required @csrf_exempt def send(request, request_id=None): req= Request.objects.get(pk=request_id) request_folders = req.folder.all_files.all() context = [] for doc in request_folders: if doc.meta.state == u'rejected': context.append(doc) if context: ctx = {'request': req} EmailFromTemplate('document-refusal', extra_context=ctx)\ .send_to(req.customer.user) return HttpResponse('') The purpose of this code is to create a button which will send a email under specific conditions. My weakness is probably with the HTML and the jS part. Once a user click the button, I want a delay of five minutes before he could send the message again. Hence, I have to desactivate the button for five minute once it is use and display the message : 'The message was sent to the client. Please wait 5 minutes before sending the message again.' when the cursor is ON the button. How … -
Django. How to return QuerySet order_by result of a fuzzy wuzzy method?
Here is my model: class Item(models.Model): status = models.IntegerField(choices=STATUS_CHOICES, default=3) def __str__(self): return 'Item: {0}'.format(self.id) class Name(models.Model): name = models.CharField(, max_length=600, default='') item = models.ForeignKey(Item, db_index=True, blank=True, null=True) main = models.BooleanField(default=False) def __str__(self): return '{}'.format(self.name) I would like to queryset Items, so it return X items sorted by Fuzzy wuzzy. Basically I need to find matching Items and merge them. I tried to create a dictionary, but it is extremely slow. I have about 80 000 items and its still counting. I tried to something like: items = Item.objects.filter(status=3) .annotate( score=fuzz.ratio(query,i.name_set.all().first().name)) .order_by('-score') Anyone can give me some light on the topic? thanks -
How to access data form in put request of class based views in django
I am currently having a problem with accessing my data stored in a data form. I'm passing it through ajax and its received by the put method in views.py. The problem is I only know how to access it through request.POST["item_name"] and for file request.FILES["photo"]. But apparently this doesnt work in put request. Can anyone please help? jQuery const form = new FormData(); const name = $('#edit-product-name-input-' + productID).val(); const quantity = $('#edit-product-quantity-input-' + productID).val(); const description = $('#edit-product-description-input-' + productID).val(); const price = $('#edit-product-price-input-' + productID).val(); const photo = $('#edit-product-photo-' + productID); if (extractPhoto(photo)) { form.append('photo', extractPhoto(photo)); } form.append('name', name); form.append('price', price); form.append('description', description); form.append('quantity', quantity); form.append('product_id', productID); attachCSRF(); $.ajax({ url: window.location.pathname + "products/", method: "PUT", data: JSON.stringify(dict), contentType: false, processData: false, success: function (data) { alert(data["product"] + " edited"); location.reload(); }, error: function (data) { if (data.responseJSON) { displayErrors(data.responseJSON); } } views.py @staticmethod def put(request, stall_id): dict = { "product_name": request.body('name'), "description": request.body('description'), "price": request.body('price'), "quantity": request.body('quantity') } errors = handle_errors(dict) print(errors) if not errors: product = Product.objects.get(id=request.POST.get("product_id")) product.name = dict["product_name"] product.description = dict["description"] product.price = dict["price"] product.quantity = dict["quantity"] if 'photo' in request.FILES: product.photo = request.FILES.get('photo') product.save() data = { "product": product.name } return HttpResponse( json.dumps(data), content_type="application/json" … -
python: zipping csv buffers
I want to zip some csv buffers into a new zip buffer as follows (python 2.7): files = [] csv_buffer = StringIO.StringIO() writer = csv.writer(csv_buffer) writer.writerow(["some", "csv", "data"]) csv_buffer.seek(0) files.append(csv_buffer) zipped_file = io.BytesIO() with zipfile.ZipFile(zipped_file, 'w') as zipper: for i, csv_file in enumerate(files): csv_file.seek(0) zipper.writestr("{}.csv".format(i), csv_file.read()) zipped_file.seek(0) Then I dispatch the resulting buffer through a Django view to download. However if I open the zip, I find a file (0.csv), but it is not correctly encoded. I would like to have it encoded as UTF-8. I tried also as follows: zipper.writestr("{}.csv".format(i), csv_file.read().encode("utf-8")) but that made no difference. Also changing zipped_file = io.BytesIO() to zipped_file = StringIO.StringIO() Didn't help. Any ideas about what went wrong would be much appreciated! -
Is it possible to show multiple times the same queryset on template?
This is an odd question but I'd like to be able to show the same queryset multiple times on my template using different {% for loops %}, I'm trying to avoid copy pasting each {% for loops %}. Let's say I have my views.py like this : ... chicken = Chicken.objects.filter(id=1) return render(request, 'chicken.html', {'chicken':chicken} chicken.html : the example below is the one I'm avoiding. <!-- {{ egg }} has the same value everywhere --> {% for egg in chicken %} <!-- has a different index than other loops --> <p id="egg_1">{{egg}}</p> {% endfor %} {% for egg in chicken %} <p id="egg_2">{{egg}}</p> {% endfor %} {% for egg in chicken %} <p id="egg_3">{{egg}}</p> {% endfor %} ...x52... Is there a way to automatise this while having index on each loop ? -
Connection refused to REST Django
I have a problem with access to my REST Django data. As u already understand, I have a Django app whith standart REST localhost with my data. My another application, which i made in ReactJS, got Json file with data using axios throught standart GET ajax request. Now i wanna to connect to my React app from another computer at the same network and it's go easily using http://ip4:3000. But in that way i can't get data from REST page which i have on my localhost:8000. I try to get data from terminal in the same way using ip + localhostport, but i always got an error : curl: (7) Failed to connect to 106.120.89.142 port 8000: Connection refused I can't do it using browser to, someone know solution for that? -
django-autocomplete-light, not load selected value
I use in form Select2Multiple: events = forms.MultipleChoiceField(choices=(('vispage', 'Visited Page'), ('visevent', 'Visited Event'), required=False, widget=autocomplete.Select2Multiple(attrs={'class': 'form-control', 'data-placeholder': 'Select type(s)'})) template: <div class="form-group">{{ form.events }}</div> {% if form.events.errors %} <div class="alert alert-danger" role="alert">{{ form.events.errors }}</div> {% endif %} But it gives the following error, regardless of the Value or form I choose choose: Select a valid choice. is not one of the available choices. -
Keep user logged in accross Sites
I'm using Django Sites framework to hadle different sites. They have different domains but same database and same users. I'd like to add a link to switch between my sites. The thing is I don't want to get redirected to login form. What is the best way to achieve this? Is it possible to build a view that logs the user in the destination site and then redirect to it? class SiteSwitcherView(View): def get(self, request, *args, **kwargs): site = Site.objects.filter(pk=kwargs.get('site_pk')).first() # log request.user in the destination Site # ... return redirect("http://{0}/dashboard/".format(site.domain)) To use authenticate() and login(), I have to pass the user credentials and current request...maybe if I send a post request to login view of the destination site before redirect would work? -
In Django ORM, how does one get_or_create for values in JSONField?
I am having a Django model like: class Subscription(models.Model): data = JSONField(default=dict) I want to do something like this: data = {"product_id": 123, "available": False} subscription, new = Subscription.objects.get_or_create(data__product_id=123, data__available=False) I tried doing the above but it just set the field as empty dictionary. -
is there any convenient way for django makrdown add css style?Such as mistune
is there any convenient way for django makrdown add css style?Such as mistune.I mean add css in filter this is the templatetag i found: with using this in template {{ content | markdown_detail | safe }} I just got html with stylesheet,Can anyone help? def block_code(text, lang, inlinestyles=False, linenos=False): if not lang: text = text.strip() return u'<pre><code>%s</code></pre>\n' % mistune.escape(text) try: lexer = get_lexer_by_name(lang, stripall=True) formatter = html.HtmlFormatter( noclasses=inlinestyles, linenos=linenos ) code = highlight(text, lexer, formatter) if linenos: #here add style class for div if linenos exsited return '<div class="highlight">%s</div>\n' % code return code except: return '<pre class="%s"><code>%s</code></pre>\n' % ( lang, mistune.escape(text) ) class HighlightMixin(object): def block_code(self, text, lang): # renderer has an options inlinestyles = self.options.get('inlinestyles') linenos = self.options.get('linenos') return block_code(text, lang, inlinestyles, linenos) class TocRenderer(HighlightMixin, mistune.Renderer): pass @register.filter def markdown_detail(value): renderer = TocRenderer(linenos=True, inlinestyles=False) mdp = mistune.Markdown(escape=True, renderer=renderer) return mdp(value) -
ModuleNotFoundError: No module named 'api'
I created a Django project inside of api folder called bucks: api |____ bucks/ |____ __init__.py |____ manage.py webroot |___ ... And in my bucks folder inside the api, I am doing the following: from api.users.views import CustomObtainAuthToken But I am facing an error when I run makemigrations: ModuleNotFoundError: No module named 'api' I also tried to add users.app.UsersConfig in my INTALLED_APPS, but then, this error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. So I am in this impass. I couldn't find another way to import CustomObtainAuthToken, it'd only allow me to access it through that syntax. -
302 status on my heroku django app
I have deployed my django app to heroku. when i try to access the app from my computer it is working fine -- all the get and post ajax request. all are working fine. But when I am trying to acces the map from other computer it gives below error: 2017-07-05T11:49:32.879209+00:00 heroku[router]: at=info method=GET path="/times heet/?from=getTimeSheet&selectedWeek=Fri+Jul+07+2017" host=myotes.herokuapp.com request_id=8d4749b2-b1d8-4681-9134-c155dc41165f fwd="115.118.212.176" dyno=web.1 connect=0ms service=63ms status=302 bytes=302 protocol=https It is status 302 which is related to redirect. But why I am getting this from machine and not from other. Is it related to chrome version or anything else? Thanks in advance