Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Visual Studio Code formats on save no matter what I do. How do I stop this?
I am using python (django syntax) inside an html file: <form action="{% url 'home:favorite' album.id %}" method="POST"> {% csrf_token %} {% for song in album.song_set.all %} <input type="radio" id="song{{ forloop.counter }}" name="song" value="{{ song.id }}" /> <label for="song{{ forloop.counter }}"> {{ song.song_title }} {% if song.is_favorite %} ** {% endif %} </label><br> {% endfor %} <input type="submit" value="Favorite"> </form> No matter what I do in the VS Code settings.json (for user OR workspace) it formats the code like this: <form action="{% url 'home:favorite' album.id %}" method="POST"> {% csrf_token %} {% for song in album.song_set.all %} <input type="radio" id="song{{ forloop.counter }}" name="song" value="{{ song.id }}" /> <label for="song{{ forloop.counter }}"> {{ song.song_title }} {% if song.is_favorite %} ** {% endif %} </label> <br> {% endfor %} <input type="submit" value="Favorite"> </form> (pushes the {% for song in album.song_set.all %} among other things to the previous line and keeps it from being on its own line. Here are my vs code settings: { "editor.fontSize": 18, "editor.formatOnType": false, "editor.formatOnSave": false, "editor.glyphMargin": true, "editor.tabSize": 4, "editor.detectIndentation": false, "editor.wordWrap": true } These settings are the same for both user and workspace. Am I missing something? Thanks, Zach -
Problems with getting data from sqlite database django project
Recently i have started to learn programming and can't solve one problem. I know that i am doing something wrong, can anybody help me. I have Article model, that are connected by a foreingkey to vipusk. Where vipusk is connected to a Year model also by a foreign key. On the top of all is Year model. I have created couple of articles in my database , random ammount of vipusks and some number of Year. When i am trying to get it directly from the databese i got only some of them, i mean one year contains couple of vipusks, and when i am trying to display number of vipusks, i got only 2 each. But i know that one of year contains 4 vipusks. I think the problem is somewhere in views. But i don't know how to fix it THis is my viev field: def arkchive(request): latest_year = YearPub.objects.all().order_by('year_alias') for i in latest_year: latest_vipusks = Vipusk.objects.filter(vipusk_year=latest_year).order_by('id') for j in latest_vipusks: articles = Article.objects.filter(article_vipusk=latest_vipusks).order_by('id') args = {} args['years'] = latest_year args['vipusks'] = latest_vipusks args['articles'] = articles return render_to_response('arkchive.html', args)enter code here and here is what i am trying to get in my template {% for year in years … -
Add some paramenters to FilterSet (django-filter) + some parameters
i have 3 models: class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=70, null=True, blank=True) class SubCategory(models.Model): category= models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=200, ) class Products(models.Model): user= models.ForeignKey(User, on_delete=models.CASCADE) category= models.ForeignKey(Category, on_delete=models.CASCADE) subcategory = models.CharField(max_length=200, null=True, blank=True) and i have a view which recieve request and category.slug def category_list(request, slug): category = Category.objects.get(slug=slug) products = ProductFilter(request.GET, queryset=Products.objects.filter(category=category) return render(request, 'products/category_list.html', {"products":products, 'category': category}) when rednering i recive a QuerySet filtered to Category I want to send category.id to ProductsFilter and recive a dynamic Choices from database class ProductsFilter(django_filters.FilterSet): subcategory= django_filters.ChoiceFilter(lookup_expr='iexact', choices=TEST, required=False) class Meta: model = Products fields = { "subcategory", } Want to change choices=TEST to choices=list(SubCategory.objects.filter(category_id=category.id) Is this possible? -
Wagtail - Reference form from child page
I'm using the Wagtail Form Builder so that site implementers can extend to create their own FormPage type with their own site-specific templates. I want to render all form pages on a parent page; this includes all child page fields, such as the title, as well as the full child form. Ideally, the submit button should also act on a per-form basis. Here's what I've tried: <ul> {% for child in page.get_children %} <li> <h5 class=>{{ child.specific.title }}</h5> <div> {{ child.specific.intro|richtext }} <div id="form-holder"> <form action="{% child.pageurl page %}" method="POST"> {% csrf_token %} {{ child.specific.form.as_p }} <input type="submit"> </form> </div><!-- contact-form-holder--> </div> </li> {% endfor %} </ul> My form models are more or less as per the Form Builder documentation with a few extra fields: class FormField(AbstractFormField): db_table = 'form_field' page = ParentalKey('FormPage', related_name='form_fields') class FormPage(AbstractEmailForm): db_table = 'form_page' header = models.CharField(max_length=250) intro = RichTextField(blank=True) thank_you_text = RichTextField(blank=True) content_panels = AbstractEmailForm.content_panels + [ FormSubmissionsPanel(), FieldPanel('intro', classname="full"), FieldPanel('header'), InlinePanel('form_fields', label="Form fields"), FieldPanel('thank_you_text', classname="full"), MultiFieldPanel([ FieldRowPanel([ FieldPanel('from_address', classname="col6"), FieldPanel('to_address', classname="col6"), ]), FieldPanel('subject'), ], "Email"), ] I've found that I can render the child page fields such as title and intro if I use the .specific method. However, I can't seem to get … -
Django Many-to-Many query all() returns empty set
As per the Django docs I created a relationship between people and dates for a museum application. First the models (with unnecessary fields removed): class Agent(models.Model): name = models.CharField(max_length=255) dates = models.ManyToManyField(HistoricDate, 'date_for_agent', models.CASCADE, through='AgentDateType') . . . . class HistoricDate(models.Model): display = models.CharField(max_length=255, help_text='Textual representation of date') earliest = models.CharField(max_length=15, blank=True) earliest_accuracy = models.BooleanField(default=False, verbose_name="circa") latest = models.CharField(max_length=15, blank=True) latest_accuracy = models.BooleanField(default=False, verbose_name="circa") class AgentDateType(models.Model): datation = models.ForeignKey(HistoricDate, models.PROTECT) dated = models.ForeignKey(Agent, models.CASCADE) date_type = models.CharField(max_length=31, choices=date_types) . . . . Then the test: caesar = Agent.objects.create(name="Gaius Julius Caesar", name_type="personal", culture="Ancient Rome", display="Julius Caesar (Roman, 100–44 B.C.)") c_life = HistoricDate.objects.create(display="13 July 100–15 March 44 B.C.", earliest="-100-07-13", earliest_accuracy=False, latest="-44-03-15", latest_accuracy=False) c_act = HistoricDate.objects.create(display="60–44 B.C.", earliest="-60", earliest_accuracy=False, latest="-44-03-15", latest_accuracy=False) caesar_lives = AgentDateType.objects.create(dated=caesar, datation=c_life, source="Suetonius, Lives of the Caesars", date_type="life") caesar_acts = AgentDateType.objects.create(dated=caesar, datation=c_act, source="Livy", date_type="activity") Now the following queries return the expected sets: AgentDateType.objects.all() c_life.date_for_agent.all() c_act.date_for_agent.all() However, caesar.dates.all(), which should be the most straightforward, returns an empty set. What gives? -
Recombining multiple inheritance in Django models
Been using Django Polymorphic to help me with complex inheritance patterns in my Django model. I'm having an issue where I need to have a concrete base model (because it needs to have a ForeignKey to itself), and then have multiple models inherit from it, with eventually some model inheriting from multiple of those. The issue is that I'm getting a E005 error: app.NamedWeightedModel: (models.E005) The field 'basemodel_ptr' from parent model 'app.namedmodel' clashes with the field 'basemodel_ptr' from parent model 'app.massmodel'. The simple example that triggers this is shown below: from django.db import models from polymorphic.models import PolymorphicModel class BaseModel(PolymorphicModel): parent = models.ForeignKey('self') class NamedModel(BaseModel): name = models.CharField(max_length=32) class MassModel(BaseModel): weight = models.FloatField() class NamedWeightedModel(NamedModel, MassModel): pass Is there a better way to handle this? Or a standard approach? My real model is much more complex (an implementation of the UML spec), and I would like to be able to use multiple inheritance (ideally through Polymorphic) to make things easier. I've considered making any multiple inheritance models be single inheritance with all additional inherited models mapped as OneToOneFields, but this negates some of the nice things that polymorphic does. Any help you can provide would be greatly appreciated. -
executing a python script in PHP / Django
I made a python script (a URL extractor with selenium)(myurl.py) and I want to print the output URL into an HTML button. I'm using Django. -
mod_wsgi says python 2.7 is configured, code running in python 3.6
First I get this UnicodeError, which on my local machine runs as is should without any error. File "/home/malak/www/dev/shopvoice/dashboard/views/payment_view.py", line 126, in paypal_notify send_login_email_body = SEND_LOGIN_EMAIL_BODY % (user.email, random_pass) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 86: ordinal not in range(128) When I print out the type of the 3 variables I get user.email: <type 'unicode'> SEND_LOGIN_EMAIL_BODY: <type 'str'> random_pass: <type 'str'> First question: How is this possible in python3 ? When I rebuild this error on my local machine I get 3 variables of type string. Does something like "<type 'unicode'>" even exist in python 3? Obviously, what first comes to mind, does it run in Python 2 on my server? No! Here comes the weird part of the Story: This is the full Traceback of the error which obviously shows its python3.6: [Tue Feb 07 20:39:50.764173 2017] [:error] [pid 21179:tid 140085013579520] Traceback (most recent call last): [Tue Feb 07 20:39:50.764176 2017] [:error] [pid 21179:tid 140085013579520] File "/home/malak/www/dev/shopvoice/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 39, in inner [Tue Feb 07 20:39:50.764189 2017] [:error] [pid 21179:tid 140085013579520] response = get_response(request) subinterpreter. Returning 0. [Tue Feb 07 20:39:50.764192 2017] [:error] [pid 21179:tid 140085013579520] File "/home/malak/www/dev/shopvoice/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response [Tue Feb 07 20:39:50.764195 2017] … -
how to force which base file is used in template
I would like to add custom view/template into the admin which I succeeded . But my issue here is that when I extends the base.html it takes the one from my project template and I would like to be able to tell django to take the one from mezzanine admin (as it is a admin page and i would like to have the same look and feel as the rest of the admin) Any idea how to force the template resolution ? -
Making forms in Django 1.10 and received a CSRF verification failed. Request aborted
I'm having a difficult time getting the POST request to work using Django. I continuously get this 403 error message: Response Page because of request I'm trying to eventually make a search bar to search a database. On the index.html I have a search bar and then it takes a user input and sends the result to the search.html page. I haven't implemented the query search, I just want the user input to be displayed onto the search.html page using Django form functionality. I've been using this tutorial to make my first form: https://docs.djangoproject.com/en/1.10/topics/forms/ Below are the python & html scripts I created (Some of the variables are little different from the tutorials, but the concepts are the same) index.html <form action="search/" method="post"> <div class="search-bar"> <input name="search" type="text" class="form-control" placeholder="What are you interested in?" style="width:1000px"> &nbsp; <button type="submit" class="btn btn-default text-center" style="align-items: center;">Search</button> </div> </form> views.py from django.shortcuts import get_object_or_404, render, render_to_response from django.http import HttpResponseRedirect from django.views import generic from django.utils import timezone from .models import * from django.views.generic.base import TemplateView # View static pages easier, no list from .forms import NameForm from django.template import RequestContext from django.views.decorators.csrf import csrf_protect class IndexView(generic.base.TemplateView): template_name = 'ahawebsite/index.html' # class ContactView(generic.base.TemplateView): template_name … -
move a django project from "http://ip_address/" to "http://api.domain/
I was developing with just the IP Address, now I'm almost done, and I would move the whole project to "api.domain." I set this in the settings.py ALLOWED_HOSTS = ['api.*domain*.com'] But it's not enough I think. I cannot get any response.I followed this tutorial. It's the first time that I've to do this by myself. So, I don't have any idea. Maybe someone had the same problem or knows how to solve it. -
Django Rest Framework Not Returning Full JSON
I am having trouble retrieving the full JSON Response when executing a GET request on an API I am building with DRF. If I include pagination and retrieve, say, 100 results then I receive the full JSON Response. If I do not use pagination, and would like to retrieve a few thousand results, then the server simply cuts off at a seemingly random spot and does not return full JSON. For instance, it may return {"hi": "hel instead of returning {"hi":"hello"}. DRF reports this as a 200 response code, so it seems as though it executes properly. The code for my view looks like: class RepresentativeListView(generics.ListAPIView): queryset = models.Representative.objects.all() serializer_class = serializers.RepresentativeSerializer The code for my serializer looks like: class RepresentativeSerializer(serializers.ModelSerializer): class Meta: model = models.Representative fields = ( 'bioguide_id', 'stats', 'leadership_score', 'ideology_score', ) Could anyone understand why a full JSON response would not be coming through? -
Rest-auth still reports the error of "CSRF cookie not set", but I've set the csrf
I tried to implement an authentication(login/registration) function using Django rest-auth package. url(r'^rest-auth/', include('rest_auth.urls')), url(r'^rest-auth/registration/', include('rest_auth.registration.urls')), But when I tried to post the rest-auth urls, it give me the error: However, in Nodejs I've already set the csrf token using the 'csurf' package, const cookieParser = require('cookie-parser'); const csrf = require('csurf'); const app = new Express(); app.use(cookieParser()); app.use(csrf({ cookie: true })); Also, I can see the csrf token using Fiddler: Could you help me figure out where is the bug? -
Python Kivy: Refer to Label(Button) id (created in *.py file) via self.ids command
I am working with two files test.py test.kv The content of test.py is the following: import kivy kivy.require('1.0.0') from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.label import Label from kivy.uix.screenmanager import ScreenManager, Screen from kivy.lang import Builder Builder.load_file("test.kv") class MainScreen(Screen): def __init__(self, *args, **kwargs): super(MainScreen, self).__init__(*args, **kwargs) def printIds(self): print self.ids def printChildren(self): print self.ids.box.children for child in self.ids.box.children: print child.text, child.id def addButton(self): self.ids.box.add_widget(Button(text = "newly added Button", id = "test_button_id")) pass class MyApp(App): def __init__(self,*args, **kwargs): super(MyApp, self).__init__(*args, **kwargs) def build(self): app = MainScreen() return app if __name__ == '__main__': MyApp().run() The content of test.kv is: <MainScreen>: BoxLayout: orientation: "horizontal" id: box Label: text: "test label" id: test_label_id Button: text: "Print Children" on_release: root.printChildren() Button: text: "Print ids" on_release: root.printIds() Button: text: "Add Button" on_release: root.addButton() My problem is the following: I want to access the newly added Button (which will be added when calling the function addButton via pressing the Button Add Button) via the self.ids command in the python file. But when i do so (i.e. pressing the Button Print ids) it only shows the ids which i have assigned in the kivy file, namely: box (which is the id … -
Django: tweak AdminDateWidget
Django AdminDateWidget by default displays "today" shortcut between date field and calendar icon. I want to remove this shortcut. I guess, this should be done via overriding some "render" method or smth like this, but I failed to find where this shortcut is rendered. AdminDateWidget derives from DateInput, derived from DateTimeBaseInput, derived from Input. No sign of render process nowhere. Where all this stuff is rendered and how do you know that? :) -
Alternative to importing django models in __init__, but make them available in module namespace
I have a package which has several Classes: package __init__.py Class1.py Class2.py Class3.py In my __init__.py, I import the classes as follows: from .Class1 import Class1 from .Class2 import Class2 so that I can access those objects like this: import package class1 = package.Class1() class2 = package.Class2() instead of this: from package.Class1 import Class1 from package.Class2 import Class2 class1 = package.Class1() class2 = package.Class2() However, since django 1.9, models shouldn't be imported in the __init__ or the following exception is thrown: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I'm wondering if there's a way to reorganize this but maintain the same functionality? -
Pip Import Error No module named logging
Whenever I am running any command using pip, I am getting the following error. I have tried uninstalling python,pip and reinstalling them back again. I also used sudo apt-get autoremove and then updated and upgraded sudo apt-get update sudo apt-get upgrade And once again installed python and pip. I am still getting the same error whenever I run any command using pip. Traceback (most recent call last): File "/usr/bin/pip", line 9, in <module> from pip import main File "/home/shashank/.local/lib/python2.7/site-packages/pip/__init__.py", line 28, in <module> from pip.vcs import git, mercurial, subversion, bazaar # noqa File "/home/shashank/.local/lib/python2.7/site-packages/pip/vcs/mercurial.py", line 9, in <module> from pip.download import path_to_url File "/home/shashank/.local/lib/python2.7/site-packages/pip/download.py", line 34, in <module> from pip.utils.logging import indent_log ImportError: No module named logging Can anybody suggest a solution? -
which query to be used in data base
For the quiz app, I am having the following model class Question(models.Model): question_id=models.IntegerField(default=0) question_text=models.CharField(max_length=1000) def __str__(self): return self.question_text class Options(models.Model): question=models.ForeignKey(Question,on_delete=models.CASCADE) options=models.CharField(max_length=500) is_answer=models.BooleanField(default=False) def __str__(self): return self.options Only one option for each question is Set to True. Which is the best query here? I am using Sqlite. Thank You. -
nginx app in docker not working on remote machine
I see something really weird happening, with nginx (dockerized). Here's my conf for the same : upstream web{ ip_hash; server 127.0.0.1:8000; } server { listen 8000; server_name localhost; location /web/ { autoindex on; alias /src/reporting/web/; } location / { proxy_pass http://web/; } } and the docker-compose.yml file : version: '2' services: nginx: image: nginx:1.10.3 container_name: ng01 ports: - "8000:8000" volumes: - ./src:/src - ./config/nginx:/etc/nginx/conf.d - /web:/static depends_on: - nafiri nafiri: build: . container_name: dg01 command: bash -c "python manage.py makemigrations && python manage.py migrate && gunicorn nafiri.wsgi -b 0.0.0.0:8000" volumes: - ./src:/src - /web:/static expose: - "8000" This works totally fine on local machine / host,but if I have to deploy it on another machine/server, it gives vivid errors : 1. e.g recv() failed connection rejected by peer 2. docker log simply wont update after docker-compose start / stop. I am totally stuck and cant debug where the fault tries, shooting in the dark I am trying hit-n-trial on replacing 127.0.0.1 with server ip etc. but all in vain. Thanks in advance! -
Django trigger signal on bulk update
I'm aware that signals aren't triggered for bulk updates, however, I need this behaviour. I'm wondering which of these two ways is more efficient: qs = MyObject.objects.all() Do a bulk update, then in a loop manually trigger the signal for each instance: qs.update(active=True) for instance in qs: post_save.send(sender=MyObject, instance=instance) Loop the qs and call save on each instance: for instance in qs: instance.active = True instance.save(update_fields=['active']) -
Blockquote not working on blogsite using markup and pagedown
I'm building a website using semantic ui with Django 1.10. I have installed Django pagedown to create a widget like that on stackoverflow to edit blog post and ive also install Django markdown deux to render the blog post in html format instead of raw text format. But for some reason the blockquote tag is not working...it shows fine in preview but does not render on the website when posted...all other tags including heading tags, link tags, image tags and the likes works perfectly but blockquote fails to render. Can anyone please suggest me a solution. -
Django strange behavior: infinite loading all views, but django is working
2 years experience with Django (1.8.12, Ubuntu 14.04) and faced this problem 1st time. After some time (not sure why) i come to my site and tried to load some page: result is infinite loading all views including admin panel (cannot login) and all external views. Browser tab shows loading circle and never loads. Super strange is the following: i tried add\remove some apps from settings.py, make mistakes in my code, add\erase some imports and when i do this Django start working normally: it shows me standard error page (yellow-gray with traceback). Then i go to code and fix mistake - infinite loading arise again. Once today i was able to get my view working - it is loaded normally (simple view with form). But is is impossible to reload this view second time - it loads once and after that i got infinite loading again all other tries. In Apache error.log i see: [Tue Feb 07 19:50:23.776657 2017] [core:warn] [pid 16963:tid 139669519046528] AH00045: child process 16966 still did not exit, sending a SIGTERM [Tue Feb 07 19:50:23.776852 2017] [core:warn] [pid 16963:tid 139669519046528] AH00045: child process 16967 still did not exit, sending a SIGTERM [Tue Feb 07 19:50:25.779159 2017] [core:warn] … -
django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username
I have a Organisation class with the following properties: class Organisation(models.Model): user = models.OneToOneField(User, null=True) phoneNumber = models.CharField(max_length=12) description = models.CharField(max_length=1024) image = models.ImageField(upload_to='organisation_image') category = models.ForeignKey("Category") subscribedVolunteers = models.ManyToManyField(Volunteer) def __unicode__ (self): return self.name I want to populate the database with this file: def populate(): organisations = [ {"first_name":"Concrete Garden","description":description, "email":"info@concretegarden.org.uk", "password":"cgarden", "username":"cgarden", "phoneNumber":"0141 237 9144", "category":categories_arr[0]} } organisations_arr = [] for org in organisations: organisations_arr.append(add_organisation(org)) def add_organisation(org): print(org["username"]) #ERROR HERE - when trying to create user object u = User.objects.create_user(username=org["username"], email=org["email"], first_name=org["first_name"],last_name=org["first_name"], password=org["password"]) u.save() c = Organisation.objects.get_or_create(user=u,phoneNumber=org["phoneNumber"],description=org["description"],category=org["category"])[0] c.save() return c if __name__ == '__main__': print("Starting population script...") populate() Any comment or suggestion is greatly appreciated. Thank you. -
performing create on related object in django stops code execution
I am trying to create an object using the reverse side of the relation. (the many side). I am encountering an issue that my code pretty much stops the moment I perform the actual create, it fails, but silently. Placing any statements after are not executed. The entire program does not fail or show any errors. Without any error statements or exceptions showing stacktraces, I cannot figure out what is actually wrong here. Here is the aforementioned statement: # Class method on Pot object def create_static_notification(self, interval, duration, value_exceeded, is_high, measurement_type, level): self.staticnotification_set.create( interval=interval, duration=duration, value_exceeded=value_exceeded, is_high=is_high, measurement_type=measurement_type, level=level, ) print 'I will never be printed ):' The model it is trying to create an instance of is this: class StaticNotification(models.Model): registered_on = models.DateTimeField(default=timezone.now) dismissed_on = models.DateTimeField(blank=True, null=True) is_relevant = models.BooleanField(default=True) interval = models.DurationField() duration = models.DurationField() value_exceeded = models.FloatField() is_high = models.BooleanField(default=True) measurement_type = models.ForeignKey(StaticParameterType, on_delete=models.CASCADE) level = models.ForeignKey(ReportLevel, on_delete=models.CASCADE) pot = models.ForeignKey(Pot, on_delete=models.CASCADE) I have validated that all the fields that have to be there, are there. For extra context: This code is run through a custom django command which runs on the MQTT protocol. Subsequent calls from MQTT are actually still working, the single call stops. Next … -
Saving a local datetime offset the time by 4 minutes
I'm trying to modify a datetime based on a timezone on save and on load the following way: An input datetime, along with a input timezone are sent to the server and the server should update the datetime to reflect the timezone. So when its save in the database (PostregSQL), the UTC time is saved (after the offset caused by the timezone, of course). To reflect this here's a simpler example that fails in the same way: Some imports: >>> import datetime >>> import pytz >>> from apps.myapp.models import Project Creating the two inputs: >>> input_date = timezone.now() >>> input_date datetime.datetime(2017, 2, 7, 16, 7, 14, 377429, tzinfo=<UTC>) >>> current_tz = pytz.timezone('America/New_York') >>> current_tz <DstTzInfo 'America/New_York' LMT-1 day, 19:04:00 STD> As you can see, the timezone is not 5h (24 - 19 = 5), but 4h56. At this stage I'm thinking that's OK, it may be related to the Daylight Saving Time. Now I'm replacing the timezone on the input date: >>> input_date = input_date.replace(tzinfo=current_tz) >>> input_date datetime.datetime(2017, 2, 7, 16, 7, 14, 377429, tzinfo=<DstTzInfo 'America/New_York' LMT-1 day, 19:04:00 STD>) As expected, the time hasn't changed, but the timezone has, which is fine. I'll assign this value to a project …