Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django url multiple parameter
It have been from a week that I search without any answer to my problem. I don't know if I proceed in the good way, but I try to have an url that look like this : article/title/0/search=ad/2017-08-01/2017-08-09/; where the parameter are (in brace) : article/{filter}/{page}/search={search}/{date1}/{date2}/. My url.py regex is: url(r'article/(?P<filter>.+)/(?P<page>\d+)/(?:search=(?P<search>.*)/)?(?:(?P<date1>(\d{4}-\d{1,2}-\d{1,2})?)/)(?:(?P<date2>(\d{4}-\d{1,2}-\d{1,2})?)/)?$') When the value search, date1 and date2 are fill, my url think that the {searched word}/2017-08-01/2017-08-09/ is the search value. When search, date1 and date2 are empty, my link are like this: article/title/0/search=///. When the dates are filled article/title/0/search=/2017-08-01/2017-08-09/. In my template, I need my url to be like this :{% url "view" filter page search date1 date2 %} Can someone help me and correct me if i did it in the wrong way? -
Incorporating Django and AngularJS
I had a quick question. I am a beginner in python and have my sites set on building a website. I chose the django framework and have watched a few videos to try and understand it a bit more. So I am by no means an expert. I was wondering if there are any guides on how to mix in angularJS within Django. My overall goal is to add a grid component that pulls from a database that I set up. (if you were to google any type of angular grid component, you'll see what I mean - just a grid that i can add/delete etc ) So my question is how exactly do I do this? Where do I put it in in my django folders? If there are any things I need to follow up with, please let me know! Thanks -
Django Admin and Queues
I would like to use queue messages to keep data consistent across multiple data stores. Right now all of the data for my application is being entered through Django admin and saved directly to Postgres. What's the best route to take in order to trigger a pub/sub type event and update the other data stores with the info save in Django admin? -
Multiple forms using AJAX cause page to run too slowly
I am building a website in Django/python, and on this particular page, the view returns a set of objects. The template then generates a form for each object, and the form is submitted with AJAX. Everything works as I want it to without errors, but the problem is the more objects that are in the view, the slower the AJAX works. With about 100 objects, it takes 2 to 3 seconds for each one, where with about 10 objects, it takes less than a second. Originally I tried commenting out a lot of the things that happen on submission, but it didn't improve the speed at all! I'm not sure how I can speed it up, without changing the way the code is organized, which I would like to stay away from, as is a feature I really like! I have been searching but all answers are saying that it is the submission of the form that takes long, when that has made no difference to the speed of my code. interact.html {% for adopt in adopts %} <form class="interact-form"> <!-- some fields --> </form> {% endfor %} <script type="text/javascript"> $(document).ready(function(){ $(".interact-form").submit(function(){ event.preventDefault(); $.ajax({ url: '{% url 'interact' %}', type: … -
django: how override get_queryset of List_view?
Have some troubles with ListView. I would override get_queryset for give an argument for sort my list but its like its a new method my view : enter image description here I think trouble come from the import of listView. if i dont write ListView.attribut in class its doesn't work ex if i write List.view.model its work if i write model it doesn't work What i need to do for override get_queryset and for dont have to write the "ListView" before attribut? Can you help me please? Thanks! python : 3.4 django : 1.13 -
What determines which ErrorLog Apache logs an error to (httpd.conf vs. vhost.conf)?
Background I have a Django site served by Apache, set up in its own virtualhost and using mod_wsgi. I want all of the errors associated with this virtualhost to be logged to a single file. Currently, some errors are being sent to Apache's default error log and others are being sent to the one I defined in the virtualhost. I'm pretty sure I have Django set up to stream WARN, ERROR and CRITICAL errors to sys.stderr via an instance of logging.StreamHandler configured in my Django settings. I think mod_wsgi passes that along to Apache, which then logs it according to whichever ErrorLog, ErrorLogFormat and LogLevel directives apply. Questions What settings/situations cause errors to go to one log over another? Is it possible to unify the kinds of errors I give examples of? Are there any limitations on which errors can be logged where? Error log examples /var/log/apache2/mysite_error.log : (Caused by purposefully setting an invalid log level "foo" for the default Django logger in the Django settings files.) [Wed Aug 09 19:48:31.049028 2017] [:error] [pid 30894:tid 140490808121088] [client 129.112.115.40:32828] mod_wsgi (pid=30894): Target WSGI script '/home/myuser/mysite/mysite/mysite.wsgi' cannot be loaded as Python module. [Wed Aug 09 19:48:31.049050 2017] [:error] [pid 30894:tid 140490808121088] [client … -
Using Python Generators with sub list
My source of data is from a Django QuerySet which has the following info: transaction_date, transaction_id, transaction_amount, I want it arrange it in list that group by week, then group by day. The result of list is something like this week_list = [{'week': tran.date.isocalendar()[1], 'tran_count': 5, 'tran_total': 18000, 'day':[{'day': tran.date, 'tran_count': 1, [list_of_transaction}]] here's my current code transaction_list, week, day = [], None, None for transaction in queryset: if not week == transaction.date.isocalendar()[1]: week = transaction.date.isocalendar()[1] week_data = {'week': transaction.date.isocalendar()[1], 'transaction_count':0, 'transaction_total': 0, 'day_list':[], } transaction_list.append(week_data) if not day == transaction.date: day = transaction.date day_data = {'day': day, 'transaction_count':0, 'transaction_total': 0, 'transaction_list': [],} week_data['day_list'].append(day_data) day_data['transaction_list'].append({'id': transaction.id, 'date': transaction.date , 'amount': transaction.amount}) day_data['transaction_count'] += 1 day_data['transaction_total'] += transaction.amount week_data['transaction_count'] += 1 week_data['transaction_total'] += transaction.amount my question is if this is possible to re-write using generators or any improvement can be made? Thanks -
Unable to read Django FieldFile in custom storage`
I'm attempting to make a custom file storage class for my Django app that transparently logs a hash of all files saved. My test storage class is pretty trivial: from django.core.files.storage import Storage from django.db.models.fields.files import FieldFile from utils import get_text_hash class MyStorage(Storage) def _save(self, name, content): if isinstance(content, FieldFile): raw_content = content.open().read() else: raw_content = content assert isinstance(raw_content, basestring) print(get_text_hash(raw_content)) return super(MyStorage, self)._save(name, content) However, when I try and save a file in my app, I get the error: 'NoneType' object has no attribute 'read' with the traceback ending on the line: raw_content = content.open().read() Why is open() returning None instead of a file handle? What's the proper way to access your raw file content inside a Django storage class? -
{% if a==b %} statement makes cuts off part of object
When using the templating language to filter some objects that look like this: ({'a': u'TEST'} {'b': [804]}) And inside my template: {% for code in list%} #Loops through all of the possible 'a's for that client, only contains strings {% for sum in test_sum%} #Is the above object, 'a' is a string, 'b' is a number. {% if sum.a == code %} #Matches the two fully <div class="test"> {{code}} </div> <div class="test"> {{sum}} #Should display {'a': u'TEST'} {'b': [804]} </div> {% endif %} {% endfor %} {% endfor %} Instead, doing this only gives me the following result: {'a': u'TEST'}. When I test it without any if statement, I can see that the full object is returned. So my question is - how come an if statement is cutting off the second part of my object? Right, now, it's working exactly as intended except for that issue. Thanks in advance. -
Django - No redirect on form submission
I'm at the end of my rope trying to figure out why a simple form redirect is not working. I'm submitting a form with one text field via POST request that gets combined with some data from a function in the same views.py file, which is then saved to the model on the database. For some reason, with the redirect schemes that I've set up on submission of the form, I get either a second copy of the form. feedbackapp/views.py from django.shortcuts import render, redirect from django.http import HttpResponseRedirect from django.urls import reverse from .forms import FeedbackForm from .models import Feedback def record_feedback(request): if request.method == 'POST': form = FeedbackForm(request.POST) if form.is_valid(): feedback = Feedback() feedback.submitter_ip = get_client_ip(request) feedback.feedback_text = form.cleaned_data['feedback'] feedback.save() return HttpResponseRedirect(reverse('feedbackapp:thanks')) elif request.method == 'GET': form = FeedbackForm() return render(request, 'feedbackapp/feedback_form.html', {'form': form}) def thanks(request): return render(template_name='feedbackapp/thanks.html',request=request) # https://stackoverflow.com/questions/4581789/how-do-i-get-user-ip-address-in-django def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-1] # needs to be the last element in array for Heroku else: ip = request.META.get('REMOTE_ADDR') return ip feedbackapp/forms.py from django import forms class FeedbackForm(forms.Form): feedback = forms.CharField(label='Feedback', max_length=5000) feedbackapp/templates/feedbackapp/feedback_form.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Anonymous Feedback</title> </head> <body> <form action="/" method="post"> {% csrf_token %} {{ form … -
Pika-RabbitMQ: how to make a completion callback with nowait==False (re. channels in Django)?
I have a problem with implementing django-channels with RabbitMQ channel layer. I'd finished RabbitMQ tutorial and ran through Andy Goodwin's (https://github.com/andrewgodwin/channels-examples) and Vincent Zhang's (https://github.com/VincentTide/django-channels-celery-example) examples without any problem, but stumbled upon mixing the two for my purposes. The problem seems to be with Pika module. At first, pika==0.10.0 raised the following exception: pika.exceptions.ChannelClosed: (404, "NOT_FOUND - no exchange 'binding.enquirer' in vhost '/'") After upgrading pika to 0.11.0b1 the exception changed to ValueError: Must have completion callback with nowait=False Tracing back to pika's source code (channel.py), it seems that the method responsible for canceling the consumer, basic_cancel, has the follwing parameters: nowait==False callback is None which isn't acceptable by the program. I don't know how to solve this. Here's my code (nothing beyond Andy's example, really): consumers.py class Demultiplexer(WebsocketDemultiplexer): consumers = { "taxpayer": TaxpayerBinding.consumer, } groups = ["binding.enquirer"] models.py class Taxpayer(models.Model): ... class TaxpayerBinding(WebsocketBinding): model = Taxpayer stream = "taxpayer" fields = ["taxpayer_id", "checksum_status", "name"] @classmethod def group_names(cls, *args, **kwargs): return ["binding.enquirer"] def has_permission(self, user, action, pk): return True routing.py channel_routing = [ route_class(Demultiplexer, path="^/binding/"), The html template and javascript inside is a mess right now, so unless crucial to solving this problem, I'd rather not show it right now … -
A plugin to assign tasks to other programmers
I've created a Django project. As I am the manager of the project, I am looking for the better way to assign tasks to the other programmers with me. What do you guys suggest? Is there a plugin, a website or an application I could use? I prefer a good plugin. -
Where can I find the Read The Docs application log file
This is an admittedly basic question -- but as I'm new to Django and our self-hosted Read The Docs ecosystem, I've got to ask it: Where can I find the most comprehensive application log file in a self hosted Read The Docs instance? I'm specifically looking for this to better understand the code's flow of execution as well as troubleshoot some bugs that have come up. -
Getting a n.apply is not a function error while trying to pass data from Django to the nvd3 chart
I was trying to build a nvd3 line chart. I would like to set up my dataset in python and then pass it to the nvd3 chart script. However, I was getting an javascript error "n.apply is not a function". Please let me know if you see any error in my code, or if you know the proper way of doing this. views.py xdata = [1,2,3] ydata = [2,4,6] chartData = {'x': xdata, 'y': ydata} context = {'chartData':chartData} html <script>var lineData = "{{ chartData }}"</script> <div id="chart" style="height:88%"> <svg></svg> <script> nv.addGraph(function() { var chart = nv.models.lineChart() .useInteractiveGuideline(true) ; chart.xAxis .axisLabel('Date') .tickFormat(d3.format(',r')) ; chart.yAxis .axisLabel('Price') .tickFormat(d3.format('.02f')) ; d3.select('#chart svg') .datum(lineData) .transition().duration(500) .call(lineData) ; nv.utils.windowResize(chart.update); return chart; }); </script> </div> -
Sending POST request to the server inside docker
I'm trying to make a webserver application on django running inside docker container alongside celery. Here is my docker-compose.yml: version: '2' services: app: restart: always build: . volumes: - .:/myapp - /etc/myapp:/etc/myapp - /opt/myapp/static:/myapp/collected_static - /opt/myapp/media:/myapp/media - /opt/myapp/datasets:/myapp/datasets ports: - "8080:8080" links: - db - redis command: ./deploy/docker_entry.sh environment: - PYTHONUNBUFFERED=0 tty: true db: restart: always image: postgres:latest environment: POSTGRES_USER: myapp POSTGRES_PASSWORD: myapp POSTGRES_DB: myapp volumes_from: - data ports: - "5432" data: image: busybox:latest volumes: - /var/lib/postgres command: "true" redis: image: redis:latest hostname: redis worker: build: context: . dockerfile: Dockerfile command: ./deploy/run_celery.sh volumes: - .:/myapp - .:/app - /etc/myapp:/etc/myapp - /opt/myapp/media:/myapp/media links: - db - redis My Dockerfile: FROM python:3.6 RUN pip3 install -U pip setuptools RUN pip3 install uwsgi ADD . /myapp ENV DJANGO_SETTINGS_MODULE app.settings # Install R for rpy2 RUN apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9 RUN apt-get update RUN apt-get install -y r-base RUN pip3 install -r /pandora/requirements.txt EXPOSE 8080 EXPOSE 8000 EXPOSE 80 WORKDIR /myapp The problem is, that Im not able to send POST request from my frontend on ReactJS. Consider the following function: $.ajax({ method: 'POST', url: '/myapp/upload_user_sample/', data: data, processData: false, contentType: 'multipart/form-data', success: function (response) { console.log(response); } }) When you send … -
Django - TDD: 'HttpRequest' has no attribute 'POST'
So I'm doing TDD with Django and I'm stuck on the following problem. Test method for class from TestCase def test_home_page_can_save_POST_request(self): request = HttpRequest request.method = 'POST' request.POST['item_text'] = 'A new list item' response = home_page(request) self.assertIn('A new list item', response.content.decode()) And I'm getting error as: request.POST['item_text'] = 'A new list item' AttributeError: type object 'HttpRequest' has no attribute 'POST' But HttpRequest has the attribute 'POST' as per Django docs. Thansk guys! -
Showing Alert Message Before Saving Model in Django Admin
There are ways to show a message after a model has been saved in the database or if there is any error while saving. But how do I show an alert when the user clicks save button in Django Admin? Is there a way to do that? -
what should i be researching if i want to learn a web application development workflow regardless of programming language [on hold]
I'm probably gonna get a lot of downvotes for this but frankly I don't care I just want to learn. So, my problem is I can pretty much code a static/responsive/interactive website from the ground up but I can never get the back end logic down. I'm no IT student/graduate. I've learnt to code on my own through watching video tutorials and reading articles online and I've somehow managed to learn HTML, CSS, Javascript, jQuery, JSON, AJAX, a bit of PHP and MySQL. I tried learning both Laravel and Python afterwards but all the back end stuff is just too confusing and I feel like I am missing some things. Like web application directory structures, or how to connect this file to another file and so on... so what exactly is a good learning path for back end programming? For instance, for front end you start off with HTML, then CSS, then a scripting language like Javascript and finally PHP and MySQL, but for back end programming I'm pretty much drawing a blank. Like am I supposed to just study Python and Django without learning how to build a web app from scratch and just let the framework do the … -
I am trying to make a field for a model which is unique for the choices but could be blank or null
I have a field in a model that I would like to be a choice or blank. There may be as many blank items as possible but need to be unique for all others ie there may not be two specials on the same day. Here is my views.py class Item(models.Model): CATEGORY_CHOICES = (('Sandwich', 'Sandwich'), ('Salad', 'Salad'), ('Slider', 'Slider'), ('Side', 'Side'), ('Drink', 'Drink')) DAYS = (('Monday','Monday'), ('Tuesday','Tuesday'), ('Wednesday','Wednesday'), ('Thursday','Thursday'), ('Friday','Friday'), ('Saturday','Saturday'), ('Sunday','Sunday')) name = models.CharField(max_length=50) description = models.TextField() category = models.CharField(max_length=50) price = models.DecimalField(max_digits=6, decimal_places=2) category = models.CharField(max_length=30, choices=CATEGORY_CHOICES) order = models.PositiveSmallIntegerField(default=0, blank=True, null=True) special = models.BooleanField(default=False) day = models.CharField(max_length=30, choices=DAYS, unique=True, blank=True) publish = models.DateField(auto_now=False, auto_now_add=False), updated = models.DateTimeField(auto_now=True, auto_now_add=False) def __str__(self): return self.name I am also trying to order the daily specials by day of the week ie (Monday, Tuesday, etc) and I thought the following view was working but it seems to be ordering the Items by id def specials(request): specials_list = Item.objects.filter(special = True).order_by('day') context = { 'specials_list': specials_list, } return render(request, 'menu/specials.html', context) Thanks in advance for the help! -
Making a drop down list that filters out certain model objects in Django
I'm trying to make a page that lists all objects of a certain model, but also has a dropdown on top that filters the list based what was selected in the dropdown. Below is some example code. models.py class School(models.Model): name = models.CharField(max_length=64) slug_name = AutoSlugField(populate_from='name', unique=True) class Student(models.Model): name = models.CharField(max_length=32) school = models.ForeignKey(School) tables.py class StudentTable(tables.Table): class Meta: model = Student fields = ('name', 'school') attrs = {'class': 'table table-hover', 'id': 'accessorycharge_list'} Below is what the view would look like without the dropdown list. views.py def list_students(request): student_list = Student.objects.all() table = StudentTable(student_list) RequestConfig(request).configure(table) return render(request, 'students/list_students.html', {'table': table}) In this example, I would theoretically want to make a dropdown in the same template as the list. The dropdown would contain the names of the schools. When nothing is selected, the list will show all of the students, but once a school is selected in the dropdown, the list would be filtered and only the students that have their school field match the one selected in the dropdown would be shown. How would I write my view and/or template in order to make this function? Thanks. -
__contains not working for numbers? (Django + MongoDB)
I have the following code in my Django view (python): query = {} for k, v in filters.items(): if v: query[k + '__icontains'] = v filters is a json which contains all the filters I want to apply. They are gathered from inputs of TYPE="TEXT". Then I do the following: result = model.objects.filter(**query).order_by(order_by).skip(page_size*(page-1)).limit(page_size).only(*attr_names) For some reason, for the string parameters in my MongoDB, it works fine. I can find for 'ca' and it will find things like 'Calamity' or 'alcaline'. However, if I look for 2 in a numeric field, it will only get results that are exactly 2, but not 72 or 234. If I look for 234 I will get results with 234 but not 52346 or 23456 Why is it? Might it be related to the fact that I'm comparing text with numbers? How can I fix that? And why does it work for the exactly-matching records? -
Django form: if searchForm
I got a model, for simplicity only 1 field shown here: class Family(models.Model): myboolean = models.BooleanField(default=False) Here is my form for that model: class FamilyForm(ModelForm): def __init__(self, *args, **kwargs): self.searchForm = kwargs.pop('searchForm', False) super(FamilyForm, self).__init__(*args, **kwargs) if self.searchForm: for key in self.fields: self.fields[key].required = False # let the user search by whatever field he wants to <help needed right here> class Meta: model = models.Family fields = '__all__' When I create the form with "searchForm = True" I get a problem with the boolean field in my model. It has a default value of "False" but of course I want to let the user search for a family without using that boolean field. When the user doesn't tick the box, I get "False". When he ticks the box I get "True". But I also need "value not needed for search". How do I do this? -
Generate objects in django template dynamically
I have 2 models in my system: class Display(models.Model): name = models.CharField UE = models.CharField description class Register(models.Model): temp1 = models.FloatField() temp2 = models.FloatField() flow = models.FloatField() I create displays using for inside a template, but the value of each display is a respective field in Register model. I can't make the loop with Register because i use only row (i can't loop fields). Understand? Take a look of my code: View: def main(request): dp_col = Display.objects.all() reg = Registers.objects.latest('pk') context = { 'dp_col': dp_col, 'reg':reg } return render(request,'operation.html',context) Template: {% for dp in dp_col %} <div class='col-md-6'> <div class="display-content"> <div class="display-data"> <h3 class="text-center display-desc">{{dp.name}} <span>:</span> <span class="text-center display-value">I need put the value of each field here</span> <span class='display-unit'> {{dp.UE}}</span> </h3> </div> </div> </div> {% empty %} <!--colocar alguma coisa aqui, caso não tenha nada no for--> {% endfor %} Any ideas? Thanks a lot! -
Django error when trying to use update_or_create "SyntaxError: keyword can't be an expression"
Trying to rewrite an importer for our database and I'm coming across a syntax error I don't really understand. Here's the code for the importer. The line that's causing problems is the last line. obj, _ = KeywordInContext.objects.update_or_create(main_keyword.word=this_keyword, context=context). On this line of code, I am trying to create a get or create a new KeywordInContext object. The field "main_keyword" is a foreignkey to another object called Keyword. Keyword has a field called "word," and another called "context." So I'm trying to initialize these fields as parameters. The only other thing to note is statement['context'] is part of a dictionary (but there's never been issues with this for loop ever and there shouldn't be now...) for keyword, contextlist in statement['context']: print "KEYWORD: ", keyword this_keyword, _ = Keyword.objects.get_or_create(word=keyword,) #creating a keyword object for context in contextlist: obj, _ = KeywordInContext.objects.get_or_create(main_keyword.word=this_keyword)#, context=context) This gives the following error. Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python-virtualenv/gtr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python-virtualenv/gtr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python-virtualenv/gtr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 208, in fetch_command klass = load_command_class(app_name, subcommand) File "/usr/local/lib/python-virtualenv/gtr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 40, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module … -
Django. How to change a block title in admin?
How do you change your models to show a necessary box-title in admin?