Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django. How to make model choices from another model
I am trying to make migrations for my models: from django.db import models TAKEN = ( (True, 'Yes'), (False, 'No') ) class Room(models.Model): name = models.CharField(max_length=32) number = models.IntegerField() taken = models.BooleanField(choices=TAKEN) description = models.CharField(max_length=128) ROOMS_CHOICE = (Room.objects.filter(taken=False)) class Reservation(models.Model): date = models.DateField() hours = models.IntegerField() choice = models.OneToOneField(Room, on_delete=models.CASCADE, choices=ROOMS_CHOICE) forms for the models: from django import forms from .models import TAKEN, ROOMS_CHOICE class NewRoomForm(forms.Form): name = forms.CharField(label='Name', max_length=32) number = forms.IntegerField(label='Room Number') taken = forms.ChoiceField(choices=TAKEN, label='Taken', widget=forms.Select) description = forms.CharField(label='Description', widget=forms.Textarea) class ReservationForm(forms.Form): date = forms.DateField(label='Date', widget=forms.SelectDateWidget) hours = forms.IntegerField(label='hours', max_value=8) choice = forms.ChoiceField(choices=ROOMS_CHOICE, label='room', widget=forms.Select) When I try to make migrations, an ProgrammingError appears: django.db.utils.ProgrammingError: (1146, "Table 'conference_room.conference_room' doesn't exist") I try to make a view where user can book a conference room from a available rooms (those that are not occupied - taken=False). I assume I made some mistakes during building OneToOne relation and writing choices based on the Room model, and that is why the error appeared. How can I rewrite my models and forms? -
Django-tables2 - how to set default value for all columns?
Django-tables2 renders double dash in case there is no value in the cell. We can change it explicitely specifying default attribute for every column. Can I do that for all columns at once? Of course I tried to override __init__ method but Table.columns can't be modified and Table.base_columns seems to cause the same problem. def __init__(self,*args,**kwargs): for name,col in self.base_columns.items(): col.default = '' super(DopytyTable,self).__init__(*args,**kwargs) raises col.default = '' AttributeError: can't set attribute -
TypeError: All provided fields *must* be text when bytes mode is off; got 'CN=XXX,CN=Users,DC=domain,DC=com'
I am trying to create a new Model using the django-ldapdb library. When I try to run python manage.py makemigrations, it tells me that the bytes mode is off. I do not really know where this is and how to activate it. This is my model: class LdapUser(ldapdb.models.Model): base_dn = "CN=XXX,CN=Users,DC=domain,DC=com" object_classes = ['posixAccount', 'shadowAccount', 'inetOrgPerson'] # inetOrgPerson first_name = CharField(db_column='givenName', blank=True) last_name = CharField(db_column='sn', blank=True) email = CharField(db_column='mail', blank=True) salutation = CharField(db_column='title', blank=True) phone = CharField(db_column='telephoneNumber', blank=True) mobile_phone = CharField(db_column='mobile', blank=True) I looked it up, but could not find anything helpful. I hope someone can help me. Thanks in advance. -
NotImplementedError: Only tempfile.TemporaryFile is available for use
I'm using django and Google App Engine. I can't determine where's the error came from because if I'm using it on local my site is functioning. After I deployed it on GAE it works fine but when using googleadwords api this error comes: NotImplementedError: Only tempfile.TemporaryFile is available for use at PlaceHolder (/base/alloc/tmpfs/dynamic_runtimes/python27/a7637d5531ec9deb_unzipped/python27_dist/lib/python2.7/tempfile.py:45) at __init__ (/base/data/home/apps/f~xxxx/20180320t181216.408435502723573470/lib/suds/cache.py:115) at __init__ (/base/data/home/apps/f~xxxx/20180320t181216.408435502723573470/lib/suds/client.py:112) at GetService (/base/data/home/apps/f~xxxx/20180320t181216.408435502723573470/lib/googleads/adwords.py:459) at post (/base/data/home/apps/f~xxxx/20180320t181216.408435502723573470/ksvt/views.py:47) at dispatch (/base/data/home/apps/f~xxxx/20180320t181216.408435502723573470/lib/django/views/generic/base.py:88) at view (/base/data/home/apps/f~xxxx/20180320t181216.408435502723573470/lib/django/views/generic/base.py:68) at _get_response (/base/data/home/apps/f~xxxx/20180320t181216.408435502723573470/lib/django/core/handlers/base.py:185) at _get_response (/base/data/home/apps/f~xxxx/20180320t181216.408435502723573470/lib/django/core/handlers/base.py:187) at inner (/base/data/home/apps/f~xxxx/20180320t181216.408435502723573470/lib/django/core/handlers/exception.py:41) Can someone explain what is the meaning of this error? Thanks! -
Coomon authentication for application
can i use common authentication(signin, signup) for both django and python cgi.Actually one application is running on python cgi and another application is running on django.is it possible to use common authentication for both application? how? Thanks -
Limit Foreign Key Choices in Django Admin
Consider an app where people can participate in a contest. I have a Contest and ContestProblem Model ready. I want to have following features for the contest: A contest can have many problems A problem can not appear in more than one contest In my models.py, I have: class ProblemsInContest(CreateUpdateDateModel): contest = models.ForeignKey(Contest) problem = models.ForeignKey(ContestProblem) class Meta: verbose_name = "Problem in Contest" verbose_name_plural = "Problems in Contest" def __str__(self): return "{problem}".format(problem=self.problem) In my admin.py, I have: class ContestProblemInline(admin.TabularInline): model = ProblemsInContest extra = 1 class ContestAdmin(admin.ModelAdmin): readonly_fields = ['contest_image'] inlines = [ ContestProblemInline, ] I am using Django Admin to add problems to a contest. The problem being the fact that in the Problem dropdown, it shows me all the ContestProblem but I want to limit it to only those ContestProblem which does not appear in any other contest. Any hints or advice or references to achieve the desired results will be highly appreciated. -
How to modify autogenerated Django models?
I am using django 1.11. I have generated models.py using inspectdb. I followed makemigrations and migrate, which was successfully done. By default after inspectdb, managed is set to False, which I've changed to True (or can be removed). It looked something like this, before making the change: class TableName(models.Model): id = models.AutoField(primary_key=True) field_one = models.IntegerField(blank=True, null=True) field_two = models.IntegerField(blank=True, null=True) field_three = models.CharField(max_length=10) field_four = models.IntegerField(blank=True, null=True) class Meta: managed = True db_table = 'table_name' After the manual change in models.py : class TableName(models.Model): id = models.AutoField(primary_key=True) field_one = models.ForeignKey(TableXYZ, on_delete=models.CASCADE) field_two = models.ForeignKey(TableABC,on_delete=models.CASCADE) field_three = models.CharField(max_length=10) field_four = models.BooleanField() class Meta: managed = True db_table = 'table_name' Now when i followed makemigrations and migrate, no changes were detected or applied. I want the changes to reflect, but it is not detecting any change in models. This doesn't happen when we manually write the models, as it is happening when generated with inspectdb. Please help. -
Python does not work anymore after update of django and python update
I have python code for my website. python --version Python 2.7.13 ./manage.py --version 1.11.11 Everything was working well before an update of my server. One function have to read into a file where I have something like: 1,"TY - JOUR|T1 - BLABLABLA|.........|AU - name1|AU - name2|......" I use the following python code: from django.db import models ..... class Sources(models.Model): sourceid = models.IntegerField(primary_key=True) ris = models.TextField() class Meta: db_table = u'sources' def extractChain(self,tokens,st): for token in tokens: if(token.startswith(st)): break result = token[5:] if(st == "TY"): result={ "JOUR": "journal", "BOOK": "book", "":"" }[result] return result def author(self,tokens,st): a=[] for token in tokens: if(token.startswith(st)): a.append(token[5:]) return a def extractRisVal(self,st): tokens = self.ris.split("|") result={ "TY": self.extractChain(tokens,st), "T1": self.extractChain(tokens,st), "JO": self.extractChain(tokens,st), "VL": self.extractChain(tokens,st), "IS": self.extractChain(tokens,st), "SP": self.extractChain(tokens,st), "EP": self.extractChain(tokens,st), "PY": self.extractChain(tokens,st), "AU": self.author(tokens,st), "M1": self.extractChain(tokens,st), "ER": self.extractChain(tokens,st) }[st] return result Source.sourceid gives 1. That's ok. But when I use the method extractRisVal(self,st) like: extractRisVal("TY") it literrally returns extractRisVal("TY") while it should be journal. If I add a test method in the Source class: def testCode(self): a=[] tokens = self.ris.split("|") for token in tokens: if(token.startswith("AU")): a.append(token[5:]) return a It returns what I want. So it looks like I have a problem with the attributes token and … -
Django Check if User Is in Many to Many User Field (template)
I have a model: class Projects(models.Model): name = models.CharField(max_length=200) users = models.ManyToManyField(User) As you can see, the model contains a ManytoMany field with User model. In my template, I want to check if the current authenticated user is in the Projects users field that was passed to the template: @login_required def index(request): projects = Projects.objects.all() context = { 'projects' : projects } return render(request,'app/index.html',context) The template code will look something like this: {% for project in projects %} {% if user is in project.user %} {% endif %} {% endfor %} Any help will be appreciated! -
Import Error: Missing required dependencies ['numpy']
I am developing an app with virtualenv and python3.5, now I want to go to production with httpd on centos. The app runs normally in dev environment. I execute it with python manage.py However, once I execute on production it gives Missing required dependencies ['numpy'] The numpy is installed in Virtualenv and on a system level. I ran it after sourcing the virtualenv and worked correctly. If I remove the import pandas as pd, the app runs normally in production. I am puzzled as to what the error might be! -
Django 2 django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
I currently have a django app running Django==2.0. I wasn't having this problem before but yesterday when I was running through some code I got the error from home.models import Notification ImportError: cannot import name 'Notification' This was from meetings/models.py which is an app at the same level as mange.py My apps are registered as following INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', 'meetings', ] If I simple import home and then print it out I see <module 'home' from '<relative_path>/home/__init__.py'> But if I try something like this from django.apps import apps print(apps.get_models()) I get the error django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. After that I tried testing the same thing through python manage.py shell and I got completely different results. apps.get_models() returned all of the models I was expecting to see and that are in the database. >>> apps.get_app_config('home').models['notification'] returned <class 'home.models.Notification'> I'm trying to figure out why I can't import Notification in my meetings models and why I'm getting different results when I run these commands in the shell. I also have django channels and storages as installed apps. -
Serializer validate function is not called DRF
class ChildSerializer(serializers.ModelSerializer): """ Serializer for Dependency Task. Use with TaskSerializer """ class Meta: model = DependencyTask fields = '__all__' class ParentSerializer(serializers.ModelSerializer): """ Serializer for task """ def validate_title(self, data): if not data.get('dependency_task'): raise serializers.ValidationError('Please set title') return data Validate Function is not called when Post ,Also how can i give custom errors to ChildSerializer , -
How to show more ldap attributes in Django
I need help concerning the authentication in Django with an LDAP user. I want to show more than just the standard user attributes: class Meta: model = User fields = ( 'first_name', 'last_name', 'email', ) Am I right, when I say I need a new Model by using django-ldapdb? Or is there a way to show let's say telephoneNumber? Something like this: class LdapUser(ldapdb.models.Model): base_dn = "CN=LDAP_IPA,CN=Users,DC=sbvg,DC=ch" object_classes = ['posixAccount', 'shadowAccount', 'inetOrgPerson'] # inetOrgPerson first_name = CharField(db_column='givenName', blank=True) last_name = CharField("Final name", db_column='sn') email = CharField(db_column='mail') salutation = CharField(db_column='title', blank=True) phone = CharField(db_column='telephoneNumber', blank=True) mobile_phone = CharField(db_column='mobile', blank=True) Or is it even easier with django-auth-ldap: AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", "mobile": "mobile", "salutation": "title", "dn": "distinguishedName", } How do I call these in my forms? As you can see, I need help about this. If you are familiar with the problem or have any idea, please do not hesitate to post it. -
How do I push the multiple django-cookiecutter-made Docker images to Heroku?
I developed locally using Docker and cookiecutter-django. Cookiecutter-django creates several Dockerfiles within the "compose" directory. I am now trying to push the project to Heroku. However, heroku container:push web will return No images to push. If I try the same command within a subdirectory of the compose directory, it will eventually break--probably due to an attempt at only pushing partial dockerfiles. How do I get this up and running on Heroku taking advantage of Heroku containers? This article from Heroku says I can push multiple images using by renaming the Dockerfiles, but I'm not sure how to figure out which of these cookiecutter-generated Dockerfiles are of which process type. docker images will return: REPOSITORY TAG IMAGE ID CREATED SIZE <none> <none> 16e570f295a7 10 minutes ago 318MB luup_celeryworker latest bd7ff7e5eb10 2 hours ago 531MB luup_django latest bd7ff7e5eb10 2 hours ago 531MB luup_celerybeat latest bd7ff7e5eb10 2 hours ago 531MB luup_postgres latest e50eb7b8a704 2 hours ago 287MB registry.heroku.com/fierce-forest-57627/web latest 27690b3e49d4 16 hours ago 766MB python 3.6-alpine c3a4a35c9244 22 hours ago 90MB This is the Dockerfile made by cookiecutter. It is the DF under compose/production/django. There are other DFs--for caddy, postgres, as well as DFs for local. FROM python:3.6-alpine ENV PYTHONUNBUFFERED 1 RUN apk … -
Avoiding race conditions while updating jsonb fields in Django
Taking cues from the Django documentation at https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/fields/#querying-jsonfield, a jsonb field can be updated through the following code : collie = Dog.objects.filter(data__breed='collie')[0] collie['owner']['name'] = 'Jeff' collie.save() Internally Django gets the full jsonb field in memory, we update the owner name in the dict and then save it. However, this can cause a race condition, since another piece of code could update the same Dog row while we are assigning it an owner. Also, something like the following does not work : Dog.objects.filter(data__breed='collie').update(data__owner__name='Jeff') What would be the best way to handle this? -
Django filter adding results from two tables
I am trying to get results from two tables by filter. I want to get all the properties and if there is an agreement I also want to include the renters first and last name. Below is a simple model. class Property(models.Model): name = models.CharField(max_length=70, blank=True, verbose_name="Property Name") class Agreement(models.Model): property = models.ForeignKey(Property, on_delete=models.CASCADE) firstname = models.CharField(max_length=40, verbose_name="First Name") lastname = models.CharField(max_length=40, verbose_name="Last Name") Normally I get all the properties with properties = Properties.objects.all() Is there some way like below: properties = Properties.objects.all() \ .somemethod(get values of firstname and lastname from aggreement if related record exists.) I can loop at properties results and get the values from agreements. But I think this is not the preferred way as it will make many SQL calls. -
how to get the data from view to templates?
i'm trying to get the data from my views.py to the html page. if the views.py code is this def VerifiedBySuperuser(request): if request.method == 'POST': vbs = MaanyaIT_EXAM48_ManageQuestionBank() vbs.QuestionID = MaanyaIT_EXAM48_ManageQuestionBank.objects.get(QuestionID=request.POST.get(QuestionID, None)) vbs.QuestionInEnglishLang = request.POST.get('QuestionInEnglishLang', None) vbs.save() else: return render(request, 'exam48app/verifiedbysuperuser.html') then what shoud the code of html page to view my all data to the tamplates.. -
How to add "description" for a column in Postgres DB using the corresponding Django model?
For e.g., in this table, I'd like to be able add the "description" text at the Django ORM layer and have it reflected at the database level. test=# \d+ django_model Table "public.django_model" Column | Type | Modifiers | Description --------+---------+-----------+------------- i | integer | | j | integer | | Indexes: "mi" btree (i) - Tablespace: "testspace" "mj" btree (j) Has OIDs: no -
Cannot apply css @media to template in django
I've got view function that returns template if url matches. This html loads normally with css styles, but when I tried to set up media in css, nothing happens. It provides version for computers. -
Django TypeError: __init__() takes 1 positional argument but 2 were given
I can't find solution for the TypeError: init() takes 1 positional argument but 2 were given TypeError appears when I try to make migrations in ubuntu concole. error: File "/home/wojciech/workspace/conference_room/conference_room/conference/forms.py", line 8, in NewRoomForm taken = forms.ChoiceField(TAKEN, label='Taken', widget=forms.Select) TypeError: __init__() takes 1 positional argument but 2 were given forms: from django import forms from .models import TAKEN class NewRoomForm(forms.Form): name = forms.CharField(label='Name', max_length=32) number = forms.IntegerField(label='Room Number') taken = forms.ChoiceField(TAKEN, label='Taken', widget=forms.Select) description = forms.CharField(label='Description', widget=forms.Textarea) models: TAKEN = ( (True, 'Yes'), (False, 'No') ) class Room(models.Model): name = models.CharField(max_length=32) number = models.IntegerField() taken = models.BooleanField(choices=TAKEN) description = models.CharField(max_length=128) Any ideas how to fix it? -
CCAvenue Refund API
Whenever i am doing form submit Refund API is working but in below case it is giving error. param_dict = { 'enc_request': enc_request_data, 'access_code': ACSCODE, 'command': "refundOrder", 'request_type': "JSON", 'version': '1.1' } r = requests.post(url = 'https://apitest.ccavenue.com/apis/servlet/DoWebTrans', data = param_dict) I am passing all the parameter's as a dictionary and hitting ccavenue server url but it is throwing error. -
form.is_valid() returns false on Login Page
I have been trying to create a login takes in registered users and authenticate them into the website. For some reason, it when executing it form.is_valid() always returns false even though I am pointing it to the right form in. The following is my views.py file from django.views import generic from django.views.generic.base import TemplateView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.forms import AuthenticationForm from django.views.generic import View from django.urls import reverse_lazy from django.http import HttpResponse from .registrationform import UserForm from .loginform import UserLoginForm from django.contrib import messages from django.contrib.auth.models import User class IndexView(View): form_class = UserLoginForm template_name = 'login/login_form.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) print(form.is_valid()) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None and user.is_active(): login(request, user) return redirect('sports:index') else: return redirect('login:login') else: return HttpResponse(request, status=500) class CreateUser(View): form_class = UserForm template_name = 'login/registration_form.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) print(form.is_valid()) if form.is_valid(): user = form.save(commit=False) email = form.cleaned_data['email'] username = form.cleaned_data['username'] pass1 … -
How can i deploy django(using python3) on a Windows computer that already has python2 in it's system PATH?
I wrote my project in python 3 and django 2.0. The deployment environment has another program that relies on it's built in python 2,and whenever it starts it writes it's python 2 path to the system environment variable,so my Django project can never run normally since it finds the wrong version of python. I'm using Windows server 2008 + Apache + mod_wsgi as the deployment environment. How can I deploy my Django project successfully without using any aggressive strategy(like deleting other python paths and add mine)? -
Django model inheritance structure
I am new to Django models and need advice on how best to structure my models. My site has services, each service has multiple plans. each company can have multiple services with one plan for the service. Here is a basic structure i have class BaseService(models.Model): some fields class ServiceA(BaseService): some fields/methods class ServiceB(BaseService): some fields/methods I have the same structure for service plans. Here are my questions: 1. Is this correct 2. How can I access all the services a company has Thank you -
Django (DRF) Serializer inserting NULL
I've got an issue with Django where I am attempting to insert a new row into a MySQL database without providing NULLs for unspecified data. For example, consider the following: class MyModel(models.Model): class Meta: db_table = 'model_table' managed = False a = models.AutoField(primary_key=True) b = models.CharField(max_length=255) c = models.CharField(max_length=255, blank=True) When providing the following data to the Serializer for a save(): data = list() data['b'] = 'Some Text' serializer = serializers.MyModelSerializer(data=data) serializer.save() The resulting SQL generated has NULL for every unspecified field, in this case 'c'. The table in the database does not allow NULL but has default values in place to handle unspecified data. Is it possible to override this Serializer functionality to allow fields to be entirely omitted when attempting to insert, or will I have to create a new model with those fields omitted and have a 'creation' model for this specific case that does not have any awareness of these fields? Note: the Serializer only has the field 'b' in its fields variable, so it has no immediate awareness of the 'c' column.