Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using managers in django for dynamic filtering
from django.db import models # Create your models here. from multiselectfield import MultiSelectField from account.models import CustomUser class Feature(models.Model): feature = models.CharField(max_length = 100) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) by = models.ForeignKey(CustomUser) def __str__(self): return self.feature class FeatureValue(models.Model): feature = models.ForeignKey(Feature,on_delete = models.CASCADE) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) by = models.ForeignKey(CustomUser) value = models.CharField(max_length = 100,blank = False,null = False) class Meta: unique_together = ['feature','value'] def makechoices(val): arr = [] k = 0 while k<len(val): tup = (val[k].feature,val[k].feature) arr.append(tup) k = k+1 ''' class Scenario(models.Model): created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) by = models.ForeignKey(CustomUser) q = Feature.objects.all() i = 0 while(i<len(q)): a = q[i].feature val = FeatureValue.objects.filter(feature = q[i]) b = a +'choices' b = makechoices(val) Scenario.add_to_class(a, MultiSelectField(max_length=100,choices = b,default = 'NONE' )) i = i+1 ''' This is models.py file. I want to add all the features that are added as fields to scenario and all the feature values as multiple option select choices to those features. How to add them dynamically? Manager method can't change .filter attribute dynamically so unable to use that. -
How to remove Operational Error in Django Models?
I am making a simple blogger website in Django. whenever I run the command Blogs.objects.all() in python shell it gives me OperationalError: no such column: Blogs_blogs.id error {# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models import datetime class Login(models.Model): email = models.EmailField() password = models.TextField(max_length=20) def __str__(self): return self.email class User(models.Model): fullname = models.CharField(max_length=30) description = models.TextField(max_length=50) state = models.CharField(max_length=30) city = models.CharField(max_length=30) country = models.CharField(max_length=30) email = models.EmailField() login_id = models.ForeignKey(Login) def __str__(self): return "%s %s %s %s %s " % (self.fullname, self.city, self.country, self.country, self.login_id) class Blogs(models.Model): title = models.CharField(max_length=100) content = models.TextField(max_length=10000) date = models.DateField("DATE", default=datetime.date.today) username = models.ForeignKey(User) def __str__(self): return " %s %s %s %s " % (self.title, self.content, self.date, self.username.fullname) -
How to add travis environment variables to Tox
My project uses environment variables and I am trying to use them in the Tox. According to https://stackoverflow.com/a/37522926/3782963 I have to set passenv in the tox.ini, but when I do that the, I get an error as Collecting django<1.10,>=1.9 Using cached Django-1.9.13-py2.py3-none-any.whl Collecting AUTHY_API Could not find a version that satisfies the requirement AUTHY_API (from versions: ) No matching distribution found for AUTHY_API It looks like the Tox thinks that AUTHY_API is a distribution file whereas it is actually an environment variable. My configurations are: .travis.yml: language: python python: - 3.5 - 3.6 services: postgresql addons: postgresql: "9.4" before_script: - psql -c "CREATE DATABASE mydb;" -U postgres branches: only: - master - v3 install: - pip install tox-travis script: - tox env: - TOXENV=django19 - TOXENV=django110 - TOXENV=coverage notifications: email: false tox.ini: [tox] envlist = django19, django110 skipsdist = True [testenv] commands = pytest setenv = DJANGO_SETTINGS_MODULE=gollahalli_com.settings PYTHONPATH={toxinidir} [base] deps = -r{toxinidir}/requirements-testing.txt passenv = AUTHY_API cloudinary_api cloudinary_api_secret DEBUG SECRET_KEY GITHUB_KEY [testenv:django19] deps = django>=1.9, <1.10 {[base]deps} {[base]passenv} [testenv:django110] deps = django>=1.10, <1.11 {[base]deps} {[base]passenv} [testenv:coverage] commands = ; coverage run --branch --omit={envdir}/*,test_app/*.py,*/migrations/*.py {envbindir}/manage.py test pytest --cov=./ codecov deps = {[testenv:django110]deps} {[base]passenv} I am not sure what is wrong here. Help! -
Django and Spring running on the same tomcat server
I am assigned to make new feature for a web application written in Spring. My only problem is that it's not maintainable and takes a lot of time to deliver a server if I write it in spring. What I want to do is make a separate server-side application written in django and call it whenever it will perform the task assigned to it and go back to the old Spring application when finished. Is there any way to do this? -
NoReverseMatch django - not a valid view function or pattern
Currently using Django 1.11. I get an exception of Reverse for 'audition_details' not found. 'audition_details' is not a valid view function or pattern name. Request Method: GET Request URL: http://localhost:8000/library/book/c7311ecf-eba7-4e9d-8b1a-8ba4e075245a/ Django Version: 1.11 Exception Type: NoReverseMatch I want to use the get_absolute_url from my Model in the details page to go to a Update page. When I take out the reference to the .id and use the get_absolute_url. I checked to see the name "book_details" is referenced properly. I can go to the page and have books details render properly. In the admin console of Django, the "view on site" button also does not render properly it shows this localhost:8000/admin/r/13/c7311ecf-eba7-4e9d-8b1a-8ba4e075245a/ so it does not get the library/books either current <a href =" {{ book.id }}/update">Update</a> desired <a href =" {{ book.get_absolute_url }}/update">Update</a> Where have I mistyped for this to not work? Setup in files: Yes, I do have UUID as the primary key. In views.py class BookDetailsView(generic.DetailView): """ Generic class-based detail view for a Book. """ model = Book in urls.py url(r'^book/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$', views.BookDetailsView.as_view(), name='book_details'), url(r'^audition/(?P[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/update/$', views.BookUpdate.as_view(), name='book_update'), in models.py class Book(models.Model): def get_absolute_url(self): """Returns the URL of the book for details""" return reverse('book_details', args=[str(self.id)]) -
Django queryset for list item
I am still fairly new to django and I ran into a problem which I am having a hard time figuring out even with using google or maybe I am not seeing the solution. So I have a model named movieTitles like so: class movieTitle(models.Model): title = models.Charfield(max_length=50) image = models.URLField(max_length=100) description = models.TextField() year = models.PositiveSmallIntegerField() director = models.Charfield(max_length=50) Then I have my view as so: from Movie.models import movieTitles def movieListView(request): movie = movieTitle.objects.all() return render(request, 'index.html', {'movies':movie}) and my html as so: <body> {% for info in movies %} <a href="#">{{info.title}}</a> {% endfor %} </body> What I want it to do is once user goes to the movie list and they decide to click on a certain movie, how can I take the user to another html page which will show the info.image, info.description, info.year, and info.director belonging to the movie they decided to click on. I know how to write the template and all that but what im confused on is how can I write the template using {{info.???}} and not having to create a template for every movie to link to but instead use the previous template in which the user chose a movie to β¦ -
Logging filter not returning anything
I am trying to setup Django logging to log deprecation warnings. I normally wouldn't have a formatter like this or output it to console, that is just to test and show it is not working. Here is my code: def is_deprecated(record): if record.exc_info: exc_type, exc_value = record.exc_info[:2] print(exc_value) if isinstance(exc_value, DeprecationWarning) or isinstance(exc_value, PendingDeprecationWarning): return True return False LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'stuff': { 'format': 'This works!' } }, 'filters': { 'is_deprecated': { '()': 'django.utils.log.CallbackFilter', 'callback': is_deprecated, }, }, 'handlers': { 'console': { 'filters': ['is_deprecated'], 'class': 'logging.StreamHandler', 'formatter': 'stuff', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': 'INFO', }, }, } It should output "This works!" when it hits a deprecation warning however it won't. I am running python with these alerts on python -Wd So I can see the regular Django alert but I can't get the logger to detect them. -
SSL error in send mail
I try send meil drom django/ But Got error [SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:661) That my code: DEFAULT_FROM_EMAIL = 'info@xxxxxxx' html = render_to_string('email/html/new_order.html', {'order': self, 'image_code': True}) email = EmailMultiAlternatives( 'Greetings from Discovery Russia', html, DEFAULT_FROM_EMAIL, to=[self.user_email, 'info@.xxxxxx']) email.attach_alternative(html, "text/html") email.mixed_subtype = 'related' try: email.send() except SMTPRecipientsRefused: pass How i can fix thet? -
How to the original manager in Django model?
I am trying to use the original manager of a model A. But I find that some teammate has changed objects to a custom manager, such as: class A(models.Model): objects = SomeManager() ... In this case, how can I get the original manager without changing the code of the model? -
python nested dict behave like json object
I searched around for a couple hours trying to find a solution to this but haven't been able. I'm trying to nest dictionaries in python, in a django app, and would like to somehow mirror the behavior of more usable json objects. The goal is something like this: { key: {[],str} } in use, something like this: { page-title1: {[tag, tag, tag], url}, page-title2: {[tag, tag], url}, page-title3: {[tag, tag, tag, tag], url} } And here is what I've tried so far: def proj_pages(): d = {} e = {} pages = [] pagetags = [] pagephoto = [] cleantags = "" cleanurl = "" sections = ProjectPage.objects.all() for section in sections: pages.append(str(section).replace(" ", "")) for x in pages: d[x] = x for tag in section.tags.all(): pagetags.append(str(tag)) cleantags = " ".join(map(str, pagetags)) e[str(cleantags)] = str(cleantags) for img in section.topphoto.url[22:]: pagephoto.append(str(img)) cleanurl = ''.join(pagephoto) e[str(cleantags)] = cleanurl d[x] = e Which outputs: {'Projects/06': {'in-progress': 'in-progress', 'in-progress Design': 'in-progress Design', 'in-progress Design Build': 'projects/06/Anagram.jpg'}, 'Projects/05': 'Projects/05'} This is close as it uses the correct key on the first level of the dict, but the behavior for the second level is strange -- adding each individual tag as the key and value, i.e. β¦ -
Recurse over a list of querysets of unknown depth
I have a requirement where I need to be able to create multiple nodes in an org-chart type situation. The requirements call for a "child" node being able to have multiple parents, so existing solutions like mptt or treebeard are out unfortunately. The requirements also state that I should be to access a Node at any level and be able to do business stuff based on its children. Here is my attempt: class Division(models.Model): name = models.CharField( max_length=250, ) children_set = models.ManyToManyField( to='organisations.Division', related_name='parent_set', ) def _flatten_children(self, el): for item in el.children_set.all(): if bool(item.children_set.all()): yield from self._flatten_children(item) else: yield item def all_children(self): return list(self._flatten_children(self)) def add_child(self, child): self.children_set.add(child) When calling this, I only seem to be getting the queryset of the "last" child. Any help would be much appreciated. # test setup instance = DivisionFactory() child1 = DivisionFactory() child2 = DivisionFactory() child3 = DivisionFactory() child4 = DivisionFactory() instance.add_child(child1) child1.add_child(child2) child2.add_child(child3) child2.add_child(child4) Output: In [19]: instance.all_children() Out[19]: [<Division: Officia dolores illo.>, <Division: Vitae sapiente numquam.>] Notice how only the two child nodes for child2 have been returned, and both child1 and child2 have not been included in the returned list. -
Invalid grant when trying to connect to google cloud sql with django
I've been following the GAE tutorial for setting up a django project to run on app engine. I've finally gotten it to successfully run to makemigrations for my project, but I get a connection error in my google cloud sql proxy: 2017/06/25 15:12:07 New connection for "[MY_CONNECTION_NAME]" 2017/06/25 15:12:08 couldn't connect to "[CONNECTION_NAME]": Post https://www.googleapis.com/sql/v1beta4/projects/project-id/instances/projectname/createEphemeral?alt=json: oauth2: cannot fetch token: 400 Bad Request Response: { "error" : "invalid_grant" } I'm not sure what's causing this, so I'll take any help??? -
django modelform not updating instance
I have a running Django application in production,a model instance is not updating data when user tries to edit using ModelForm, but it updates when I save it from shell, also this issue is occurring only on that particular instance, other instance are just working fine -
django urllib HTTPS request: <urlopen error unknown url type: https>
i get error when using urllib python 2.6 django 1.4.1 when i using python > import ssl get Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/xxx/lib/python2.6/ssl.py", line 60, in <module> import _ssl # if we can't import it, let the error propagate ImportError: libssl.so.6: cannot open shared object file: No such file or directory i have openssl installed openssl version -v OpenSSL 1.0.1e-fips 11 Feb 2013 -
installing ta-lib for python bitnami linux
I tried installing TA-lib with the following command on an django instance: pip install TA-Lib and i got the following: "/opt/bitnami/python/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-build-4F9CVi/TA-Lib/setup.py';exec(compile(getattr(tokenize, 'open', open)(file).read().replace('\r\n', '\n'), file, 'exec'))" install --record /tmp/pip-4y2oMv-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-4F9CVi/TA-Lib/ not sure what i can do. Has anyone met with a similar problem before? Thanks -
How to get request from Views.py Django - rest_framework
I'm trying to understand how can I read request after POST or GET method in views. I need request.user and request.headers. Here is how it looks now in views.py. Can you help me to fix this and have a minute to explain what am I doing wrong? views.py from rest_framework import viewsets from rest_framework.response import Response from rest_framework import status from api.models import UploadImage from api.serializers import UploadedImageSerializer class UploadViewSet(viewsets.ModelViewSet): """API endpoint""" queryset = UploadImage.objects.all() serializer_class = UploadedImageSerializer def get_object(request): if request.method == 'POST': print ("do some stuff") status_check = MyFunction() if status_check == 'Wrong': return Response(status.HTTP_400_BAD_REQUEST) if request.method == 'GET': print("do some stuff") -
Using variable instead of field name in Django query comparions
Let say I have the following query: query_result = Mymodel.objects.values('price').filter(price__gte=0) If I want to generalize the query and put it in a function I could replace 'price' with a variable: def price_query(column_name): column_name = 'price' query_result = Mymodel.objects.values(column_name).filter(column_name__gte=0) return query_result The first replacement of 'price' with column_name works fine but how do I use the comparison __gte with a variable instead of the field name. Any help is much appreciated. -
Unique Combination of ManyToMany
I'm trying to create a unique Availability status for Player on given Hour. Here goes the code: class Player(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) class Hour(models.Model): date = models.DateTimeField() players = models.ManyToManyField(Player, blank=True, through='Availability') class Availability(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE) hour = models.ForeignKey(Hour, on_delete=models.CASCADE) available = models.BooleanField() My problem is that it's currently possible to add same Availability few times - I want to programatically limit it to just one per combination. Thanks in advance! -
Accessing a html tag attribute in Django template expression
There is a html element: <input type="text" id="someInput" name="someInput"></input> It's value is set in JavaScript: var tbIndx = 10; document.getElementById("someInput").value = tbIndx; Now,I want to construct a Django for-loop which would use the value of the html tag described above.Something like this: {% for i in val %}//val is the innerHTML of the input box described above. //code {% endfor %} Can we access a value like this in a Django template?Please suggest some methods for achieving this functionality. Thanks -
Change django.po default description
At the very beginning of many django.po files I see around in open source projects, I have noticed that they contain the following header: # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. Here's an example of where these django.po are often located. locale/ βββ bg βββ LC_MESSAGES β βββ django.mo β βββ django.po βββ translations.json I know that the creation of these files involve many different tools (like Transifex or Django's manage.py), but I don't know in which link of the chain is this header inserted. How can you change these files' generation process, to at replace the placeholders with the actual title, copyright holder, etc? -
How to use timedelta with timezone.now?
In Django models, How to increment the date field using timezone.now ? working: end_date = models.DateTimeField(default=timezone.now() + timezone.timedelta(days=365)) Not Working end_date = models.DateTimeField(default=timezone.now + timezone.timedelta(days=365)) I think timezone.now is a function which runs every time when the object is created. so that error occurs. -
How do I fix this django error:'User' object has no attribute 'backend'
There were a couple of other similar questions with answer but none of them fixed my problem. I am getting 'You have multiple authentication backends configured and therefore must provide the backend argument or set the backend attribute on the user' every time I try to create a new user using by sign up in Django. Here is my view: def signupUser(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save(commit=False) username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) form.save() user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) I had added user.backend = 'django.contrib.auth.backends.ModelBackend' in hopes of fixing the problem, but it did nothing. My forms.py: class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') password1=forms.CharField(help_text='Your password cant be too similar to your other personal information. Your password must contain at least 8 characters. Your password cant be a commonly used password. Your password cant be entirely numeric.', widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] Thank you for your time :) -
The posts are not displaying which are saved in database in django
i am new to django and i am having trouble with retrieving my allpost (which we saved in database) in 'allpost' view that i have created in my 'blog' project. here are the codes- views.py- from django.shortcuts import render,redirect from . models import Post from django.utils import timezone from . forms import PostForm def blog(request): return render(request,'blog/blogpage.html') def allpost(request): post=Post.objects.all() return render(request, 'blog/allpostpage.html', {'post': Post}) # the posts are not displaying in this template # def form(request): if request.method=='POST': form=PostForm(request.POST) if form.is_valid(): post=form.save(commit=False) post.published_date=timezone.now() post.save() return redirect('allpost') else: form=PostForm() return render(request,'blog/formpage.html',{'form':form}) urls.py- from django.conf.urls import url from . import views urlpatterns=[ url(r'^$',views.blog,name="blog"), url(r'^form$',views.form,name="form"), url(r'^allpost$',views.allpost,name="allpost"), ] formpage.html- {% extends 'blog/base.html' %} <head> <title>form</title> </head> <body> {% block content %} <form method="POST" class="post-form"> {% csrf_token %} {{form.as_p}} <button type="submit" class="save-btn btn-default">save</button> </form> {% endblock %} </body> </html> allpostpage.html- {% extends 'blog/base.html' %} {% block content %} {% for post in post %} {{post.title}} {% endfor %} {% endblock %} models.py- from django.db import models from django.utils import timezone class Post(models.Model): title=models.CharField(max_length=200) content=models.TextField(max_length=500) published_date=models.DateTimeField(blank=True) def publish_date(self): Post.published_date=timezone.now() Post.save() def __str__(self): return self.title forms.py- from django import forms from . models import Post class PostForm(forms.ModelForm): class Meta: model=Post fields=('title','content') those are my codes. please β¦ -
What is the context variable for detailview class in Django?
Django's generic view class ListView has object_list as context variable, what is the context variable for the DetailView? -
How to make form validations in Django
I'm trying to make form validations so that certain fields only accept certain types of inputs, such as names only accept letters and phone numbers only accept 10 numbers. I tried making a validation for the first name, as shown below: #forms.py class StudentForm(forms.ModelForm): # STEP 1 FORM student_id = forms.CharField(max_length=128, label="Student ID") first_name = forms.CharField(max_length=128, label="First Name", widget=forms.TextInput(attrs={'class': 'form-control'})) last_name = forms.CharField(max_length=128, label="Last Name") ssn = USSocialSecurityNumberField(widget=forms.TextInput(attrs={'class': 'form-control'}), label="SSN", help_text="Format: xxx-xx-xxxx") gender = forms.ChoiceField(widget=forms.Select(attrs={'class': 'form-control'}), label="Gender", choices=GENDER_CHOICES) dob = forms.DateField(widget=forms.DateInput(attrs={'class': 'form-control'}), label="Date of birth", help_text="Format: yyyy-mm-dd") contact_number = forms.CharField(max_length=128, label="Contact number") address = forms.CharField(max_length=128, label="Address") city = forms.CharField(max_length=128, label="City") state = forms.ChoiceField(choices=STATE_CHOICES, initial="NJ", label="State") zipcode = USZipCodeField(label="Zipcode") country = forms.ChoiceField(choices=countries, label="Country", initial="US") home_phone = forms.CharField(max_length=128, label="Home phone") cell_phone = forms.CharField(max_length=128, label="Cell phone") email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'}), max_length=254, validators=[validate_email], label="Email") background = forms.ChoiceField(choices=BACKGROUND_CHOICES, label="Background") location = forms.ChoiceField(choices=LOCATION_CHOICES, initial="south_plainfield", label="Location") workforce = forms.ChoiceField(choices=WORKFORCE_CHOICES, initial="--", label="Workforce") source = forms.ChoiceField(choices=SOURCE_CHOICES, initial="individual", label="Source") refer_by = forms.ChoiceField(choices=REFER_BY_CHOICES, initial="no refer", label="Refer by") last_status = forms.ChoiceField(choices=LAST_STATUS_CHOICES, initial="followup", label="Last status") newsletter = forms.BooleanField(widget=forms.CheckboxInput(), label="Newsletter", required=False) created_by = forms.CharField(max_length=128, label="Created by") date = forms.DateField(widget=forms.DateInput(attrs={'class': 'form-control'}), label="Date", help_text="Format: yyyy-mm-dd") notes = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control'}), required=False, label="notes", help_text="less than 1000 characters") def clean(self): cleaned_data = self.cleaned_data first_name = cleaned_data.get('first_name') if first_name.isalpha == β¦