Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run django on Centos7/Apache2.4
I want to run django on CentOS 7 and apache 2.4. I follow django website guide (with digital ocean help) step by step. I also installed mod_wsgi using pip pip install mod_wsgi I add this line to my apache httpd.conf LoadModule wsgi_module /usr/lib64/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so and here is my config for django <VirtualHost MY_IP_ADDRESS:80> ServerName TEST.EXAMPLE.COM ServerAlias www.TEST.EXAMPLE.COM WSGIScriptAlias / /path/to/myApp/myApp/wsgi.py WSGIDaemonProcess TEST.EXAMPLE.COM python-path=/path/to/myApp:/path/to/myEnv/lib/python3.6/site-packages WSGIProcessGroup TEST.EXAMPLE.COM Alias /static /path/to/myApp/myApp/static <Directory /path/to/myApp/myApp/static> Require all granted </Directory> <Directory /path/to/myApp/myApp/myApp> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> Now there is two things. First when I try to test apache with apachectl -t command this message appears: AH00526: Syntax error on line 1 of /etc/httpd/conf.d/wsgi.conf: Invalid command 'WSGISocketPrefix', perhaps misspelled or defined by a module not included in the server configuration the content of /etc/httpd/conf.d/wsgi.conf is: WSGISocketPrefix run/wsgi Second when I open my domain (TEST.EXAMPLE.COM) I get 503 Error: Service Unavailable The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later. What I tried: restart apache with systemctl restart httpd command, no errors appears kill apache process and start it again check if LoadModule wsgi_module line is before importing other *.conf files reboot VPS :( β¦ -
Why is my user model not appearing with the correct name and fields in django admin
I am using django 2.0.8 and Python 3.5 I have the following code models.py from django.db import models from django.contrib.auth.models import AbstractUser, UserManager from django.utils.timezone import now # Create your models here. class SiteMemberManager(UserManager): pass class SiteMember(AbstractUser): objects = SiteMemberManager() MEMBER_STATUS = ( ('1', 'Pending Approval'), ('2', 'Approved'), ('3', 'Banned'), ) status = models.CharField(max_length=16, choices=MEMBER_STATUS) last_seen = models.DateTimeField(null=False, default=now) abuse_report_count = models.PositiveSmallIntegerField(null=False, default=0) fields = ('last_seen', 'abuse_report_count') admin.py from django.contrib import admin # Register your models here. from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import SiteMemberCreationForm, SiteMemberChangeForm from .models import SiteMember class SiteMemberAdmin(UserAdmin): model = SiteMember add_form = SiteMemberCreationForm form = SiteMemberChangeForm admin.site.register(SiteMember, SiteMemberAdmin) When I go to the django admin page, there are two problems: My model SiteMember does not appear under the django app (instead the model displayed is Users The Users model does not display any of the fields I implemented on the SiteMember model I have run python manage.py makemigrations and python manage.py migrate already, and the migrations have been applied (according to the console output). How do I fix this? -
Handling database relations across microservices in Django
I have two django microservices, one is a accounts and the other is a properties micro-service. The user ids' are stored as uuids in the accounts microservice. While the properties microservice has a Tenant model which requires a user user_uuid field. The user user_uuid referenced in Tenant model will obviously come from getting a user user_uuid from the accounts microservice. Which is the best approach follow when handling database relations across microservices considering my scenario? Accounts models.py class User(AbstractUser): id = models.CharField(max_length=100, unique=True, default=uuid.uuid4, primary_key=True) Properties models.py class Tenant(models.Model): """Model that creates a Tenant Model.""" user_uuid = models.CharField(max_length=200, unique=True) start_date = models.DateField() end_date = models.DateField() Diagram Illustration -
ImportError: No module named config (did you rename settings/local-dist.py?)
when i try to run python manage.py runserver it show me No module named config error or when i try to do migrate than also it show me same error. from . import base import config INSTALLED_APPS = base.INSTALLED_APPS + ('django_nose',) DATABASES = { 'default': { 'ENGINE': config.DB_ENGINE, 'NAME': config.DB_DATABASE, 'USER': config.DB_USERNAME, 'PASSWORD': config.DB_PASSWORD, 'HOST': config.DB_HOST, 'PORT': config.DB_PORT, }, } ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', } } DEBUG = TEMPLATE_DEBUG = True DEV = True ALLOWED_HOSTS = [] SECRET_KEY = '{{ secret_key }}' -
Django Operational error on external db connection
Hi i'm using an Azure Virtual Machine with ubuntu server, i ssh into the machine and installed a lamp server (and also phpmyadmin, so i can view via browser my databases and execute operations). My django project is running on my macbook. I tried to connect to the mysql database installed on the VM in django using the method explained both in documentation and other stackoverflow questions, but none of them are working. let's say 1.2.3.4 is my VM ip. settings.py DATABASES = { # mysql 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'DBname', 'USER': 'rootuser', 'PASSWORD': 'rootPassword', 'HOST': '1.2.3.4', }, output of python manage.py runserver > django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '1.2.3.4' (timed out)") Do i need to configure the mysql database? Isn't 1.2.3.4 the same ip that i need to use for the db connection? Also when i try to install mysqlclient with pip install mysqlclient it raises an error: Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/st/8qzvdtwx6xsc1w1ffqd2c7br0000gn/T/pip-install-p25gukfh/mysqlclient/ -
Lost secret key in django project and (or) access error with database PostgreSQL
I Have a python+django project that I keep on two computers. I mean have two copy of the same project and sometimes I work on one, sometimes on the other. With copy-paste I lose the secret key in a settings.py (they were different but I overwrite). I don't know how generation and storage of secret keys works but to recover I did this: 1) make a copy of the project 2) deleted the project 3) start a new project with the same name 4) copy the new secret key 5) copy the files from the copy of the old project in the new project (so settings.py is lost and the new secret key with it) 6) change the secret key with the new secret key But this don't works and it gives the same error like before: System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000000004ADAEA0> Traceback (most recent call last): File "C:\Users\Fabio\Envs\possedimenti\lib\site-packages\django\db\backends\ba se\base.py", line 216, in ensure_connection self.connect() File "C:\Users\Fabio\Envs\possedimenti\lib\site-packages\django\db\backends\ba se\base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\Fabio\Envs\possedimenti\lib\site-packages\django\db\backends\po stgresql\base.py", line 174, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\Fabio\Envs\possedimenti\lib\site-packages\psycopg2\__init__.py" , line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: β¦ -
How can I rewrite one value in the settings for the test
How can I rewrite 'user': '5/minute' on 'user': '2/day' in the settings for the test REST_FRAMEWORK = { 'DEFAULT_THROTTLE_RATES': { 'user': '5/minute' } } How can i do this with @override_settings or mb with context manage? I need to apply this only in one test, I can not rewrite the whole dictionary -
I am unable to show table from markdown field and I am using django-markdownx
when i enter markdown for the table tag in editor then it did nothing simply paste the same in the preview is there anybody for the help. I am using django-markdownx for the markdown text -
PyCharm Jupyter Notebook AppRegistryNotReady: Apps aren't loaded yet
If you look at the image above, the dataframe is loaded, yet it gives me error, i.e. whenever I make changes to code and then press run, it gives error and loads dataframe, and in next lines says NameError df not defined, though if I do df.dropna(0) it works, I have all apps defined in installed_apps as well in settings.py. If I change line (rewrite same thing) and run gives error but works if I simply press enter, it only gives error, and nothing happnes -
Email encoding using Django
My webapp stores Hebrew text in a Postgres DB and later sends it as an email. I can see that the text is stored well in the DB, but when sent as an email it look like gibberish: ΓΒ’Γβ’ΓβΓβ Γβ’ΓΒ§ΓΒ¨, ΓβΓβΓβ’ ΓΛΓΒ‘ΓΛ ΓΒ©ΓΕ ΓβΓβΓΒͺΓΒ¨ΓΓβ’ΓΒͺ ΓβΓ ΓΒ©ΓΕΓβΓβ’ΓΒͺ ΓβΓΒ’ΓβΓΒ¨Γβ’ΓΒͺ. I'm using urlllib to unquote the text from the DB urllib.unquote(text) and EmailSender to send the email: EmailSender().send_html( "my email subject", email_content, [email], headers=headers, fail_silently=True ) What can be causing that? -
PYTHON DJANGO object not being displayed on template
When I have full set of model+view+url+template -> it goes fine but I want to try a top menu with my products' categories without specific given url. I want it to be in menu child template(?) whose parent is base.html. (I want it to be global within my website, yes) here are my codes: **models.py** class Category(models.Model): parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=100) def __str__(self): return self.name def parents(self): return self.parent def tree(self): return f"{self.parent} | {self.name}" **views.py** class CategoryView(ListView): model = Category template_name = 'category_list.html' queryset = model.objects.all() context_object_name = 'categories' **base.html** <body> <div class="container-fluid"> {% include 'navbar.html' %} {% include 'category_list.html' %} {% block content_body %}{% endblock %} {% include 'footer.html' %} </div> </body> **category_list.html** <div class="row"> {% for cat in categories %} <div class="col-1"> {{ cat.name }} </div> {% endfor %} </div> if I give a specific urlpattern and visit that url, these categories show up. but not in any other pages, it doesn't. So I failed to make it global. Please help me with this Thanks!!!!!! -
django form populate request.POST instance if form is invalid
I have a student application form, and upon user form submission, if there are errors in the form (for example, telephone number keyed in wrongly), i want django to populate the form with the previous POST data. If i'm not mistaken, I need to use instance to achieve this. But I am not sure how to get this to work. views.py def add_new_student(request): if request.user.is_authenticated: lesson_plans = LessonPlans.objects.all() if 'submit_new_student' in request.POST: form = NewStudentForm(request.POST) if form.is_valid(): #todo: add cleaned data form.save() # save into DB else: # this is where form is not valid, and where the POST data should fill up the form with the previous `post` data. form = NewStudentForm(request.POST, instance=form) else: form = NewStudentForm() args = { 'form': form, 'lesson_plans': lesson_plans } return render(request, 'static/html/new_student.html', args) The trace error that I receive is 'ModelFormOptions' object has no attribute 'concrete_fields' Any ideas how I can achieve this? -
How to add a Foreginkey field in signup form?
I am creating a signup form.I have inherited signup class.would like to add a selection list(foregin key).am geting error. model.py class Branch(models.Model): status = ( ('active', 'Active'), ('shutdown', 'Shutdown'), ('opensoon', 'Opening Soon'), ) branch_name = models.CharField(max_length=10, unique=True) availablity_status = models.CharField(choices=status, default='available', max_length=13 ) branch_state = models.CharField(max_length=20, name='State') def __str__(self): return self.branch_name form.py class SignUpForm(UserCreationForm): branch_name = forms.ForeignKey(Branch, on_delete=models.CASCADE) class Meta: model = User fields = ('username','branch_name','password1','password2') widgets = { 'username': forms.TextInput(attrs={'size': 15, 'placeholder': 'Username'}) } Error: branch_name = forms.ForeignKey(Branch, on_delete=models.CASCADE) AttributeError: module 'django.forms' has no attribute 'ForeignKey' -
Django regex validator message is not showing up
my RegexValidator seems to be working, because if the phone_number is entered in the wrong format, the form is not saved, but the error message is not showing up. If the format is according with regex, then form is saved. I checked the post Django regex validator message has no effect and included code attribute, but it did not change anything. It looks like something is missing, but I can not figure out what.My models.py and forms.py are below: #models.py from django.db import models from django.core.validators import RegexValidator class Notification(models.Model): sender = models.EmailField(max_length = 100) status = models.CharField(max_length = 50) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) message_info = models.TextField(max_length = 1000) def __str__(self): return self.message_info[:100] class ScheduleNotification(Notification): company = models.CharField(max_length = 50) phone_regex = RegexValidator( regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+79999999999'. Up to 15 digits allowed.", code="invalid") phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=False) def __str__(self): return self.sender #forms.py from django import forms from .models import Notification, ScheduleNotification ... class ScheduleNotificationForm(forms.ModelForm): class Meta: fields = ['sender', 'company', 'phone_number', 'message_info'] labels = { "sender": "your email:", "company": "your company:", "phone_number": "your mobile:", "message_info": "type your message:" } -
Migrating to django 1.11 - "context must be a dict rather than Context."
I started getting this error right after migration to 1.11.15 from 1.10. Here's the view code: def signin(request): form = forms.LoginForm() form_reset = forms.PasswordResetForm() if request.method == "POST": form = forms.LoginForm(request.POST) if form.is_valid(): login(request, form.user) messages.success(request, "You are now signed in") return redirect(reverse('landscape')) d = { 'form': form, 'form_reset': form_reset } return render(request, "signin.html", d) the "return" statement is the one in the exception trace. As you can see I am passing "dict" (not Context) into the render shortcut function. I went thru the whole stack trace and I can see that the dictionary indeed gets changed into a Context object inside the django lib (/usr/local/lib/python2.7/dist-packages/django/template/backends/django.py): class Template(object): def __init__(self, template, backend): self.template = template self.backend = backend @property def origin(self): return self.template.origin def render(self, context=None, request=None): context = make_context(context, request, autoescape=self.backend.engine.autoescape) try: return self.template.render(context) except TemplateDoesNotExist as exc: reraise(exc, self.backend) And the type check fires further down. Any idea what's wrong with my setup? the requirements.txt for full view: Django==1.11.15 http-parser==0.8.1 httpie==0.8.0 httplib2==0.8 dj-database-url==0.3.0 dj-static==0.0.6 gunicorn==19.1.1 psycopg2==2.7.5 static==0.4 wsgiref==0.1.2 websocket-client==0.32.0 Pillow==2.8.1 django-storages==1.5.2 boto==2.38.0 twitter==1.17.1 rollbar==0.13.11 django-cors-headers==1.1.0 django-annoying==0.10.3 django-letsencrypt==2.0.0 django-compressor==2.1.1 braintree==3.38.0 validate-email==1.3 pydns==2.3.6 asgi-redis==1.4.3 asgiref==1.1.2 channels==1.1.8 django-redis-cache==1.7.1 whitenoise==3.3.1 daphne==1.4.2 django-js-reverse==0.8.1 crypto==1.4.1 cryptography==1.8.1 pycrypto==2.6.1 -
Django Rest Framework - Django Nested serializer One to Many Relations
I have three models : User(django auth model), Consumer, Tasks. User model and Consumer has one to one relationship and Consumer and Task has one to many relationship. My model.py goes like this: class Consumer(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) average_rating=models.FloatField(default=5.0) class Tasks(models.Model): consumer=models.ForeignKey(Consumer,on_delete=models.CASCADE,related_name='consumer_obj') title=models.CharField(max_length=50) description=models.CharField(max_length=200) added_on=models.DateTimeField(auto_now=True) My serializers.py goes like this: class TaskSerializer(serializers.ModelSerializer): category=serializers.CharField(max_length=10) class Meta: model=Tasks fields=['title','description'] class UserSerializer(serializers.ModelSerializer): password=serializers.CharField(max_length=10,write_only=True) class Meta: model=User fields=['username','password','email'] class ConsumerSerializer(serializers.ModelSerializer): user=UserSerializer() tasks=TaskSerializer(many=True,source='consumer_obj') class Meta: model=Consumer fields=['user','average_rating','tasks'] Now what I want to do is, Whenever I save a post a task, it should get save the task and associate itself to the current Consumer. What can be done. Now, whenever I call serializer.save() in my views I can pass a user instance as an argument something like this serializer.save(user=request.user) And in my serializer create() function I can query the user and than query the consumer with the help of user to associate the task with that user. I want to know if there is any better way to do this ? I'm new to DRF and having hard time learning it. -
get Model instance created in Form for tasks.py
AIM After the User creates an Alarm object on the SetAlarmForm, I wish to use Celery to check certain relevant conditions of that Alarm object. The issue is that I obviously wish to check the relevant conditions for the specific Alarm object created in the SetAlarmForm. However, I am using: objx = Alarm(), which obviously doesn't work because it refers to a generic Alarm object. I tried: objx = self.request.Alarm() and objx = Alarm.objects.get(id=self.request.id). CODE tasks.py @shared_task def run_alarm(): objx = Alarm() second_countdown = objx.get_alarm_length() # get the length of the alarm, in seconds time.sleep(second_countdown) # wait for the alarm time conditions_satisfied = objx.check_conditionals() # check if conditionals are satisfied if conditions_satisfied == True: return True -
mongoengine connection connectionerror with django rest framework
I am trying to build Django rest framework with MongoDB. So in my local its working. But in production, i'm using MongoLab as DB backend. But i'm not able make DB connection. I'm keep on getting DB connection authentication error. command SON([('authenticate', 1), ('user', u'XXXXX'), ('nonce', u'XXXXX'), ('key', u'XXXXXX')]) failed: auth failed The MongoLab mongo version : mongod version: 3.6.6 (MMAPv1). Correct me what i did wrong -
How to make a web based drag and drop form builder?
I wanted a general direction on what tools/technologies to use to build a simple web-based form builder (I have seen the jquery post, that's not what I'm looking for). I was thinking reactjs/vuejs but I need to know if it's possible before I commit to one toolset as opposed to another. Just to reiterate, my requirement is "build a web-based form builder, people can use it to build forms (like banks/DMVs) and share them with their clients so they can be filled online and printed or printed and filled offline". How would I start implementing it? (already settled on django for backend, I just need recommendations for implementing that functionality in the frontend) Thanks :) -
SSO with active directory on Windows server 2012 os using edx.
I want to do a SSO with Windows on-prim server using edx. How to implement this? -
How do i convert the just the values from a result set from of a django query into a list?
When i execute the following query to get a query set result peak_power_machine = MachinetoDatatype_Mapping.objects.filter(datatype__in=1]).values('machine_id') print(peak_power_machine) I get the following result when i tried it. <QuerySet [{'machine_id': 1}, {'machine_id': 3}]> But what i need is a simple list like [1,3...] with just the machine ids in it. How do i do that? Any help is appreciated :) -
Django ImageField: How to select pcitures from modal
I'm, trying to build a website in which one of the function is upload pictures to Modals.So,I use ImageField to finish this. When finishing that,however,I found I need select picture from Modal and ImageField only support select picture from local. I'm searching around for a lone time on new.But no use. Please help or try to give some ideas how to achieve this. Here's my code: modals: class Course(models.Model): title = models.CharField(max_length=32) paragraph = models.CharField(max_length=200) img = models.ImageField(upload_to='course/',editable=True) class Meta: db_table = 'Course' verbose_name_plural = 'Course' def __str__(self): return self.title admin: admin.site.register(models.Course) -
Django migration for different apps
I am having different apps in my django project. Each app containing one models.py file and it contains n no of tables. I am having only one database. When am migrating all the models.py files has to migrate at a time and all the tables sit in to same database(only one database). How to achieve this in django? -
Django 1.10 - Pointing to an external JavaScript file from index.html
I have a basic django app where I have only two pages. Following the official docs, this is my current demo project structure. . βββ db.sqlite3 βββ lineoee β βββ admin.py β βββ admin.pyc β βββ apps.py β βββ apps.pyc β βββ forms.py β βββ forms.pyc β βββ __init__.py β βββ __init__.pyc β βββ migrations β β βββ 0001_initial.py β β βββ 0001_initial.pyc β β βββ __init__.py β β βββ __init__.pyc β βββ models.py β βββ models.pyc β βββ models.py.save β βββ nano.save β βββ static β β βββ lineoee β β βββ lineoee.css β βββ templates β β βββ linedetails β β β βββ index.html β β β βββ index.html.save β β βββ lineoee β β βββ gauge.js <-- Cannot access this file β β βββ index.html <-- From this HTML file β β βββ index.htmlu β βββ tests.py β βββ views.py β βββ views.pyc β βββ views.py.save βββ manage.py βββ models.pyc βββ mysite βββ __init__.py βββ __init__.pyc βββ settings.py βββ settings.pyc βββ urls.py βββ urls.pyc βββ urls.py.save βββ wsgi.py βββ wsgi.pyc I am trying to access gauge.js from the index.html file which is located in the same directory. I have tried: <script src="gauge.js"></script> and am greeted with: GET β¦ -
How to code conditional fields in Django admin?
Display or hide fields depending on the value of the prior fields. models.py from django.db import models from django.contrib.auth.models import User STATUS_CHOICES = ((1, 'Accepted'),(0, 'Rejected'),) class Leave(models.Model): ---- ---- ---- ---- status = models.IntegerField(choices=STATUS_CHOICES, default = 0) reason_reject = models.CharField(('reason for rejection'),max_length=50, blank=True) def __str__(self): return self.name admin.py from django.contrib import admin from .models import Leave @admin.register(Leave) class LeaveAdmin(admin.ModelAdmin): ------ ------ ----- def get_readonly_fields(self, request, obj=None): # the logged in user can be accessed through the request object if obj and request.user.is_staff: readonly_fields = [f.name for f in self.opts.fields] readonly_fields.remove('status') readonly_fields.remove('reason_reject') return readonly_fields def get_fields(self, request, obj=None): fields = [f.name for f in self.opts.fields] if obj.status == 1: fields.remove('reason_reject') return fields class Media: js = ('/static/admin/js/admin.js') radio_fields = {"status": admin.HORIZONTAL} depending upon the value of the radio fields, i need to display or hide the reason_reject text field? How do I do that?