Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why isn't the radio button in my Django template form displaying on the screen?
I'm following a tutorial on Django's official site (https://docs.djangoproject.com/en/2.0/intro/tutorial04/), everything went fine until I came to the part where they had me create an html form using Django templates, here's the template and form (namely, detail.html): <h1>{{ question.question_text }}</h1> <ul> <!--{% for choice in question.choice_set.all %} <li>{{ choice.choice_text }}</li> {% endfor %}--> <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }}</li> <label for="choice{{ forloop.counter }}">{{ choice.choice_text}}</label><br /> <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> {% endfor %} <input type="submit" value="Vote" /> </form> </ul> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} Here's the view: def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) The part where I start to get problems is at the radio button (in template), it doesn't display on the screen at all, here's the output: I tried rearanging the code a little in hope that there might be a syntax error, then I tried finding the solution by watching tutorials on youtube but no success, come somebody help me? -
Dashboard doesn't populate values after forking template django-oscars
here's my view.py of dashboard- from django.views.generic import TemplateView class IndexView(TemplateView): def get_template_names(self): if self.request.user.is_staff: return ['mytemplates/index.html'] else: return ['dashboard/index_nonstaff.html', 'mytemplates/index.html'] So I'm successfully able to fork the app and extend templates but for some reason no values appears on the dashboard -
Pagination in django with elasticsearch-dsl don't work
When a i search by a term/word..., a TypeError appear: Exception Value: object of type 'Search' has no len() That's my code: views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from elasticsearch import Elasticsearch from elasticsearch_dsl import Q, Search @login_required def search(request): q = request.GET.get('q') client = Elasticsearch() paginate_by = 1 if q: s = Search(using=client, index='people') s = s.highlight('name', 'cpf', 'rg', 'people_nick.nickname') q = Q("multi_match", query=q, fields=['nome', 'cpf', 'rg']) | \ Q("nested", path="people_nick", query=Q( "match", people_nick.nickname=q)) s = s.query(q) paginator = Paginator(s, paginate_by) page = request.GET.get("page") try: people = paginator.get_page(page) except PageNotAnInteger: people = paginator.get_page(1) except EmptyPage: people = paginator.get_page(paginator.num_pages) else: s = '' total_results = False time_response = False return render(request, 'search/result.html', { 'people': s, }) Looking for a solution, i follow this answer and create a Proxy, like this: from django.utils.functional import LazyObject class SearchResults(LazyObject): def __init__(self, es): self._wrapped = es def __len__(self): return self._wrapped.count() def __getitem__(self, index): search_results = self._wrapped[index] if isinstance(index, slice): search_results = list(search_results) return search_results ...and, in views.py above, i added: (...) s = s.query(q) s = SearchResults(s) # <--- added here paginator = Paginator(s, paginate_by) (...) So, when i search by a term that return … -
How do I get django-allauth to send html emails
Cookiecutter-django uses: django-allauth (which needs to send registration confirmation emails) django-anymail configured to use mailgun. Things are mostly working. But I can't figure out why I'm only getting plain text emails instead of HTML emails. I do have html emails defined in templates/account. I must be missing a configuration setting someplace. But it looks like just the presense of the .html files should be enough. So how do I get django-allauth to send html emails? -
Django Migration Problems on production server
Hi I would like to move my local environment to my production website but when I do makemigrations i get this error: django.db.utils.ProgrammingError: relation "structure_structurefields" does not exist LINE 1: ..., "structure_structurefields"."seo_keywords" FROM "structure... what do I do ? any help will be welcomed. -
Django Rest Framework Related Model Permissions
I'm using DRF to build a simple API. I've 3 related models, User, Device, Data. (One-to-many relation between User-Device and Device-Data) I've a problem about permissions. Right now, for User-Device relation, authenticated users can only view or edit their own Devices. (And when they create a Device, the relation is automatically established.) I want users to be able to view, create or edit Data only for their devices. For example, a user can't create a Data or view a Data of a device that doesn't belong to him. I couldn't figure out what is the correct way to achieve this. Can you help me with this? Here is my views.py from django.contrib.auth.models import User, Group from rest_framework import viewsets, permissions from iot_cloud_app.serializers import * from iot_cloud_app.permissions import IsOwner # Create your views here. class DeviceViewSet(viewsets.ModelViewSet): """ API endpoint that allows devices to be viewed or edited. """ serializer_class = DeviceSerializer permission_classes = ( IsOwner, ) def get_queryset(self): """ Filter devices of the user that made the request. """ return Device.objects.all().filter(user=self.request.user) def perform_create(self, serializer): serializer.save(user=self.request.user) class DataViewSet(viewsets.ModelViewSet): """ API endpoint that allows device data to be viewed or edited. """ serializer_class = DataSerializer def get_queryset(self): """ Filter data of devices that … -
Layout Form data with Bootstrap 4 (for endfor / data)
I'm trying to ploy my formdata (some text and an image) onto the screen using bootstrap in a way that puts the blocks of data (text + image) next to each other instead of below each other. I played around with column sizes but I cannot get it to work. All containers are placed below each other on a big screen. On a small screen the layout is good, but on a big screen nothing flips over to the remaining columns <div class="container-fluid"> <h1 class="my-4 text-center text-lg-left">Thumbnail Gallery</h1> {% block content %} {% for contexts in context %} <div class="col-lg-auto col-lg-auto col-6-auto"> <h2>Title: {{ contexts.title }}</h2> <p>Category: {{ contexts.category }}</p></div> <p>Description: {{ contexts.description }}</p> <p>Price: {{ contexts.price }}</p> <p>Created: {{ contexts.created }}</p> <img class="img-fluid img-thumbnail" src="{{contexts.document.url}}" width="20%" height="20%"/> </div> {% endfor %} </div> -
Fetch and display data on React bootstrap Table
Hello guys i am trying to display my data from my api here my Json response : { "id": 1, "name": "Chicken Wings", "product_category": { "name": "Starter" }, "short_description": "Delicious Chicken Wings", "image": "http://127.0.0.1:8000/api/meal_images/telechargement.jpeg", "price": 10 }, { This is my react component for the table : <BootstrapTable data={this.state.todos} striped hover> <TableHeaderColumn isKey dataField='id'>ID</TableHeaderColumn> <TableHeaderColumn dataField='name' filter={ { type: 'TextFilter', delay: 1000 } }>Name</TableHeaderColumn> <TableHeaderColumn dataField='product_category' filter={ { type: 'TextFilter', delay: 1000 } }>Category</TableHeaderColumn> <TableHeaderColumn dataField='image'> Image </TableHeaderColumn> <TableHeaderColumn dataField='price'> Price </TableHeaderColumn> </BootstrapTable> but for 'product_category' that display me '{object} {object} , i try to display the name of the product_category , i tried with dataField='product_category.name' but dosen't work how can i access to the name of my product_category table ? Thank you -
What happens when using `django-admin dumpdata` on a 'hot' or 'live' database?
When using the django-admin dumpdata command, what happens if the database is modified while the data is being exported? Is it possible for the data dump to be transactional? -
axios post to django failing due to csrf
I am using React + Django and trying to make a post request using axios but it is failing due to csrf. I have tried all the answers posted on internet to similar problem but none of them are working for some weird reason. //Django View def createUser(request): username = request.POST['username'] email = request.POST['email'] resp = { 'username' : username, 'email' : email } return JsonResponse(resp) //Axios Post axios.post('http://localhost:8000/api/createUser/',{ username : 'xyz', email : 'xyz@gmail.com' }, { headers: { Content-Type': 'application/json', } }); tried adding defaults axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; axios.defaults.xsrfCookieName = "csrftoken"; but still getting csrf failed. I know i can do @csrf_exempt on the view but i want to keep the csrf check. -
Django Google App Engine Error: Internal Error
I'm trying to deploy the app to GAE, when I get the following traceback: Updating service [lstm] (this may take several minutes)...failed. DEBUG: (gcloud.app.deploy) Error Response: [13] An internal error occurred during deployment. Traceback (most recent call last): File "/Applications/sdks/google-cloud-sdk/lib/googlecloudsdk/calliope/cli.py", line 844, in Execute resources = calliope_command.Run(cli=self, args=args) File "/Applications/sdks/google-cloud-sdk/lib/googlecloudsdk/calliope/backend.py", line 756, in Run resources = command_instance.Run(args) File "/Applications/sdks/google-cloud-sdk/lib/surface/app/deploy.py", line 87, in Run parallel_build=False) File "/Applications/sdks/google-cloud-sdk/lib/googlecloudsdk/command_lib/app/deploy_util.py", line 592, in RunDeploy flex_image_build_option=flex_image_build_option) File "/Applications/sdks/google-cloud-sdk/lib/googlecloudsdk/command_lib/app/deploy_util.py", line 401, in Deploy extra_config_settings) File "/Applications/sdks/google-cloud-sdk/lib/googlecloudsdk/api_lib/app/appengine_api_client.py", line 203, in DeployService poller=done_poller) File "/Applications/sdks/google-cloud-sdk/lib/googlecloudsdk/api_lib/app/operations_util.py", line 312, in WaitForOperation sleep_ms=retry_interval) File "/Applications/sdks/google-cloud-sdk/lib/googlecloudsdk/api_lib/util/waiter.py", line 251, in WaitFor sleep_ms, _StatusUpdate) File "/Applications/sdks/google-cloud-sdk/lib/googlecloudsdk/api_lib/util/waiter.py", line 309, in PollUntilDone sleep_ms=sleep_ms) File "/Applications/sdks/google-cloud-sdk/lib/googlecloudsdk/core/util/retry.py", line 228, in RetryOnResult if not should_retry(result, state): File "/Applications/sdks/google-cloud-sdk/lib/googlecloudsdk/api_lib/util/waiter.py", line 303, in _IsNotDone return not poller.IsDone(operation) File "/Applications/sdks/google-cloud-sdk/lib/googlecloudsdk/api_lib/app/operations_util.py", line 181, in IsDone encoding.MessageToPyValue(operation.error))) OperationError: Error Response: [13] An internal error occurred during deployment. ERROR: (gcloud.app.deploy) Error Response: [13] An internal error occurred during deployment. Everything works fine locally. I have set ALLOWED_HOSTS = ['*'] Could it be that app.yaml doesn't recognise the underscore? entrypoint: gunicorn -b :$PORT --timeout 99999999 model_lstm.wsgi -
Can't run Django project
I'm new in Django. So I wanted to run official Django tutorial. I've installed Django using pip, started projec. And when run "python manage.py runserver" console shows the same thing as in tutorial, but when I open page http://127.0.0.1:8000/ or localhost:8000 I only see one sentence 404 not found. -
In Django how to getbinary field data from POST form
I have one html file, where I am using one image upload button. Now this image is stored in MySql data base as Blob. I need to get or read this image data some how in Django through post method. Can anyone please help how to do? Icon is defined like : icon = models.BinaryField(null=True) My Html: <input type="file" id="toolicon" accept="image/*" data-type='image' > <button id="OpenImgUpload" style="margin-left: 100px">Image Upload</button> In JQuery: $('#OpenImgUpload').click(function(){ $('#toolicon').trigger('click'); }); Image: Now I want to get this file as Binary Field data. Till now I have used : tool_icon = request.POST('toolicon', '') tool_icon = request.POST.get('toolicon', '') tool_icon = base64.b64encode('toolicon', '') Nothing works ... Can any one please help me. -
Startup with Django runseerver error
I am starting up with Python-Django in Ubuntu 18.04. I have python3 installed. python3 --version says Python 3.5.2 After installing Python, I installed Django as below: sudo apt install python3-pip pip3 install django I also have Django installed. django-admin --version says 2.0.5 In my project, startproject worked successfully, but when I am trying to run the following command inside my project: python3 manage.py runserver It gives following errors: Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ImportError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in <module> ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Following command also gives error: python3 -c "import django; print(django.__path__)" Error is: python3 -c "import django; print(django.__path__)" Traceback (most recent call last): File "<string>", line 1, in <module> ImportError: No module named 'django' which django gives blank output echo $PYTHONPATH gives blank output python3 -m django --version says /usr/local/bin/python3: No module named django echo $PATH shows /home/shobhit/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin What is the problem and what … -
How can I set Django `Debugger` time?
The Django debugger is import pdb; pdb.set_trace(). Sometimes we push the code on the server without remove debugger from the code. In this conditions when we request the view (that views contain debugger) then the page will not load and the browser will hang because of that debugger. So my Question is. Can I set a debugger time or How can I avoid debugger after few minutes It's the exception case because we always check in the code but sometimes we missed it by mistake. Thanks in advance -
Using scrapy with scrapyd in Django not entering def(parse)
i'm still learning scrapy and i am trying to use scrapy with scrapyd inside a Django Project. But i am noticing that the spider just wont enter the def(parse) import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule class NewsSpider(CrawlSpider): print("Start SPIDER") name = 'detik' allowed_domains = ['news.detik.com'] start_urls = ['https://news.detik.com/indeks/all/?date=02/28/2018'] def parse(self, response): print("SEARCH LINK") urls = response.xpath("//article/div/a/@href").extract() for url in urls: url = response.urljoin(url) yield scrapy.Request(url=url, callback=self.parse_detail) def parse_detail(self,response): print("SCRAPEEE") x = {} x['breadcrumbs'] = response.xpath("//div[@class='breadcrumb']/a/text()").extract() x['tanggal'] = response.xpath("//div[@class='date']/text()").extract_first() x['penulis'] = response.xpath("//div[@class='author']/text()").extract_first() x['judul'] = response.xpath("//h1/text()").extract_first() x['berita'] = response.xpath("normalize-space(//div[@class='detail_text'])").extract_first() x['tag'] = response.xpath("//div[@class='detail_tag']/a/text()").extract() x['url'] = response.request.url return x The print("Start Spider") is in the log but the "Search Link" is not i also have this kind of error [Launcher,3804/stderr] Unhandled error in Deferred: Please help PS : When i run it outside the Django it work just fine Thank you -
Is there a way to run django migrations without manage.py?
Python django project that is currently built and deployed using MakeFiles. -
Django - update fields inside django model object using kwargs
I searched for a simple answer to this question but couldn't really find any. This question somewhat looks like it, but not quit the same so here it is. Let's say I have a custom update method inside my Django model. class People(models.Model): identifier = models.CharField(max_length=255, primary_key = True) name = models.CharField(max_length=255) house = model.ForeignKey(House) salary = model.IntegerField() def my_fancy_update(self, **kwargs): # Here I want to do my update pass What I want to do is use the kwargs to update my model. Right now I am using the following: def my_fancy_update(self, **kwargs): self.name = kwargs.get('name') self.house = kwargs.get('house') self.salary = kwargs.get('salary') self.save() This is something that looks like what I really want to do: def my_fancy_update(self, **kwargs): self.update(**kwargs) My question now is, if this is possible and how this is done in Django. It saves me a lot of time listing every attribute in my actual models. -
Get sorted queryset by specified field with regex in django
I have the following in Manager: class NullIf(Func): template = "NULLIF(%(expressions)s, '')" class MySiteManager(models.Manager): def get_queryset(self): qws = MySiteQuerySet(self.model, using=self._db).filter( some_id=settings.BASE_SOME_ID).annotate( # This is made for sorting by short labels as by numeric values short_label_numeric=Cast( NullIf(Func( F('short_label'), Value('^(\D+)|(\w+)'), Value(''), Value('g'), function='regexp_replace')), models.BigIntegerField()) ).order_by('short_label_numeric', 'short_label') for q in qws: print(q.short_label, end='\n') return qws Output of print values looks like: 1 10 100 101 102 103 104 105 106 107 108 109 11 110 111 112 113 114 115 116 117 118 119 12 120 121 122 123 124 125 126 127 128 129 13 130 131 132 133 134 135 136 137 138 139 14 140 141 142 143 144 145 146 147 148 149 15 150 151 152 153 154 155 156 157 158 159 16 17 18 19 20 200c 21 22 23 24 25 26 260 261 262 263 264 265fs 266fs 267c 268c 269c 27 273c 274c 275c 276c 28 29 2c 30 302 31 32c 33c 34 35c 36 37 38 3c 4 5 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 524 6 601 602 603 604 605 606 607 608 … -
when inserting data into my django model it displays only the entered data and delets the one which was before that
when i insert data from a form into my django model, it delets the previous data and displays the new one , i want it to display all the data which was entered thanks, in the display exemple , i want it to display : -maçonnerie -platre at the same time , i hope u understood my problem :enter image description here enter code hereenter image description here enter code hereenter image description here enter code hereenter image description here enter code hereenter image description here enter code hereenter image description here -
Display data from Django API on React Bootstrap Table
Hey guys i try to display my data on the Bootstrap Table like this : but i get an error : this is a reserved word (28:6) Also when i try to call my function this.state.todos.map(item =>( just before the Bootstrap Table , that is create me also an header for each object , i try to create just each cell for each object on my data , someone can help me thanks import React, { Component} from 'react'; import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap- table'; // import '../../css/Restaurant/Products/style.css' class Products extends Component { constructor(props) { super(props); this.state = { todos: [] }; } async componentDidMount() { try { const res = await fetch('http://127.0.0.1:8000/api/'); const todos = await res.json(); this.setState({ todos }); } catch (e) { console.log(e); } . } render() { var products = [{ this.state.todos.map(item =>( id: item.id, name: item.name, price: item.price }, { id: 2, name: "Product2", price: 80 )) }]; return ( <div> <BootstrapTable data={products} striped hover> <TableHeaderColumn isKey dataField='id'>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable>, </div> ); } } export default Products; -
Maximum recursion level reached in django project
Browser Response Request Method: GET Request URL: http://192.168.1.25/bigflow/Getprstatus/ Django Version: 2.0.3 Exception Type: OverflowError Exception Value: Maximum recursion level reached Exception Location: /usr/local/lib/python3.5/dist-packages/pandas /io/json/json.py in write, line 99 Python Executable: /var/www/bigb/venv/bin/python Python Version: 3.5.2 Apache2 Hosted File Alias /static /var/www/bigb/Bigflow/Bigflow/static Alias /staticdemo /var/www/bigb/BigflowDemo/Bigflow/Bigflow/static <Directory /var/www/bigb/Bigflow/Bigflow/static> Require all granted </Directory> <Directory /var/www/bigb/BigflowDemo/Bigflow/Bigflow/static> Require all granted </Directory> WSGIDaemonProcess bigflow processes=2 threads=15 display-name=%{GROUP} python-home=/var/www/bigb/venv WSGIProcessGroup bigflow WSGIScriptAlias /bigflow /var/www/bigb/Bigflow/Bigflow/wsgi.py WSGIDaemonProcess Bigflow_api processes=2 threads=15 display-name=%{GROUP} python-home=/var/www/bigb/venv WSGIProcessGroup Bigflow_api WSGIScriptAlias /Bigflow_api /var/www/bigb/Bigflow_api/Bigflow_api/wsgi.py WSGIDaemonProcess bigflowdemo processes=2 threads=15 display-name=%{GROUP} python-home=/var/www/bigb/venv WSGIProcessGroup bigflowdemo WSGIScriptAlias /bigflowdemo /var/www/bigb/BigflowDemo/Bigflow/Bigflow/wsgi.py <Directory /var/www/bigb/Bigflow> Options -Indexes </Directory> <Directory /var/www/bigb/BigflowDemo/Bigflow> Options -Indexes </Directory> <Directory /var/www/bigb/Bigflow/Bigflow> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www/bigb/Bigflow_api/Bigflow_api> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www/bigb/BigflowDemo/Bigflow/Bigflow> <Files wsgi.py> Require all granted </Files> </Directory> I'm working with django project, Recently i have hosted a new application in the apache2 server ,now apache2 is running with two application , both the django project are working fine. But frequently i get some error like "Maximum recursion level reached" and my application fails to work. please help me to find the problem. Is this correct to point both the application towards same virtual environment(venv) -
How to display {% django block %} dynamically with for loop?
Hello Awesome People! I'm building a dashboard for my website, in the left section, I have a menu containing multiple items : Home, Messenger, Job Offers .... When creating an account, Users are able to choose their items, re-order or remove. I have a Menu models, class Menu(models.Model): items = models.ManyToManyField('Item',blank=True) class Item(models.Model): name = models.CharField(max_length=100) unique_key = models.CharField(max_length=100,unique=True) url = ...... For the menu of the user, in my base_template I display the items of the current users with for loop. With a CSS class I want to highlight the current view, the current item. When the user visits his messenger, I want to highlight that item messenger with a CSS class. <ul> {% for item in user.menu.items.all %} <li class='{% block item.unique_key %}{% endblock %}'> <a href="{{item.url}}"> {{item.name}}</a> </li> {% endfor %} </ul> Now, when being in messenger.html for example, knowing that I have a unique_key for messenger called item_messenger, I do {% block 'item_messenger' %}active{% endfor%} It's not working, the item Messenger or whatever I choose doesn't become highlighted, I wonder why? Is there another way to achieve that? Any hint will be helpful, thanks in advance! -
How to concatenate strings in Python using Format?
I want to send dynamic data in my Payload, payload = "{\r\n \"name\": \"{0}\",\r\n \"id\":\"{1}\"}".format(1,2) *** KeyError: '\r\n "name"' But when i try to add static value it's working fine : payload = "{\r\n \"name\": \"just\",\r\n \"id\":\"32\"}" How can i add dynamic data on it? Thanks in advance. -
Django - test multiple views at once
Can I test multiple views against one condition? For example if all of these views uses LoginRequiredMixin or @login_required decorator? This is just for IndexView. class IndexTest(TestCase): def setUp(self): self.user = User.objects.create(username='testuser') def test_login_required(self): response = self.client.get(reverse("profiles:user_filter")) self.assertRedirects(response,reverse("account_login")+"?next={}".format(reverse("profiles:user_filter"))) I would like to test if all views except one or two has LoginRequiredMixin so if I create new view in future, tests will fail if I forgot to use LoginRequiredMixin.