Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is Django logging not working with Gunicorn?
I have a django site with is behind a gunicorn server. Here are the logging settings for django - LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '[%(asctime)s][%(levelname)s] %(message)s', }, }, 'handlers': { 'file': { 'level': os.environ['DJANGO_LOGLEVEL'], 'class': 'logging.FileHandler', 'filename': '/mnt/storage/logs/django.log', 'formatter': 'verbose', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': os.environ['DJANGO_LOGLEVEL'], 'propagate': True, }, }, } Here is the command which starts gunicorn server - gunicorn training_service.wsgi -b 0.0.0.0:8000 -w 4 --access-logfile /mnt/storage/logs/access.log --log-file /mnt/storage/logs/gunicorn.log --log-level $GUNICORN_LOGLEVEL Now, my understanding is that both the logging frameworks should work completely independent of each other. But when I launch the django site by calling manage.py runserver logging works are expected from the django settings. But when I launch the same thing using the gunicorn command both the logging format and the debug logs from django disappear. I am not sure what is wrong here because disable_existing_loggers is also set to false. And I don't know if there is any setting in gunicorn which should effect django's logging functionality. The only difference is Debug is set to False when I run with gunicorn. -
Accessing IIS Windows Authentication Website from Excel Web Data
I have a basic website written in Python Django, hosted on IIS 8.5. The website is used in the company intranet with Windows Authentication. Accessing the website through a browser gives no problems for authentication. However making use of a simple web api to retrieve data for reporting purposes is giving problems. I'm trying to load a URL into Excel which supplies data in CSV format (Data -> From Web). Disabling IIS Windows Authentication and using Anonymous works perfectly. However enabling Windows Authentication does not work as Excel says 'credentials are incorrect'. The URL response is a simple HttpResponse object with CSV data. Nothing weird or complicated happening. Any idea where to troubleshoot this? My IIS knowledge is limited in this regard. -
Django model dynamic field names
Is it possible to make this approach to work: class AbstractModel(models.Model): self.fields_prefix + '_name' = models.CharField(max_length=255, blank=True, default='') self.fields_prefix + '_title = models.CharField(max_length=255, blank=True, default='') class Meta: abstract = True class MyModel(AbstractModel): fields_prefix = 'someprefix' id = models.AutoField(primary_key=True) so MyModel could have fields id, someprefix_name and someprefix_title -
The view pages.views.contact didn't return an HttpResponse object. It returned None instead
views.py The view pages.views.contact didn't return an HttpResponse object. It returned None instead. -
How to Change django admin css style and font?
I'm Developing an app with django . I want to customize django admin interface , but i cant add a custom font to it . I Want to use a custom font for Persian Language . Here is What i did but not get a correct result : Step 1 : I create a css file named admin-extra.css in this directory : /templates/css/admin-extra.css After That i Changed the postition of myappname before django.contrib.admin in Installed Apps Like This : INSTALLED_APPS = [ 'django.contrib.auth', 'pool', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'fcm_django' ] And the admin-extra.css is like this : body { margin: 0; padding: 0; font-size: 40px; color: #333; background: #fff; } And Finally I put admin-extra in a file named base_site.css in \templates\base_site.html and it's content is like this : {% extends "admin/base.html" %} {% load static from staticfiles %} {% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} {% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static "css/admin-extra.css" %}" />{% endblock %} {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1> {% endblock %} {% block nav-global %}{% endblock %} But i cant see the result , what i've … -
How can i create user profile after registering user in django using singnals
I am trying to create userprofile after user has been registered in django app. User creation is working fine but it is not profile models in admin page. It is not showing any errors. so far I have done this. users/signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User #reciever from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() users/app.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals users/models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pic') def __str__(self): return f'{self.user.username} Profile' -
empty block is not working with endif inside a loop
I am builidng a dashboard where empty content has a different view so the user is not viewing a empty area. It is working well with a for loop without an if block, for example {% for dashboard in dashboard_list %} some content {% empty %} no data {% endfor %} Now that {% for todo in todo_list %} {% if todo.complete %}{% else %} some content {% endif %} {% empty %} content when its empty {% endfor %} It's not working and doesn't show the "no data" -
My Javascript in django is only working once
Im creating a online pizza ordering site in django. When the user is ordering the pizza the price of the pizza change according to the selected size of the pizza for this im using javascript to show the price of selected size and hide the remaining. im using javascript to show the block of selected pizza price and hide the others but the problem is that the javascript only work on the first div when i try to change the size of piza in second div it does nothing. function selectFunction() { var size = document.getElementById("select"); var option = size.options[size.selectedIndex].text; if(option=="Select Size"){ document.getElementById("price").innerHTML = "Rs."; } if(option=="Large"){ x = document.getElementById("l-price"); x.style.display = "block"; y = document.getElementById("m-price"); z = document.getElementById("s-price"); y.style.display = "none"; z.style.display = "none"; } if(option=="Medium"){ x = document.getElementById("m-price"); x.style.display = "block"; y = document.getElementById("l-price"); z = document.getElementById("s-price"); y.style.display = "none"; z.style.display = "none"; } if(option=="Regular"){ x = document.getElementById("s-price"); x.style.display = "block"; y = document.getElementById("m-price"); z = document.getElementById("l-price"); y.style.display = "none"; z.style.display = "none"; } } {% extends "pizza_app/base.html" %} {% load static %} {% block content %} <div class="md-padding" style="width:92%; margin-left:auto; margin-right:auto;"> <form method="post"> <div class="row"> <div class="section-header text-center" > <h2 style="color:rgba(255, 255, 255, .9);">Pizza Menu</h2> </div> {% … -
how to transfer information to django by XMLHttpRequest GET method?
Here is my js code: var request = new XMLHttpRequest(); request.open('get', 'test'); request.send("{'name':'yixuan'}"); and in django: def httptest(request): name = request.GET.get('name') # name is none body = request.body # body is empty ( b'' ) I can not get any information in django. Is the type wrong here or is the request head not setting? -
How to enable iframe inside TinyMCE HTMLField?
How to enable iframe inside TinyMCE HTMLField? I'm using Django==2.1.2, django-tinymce==2.7.0. TinyMCE settings in settings.py: TINYMCE_DEFAULT_CONFIG = { 'theme': "advanced", 'width': '100%', 'height': 400, 'plugins': "table,paste,searchreplace", 'extended_valid_elements': "iframe[src|width|height|name|align|frameborder|scrolling]" } extended_valid_elements not works. Thank you for your help. -
Having trouble running migrations using django 2.7.1
I am very new to Django. I have been following some tutorials to learn the framework. I am using django in the virtualenv. When i run the command python manage.py makemigrations I am getting the below error Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/phyadavi/django-project/django-env/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/phyadavi/django-project/django-env/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/Users/phyadavi/django-project/django-env/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/phyadavi/django-project/django-env/lib/python3.7/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Users/phyadavi/django-project/django-env/lib/python3.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/phyadavi/django-project/django-env/tictactoe/gameplay/models.py", line 5, in <module> class Game(models.Model): File "/Users/phyadavi/django-project/django-env/tictactoe/gameplay/models.py", line 7, in Game related_name="games_first_player") TypeError: __init__() missing 1 required positional argument: 'on_delete' Here is the model class from django.db import models from django.contrib.auth.models import User class Game(models.Model): first_player = models.ForeignKey(User, related_name="games_first_player") second_player = models.ForeignKey(User, related_name="games_second_player") start_time = models.DateTimeField(auto_now_add=True) last_active = models.DateTimeField(auto_now=True) class Move(models.Model): x = models.IntegerField() y = models.IntegerField() comment = … -
Can't connect to more than 6 IP cameras at the same moment
I'm new to Django and now trying to make an app, which will provide access to live video stream from several IP cameras over rtsp at the same time. First of all, I have tried the following code with 12 IP cameras and everything was working fine. import cv2 import threading class camThread(threading.Thread): def __init__(self, previewName, camID): threading.Thread.__init__(self) self.previewName = previewName self.camID = camID def run(self): print("Starting " + self.previewName) camPreview(self.previewName, self.camID) def camPreview(previewName, camID): cv2.namedWindow(previewName) cam = cv2.VideoCapture(camID) if cam.isOpened(): rval, frame = cam.read() else: rval = False while rval: cv2.imshow(previewName, frame) rval, frame = cam.read() key = cv2.waitKey(20) if key == 27: break cv2.destroyWindow(previewName) thread = camThread('Cam', 'rtsp://admin:pass@1.2.3.4/axis-media/media.amp?videocodec=h264&resolution=320x240'') thread.start() But when I tried to use it in Django like this: models.py class VideoCamera(threading.Thread): def __init__(self, cam_ip): threading.Thread.__init__(self) self.cam_ip_str = str(cam_ip) url = 'rtsp://admin:pass@' + self.cam_ip_str + '/axis-media/media.amp?videocodec=h264&resolution=320x240' self.video = cv2.VideoCapture(url) print("Starting " + self.cam_ip_str) def __del__(self): self.video.release() def get_frame(self): ret, image = self.video.read() ret, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() views.py def gen(camera): while True: frame = camera.get_frame() yield(b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def cam_index(request, cam_name): camera = Cameras.objects.get(camera_name = cam_name) video_thread = gen(VideoCamera(cam_ip=camera.IP_adress)) stream = StreamingHttpResponse(video_thread, content_type="multipart/x- mixed-replace;boundary=frame") return stream And then I just paste my … -
django.urls.exceptions.NoReverseMatch
I'm new to Django. when I click the button "New stok". it give the error below: django.urls.exceptions.NoReverseMatch: Reverse for 'stok_create' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['books/(?P<pk>[0-9]+)/create/$'] models.py from django.db import models from django.contrib.auth.models import User class Pembekal(models.Model): pembekal = models.CharField(max_length=50, unique=True) alamat = models.CharField(max_length=50) telefon = models.CharField(max_length=20) def __str__ (self): return self.pembekal class Stok(models.Model): stok = models.CharField(max_length=50, unique=True) pembekal = models.ForeignKey(Pembekal, on_delete=models.CASCADE, related_name='stoks') def __str__ (self): return self.jenis_stok views.py def stok_create(request, pk): pembekal = get_object_or_404(Pembekal, pk=pk) if request.method == 'POST': form = StokForm(request.POST, instance=pembekal) else: form = StokForm(instance=pembekal) return save_stok_form(request, form, 'books/includes/partial_stok_create.html') urls.py urlpatterns = [ path('', TemplateView.as_view(template_name='home.html'), name='home'), path('books/', views.pembekal_list, name='book_list'), path('books/create/', views.pembekal_create, name='book_create'), path('books/<int:pk>/', views.stok_list, name='stok_list'), path('books/<int:pk>/update/', views.pembekal_update, name='book_update'), path('books/<int:pk>/delete/', views.pembekal_delete, name='book_delete'), path('books/<int:pk>/create/', views.stok_create, name='stok_create'), path('admin/', admin.site.urls), ] stok_list.html <p> <button type="button" class="btn btn-primary js-create-book" data-url="{% url 'stok_create' pk=pembekal.pk %}"> <span class="glyphicon glyphicon-plus"></span> New stok </button> </p> Any helps is greatly appreciated. I'm using Ajax to render to CRUD app. The modal form isn't pop up due to the above message. Thanks -
Response CreateAPIView DRF
I want response for CreateAPIView like this return Response( { 'status': status_code.HTTP_200_OK, 'message': 'Testimonials fetched', 'data': serializer.data },) But i dont know which function will be best to use inside AddAPIView to get response like above class AddAPIView(generics.CreateAPIView): queryset = Masjid.objects.all() serializer_class = serializers.MasjidAddSerialzer permission_classes = [IsAuthenticated] -
Django ModelMultipleChoiceField 1:N initial
I have two Models, Machine and Device class Machine(models.Model): pass class Device(models.Model): machine = models.ForeignKey(Machine, related_name='devices') Now in Django Admin, In Machine change page, I want to be able to add 1:N Device references, it works nice and out of the box with ManyToMany relation, here is how it looks in admin (desired) I am trying to use forms.ModelMultipleChoiceField for 1:N selection. I've already figured out saving of this relation, but feeding the initial value just doesnt seem to work. How I am trying to feed initial values: class MachineForm(forms.ModelForm): class Meta: model = Machine fields = '__all__' devices = forms.ModelMultipleChoiceField(queryset=Device.objects.filter(machine=None).all(), required=False) def __init__(self, *args, **kwargs): super(MachineForm, self).__init__(*args, **kwargs) if self.instance: self.fields['devices'].initial = self.instance.devices.all() def save(self, *args, **kwargs): instance = super(MachineForm, self).save(commit=False) self.fields['devices'].initial.update(machine=None) instance.save() self.cleaned_data['devices'].update(machine=instance) return instance In debugger, I can clearly that the initial queryset is nonempty: initial <QuerySet [<Device: 10126>, <Device: 10127>]> but the field in django admin is still empty. Anyone knows why? -
Unable to add different block tag to my template
I am trying to add different block tags inside a for loop but it raise an error Did you forget to register or load this tag? But I register it {% for todo in todo_list %} {% if todo.complete %}{% else %} {{todo.text|capfirst|truncatechars:150}} </a> <br> <small class="text-muted">{{todo.content|capfirst}}{% empty %} {% endif %} </small> <hr> {% endif %} {% endfor %} Thanks -
Video streaming using Django and react-native
I would like to build an app that uses Django rest framework and react-native. I really don't know where to start and what search terms should i use. A simple guide will be very helpful. -
get object name from queryset in template
How can I get object from queryset by id manualy in template? I am gonna get subcategory from category, so i need get subcategory by id. category.subcategory.get(id=id) doesn't help. I'm new so please help. -
Adding new app in django installed app gives error populate() isn't reentrant for IIS
First of all I have seen all SO threads related to problem of error populate() isn't reentrant but problem I'm facing is different among them. Things I want to clear first: My Django app works perfectly on IIS Server with only my app registered in INSTALLED_APPS in settings.pyof project. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'MyDjangoWebApp.app',] When I add new app in my INSTALLED_APPS in settings.py of project it works perfectly in Django Local Server (E.g Server created and hosted by Pycharm) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Busisoft_Document_Extraction_Web.app', // Newly added app which I installed through PIP 'widget_tweaks'] 3.But when I host same project from IIS server, it gives me Error occurred while reading WSGI handler: Traceback (most recent call last): File "c:\server\MyDjangoWebApp\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "c:\server\MyDjangoWebApp\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "c:\server\MyDjangoWebApp\wfastcgi.py", line 605, in get_wsgi_handler handler = handler() File "c:\server\MyDjangoWebApp\venv\lib\site- packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "c:\server\MyDjangoWebApp\venv\lib\site- packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "c:\server\MyDjangoWebApp\venv\lib\site- packages\django\apps\registry.py", line 81, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant StdOut: StdErr: Interesting is that if I remove that extra app IIS works … -
How to design a many-to-many relation in Django?
I'm working on a webapp in Django 1.11 and it consists of: Users can add tasks and assign it to other users. Users should be able to see tasks assigned to him and created by him. Here is my models.py: from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): username = None email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] class Task(models.Model): title = models.CharField(max_length=200) description = models.TextField(max_length=500) How should I relate my task model to user model ? Should I put the many-to-many field in the user model or the task model ? How do I go about doing it ? -
Populating PostgreSQL database for Django app on Heroku by reading csv file from aws s3 bucket
I have a Django app running locally on my machine with a postgres database connected to it. I populated the database by reading csv file in a migration script. My question is, what is the best way to populate the Heroku Postgres database after I deploy my app on heroku? Should I upload csv file to an aws s3 bucket and read it from there in a migration script like I did in my local machine and populate the database (basically using csv file as static file)? Or should I upload the Postgres database’s dump file to s3 bucket and restore it? -
Stop Django from autofilling manytomany fields in admin
I have the following models: class Color(models.Model): name = models.CharField(max_length=50, null=False, blank=False) def __str__(self): return self.name class Flower(models.Model): flower_number = models.PositiveSmallIntegerField( default=1,blank=True, null=True) petal_color = models.ManyToManyField(Color,blank=True, related_name="%(app_label)s_%(class)s_petal", related_query_name="%(app_label)s_%(class)s") petal_outer_color = models.ManyToManyField(Color,blank=True, related_name="%(app_label)s_%(class)s_petal_outer", related_query_name="%(app_label)s_%(class)s") class Meta: abstract = True class Plant(Flower): name = models.CharField(max_length=50, null=False, blank=False, unique=True) On the Admin I just have: admin.site.register(Plant) When I go into the Django admin and fill out either of the manytomany petal_color or petal_outer_color with data the other manytomany field automatically gets filled when it saves. How do I stop this from happening? Nothing shows up as an error and I tried going back and deleting and re-entering data but it still happens -
DisallowedHost at / Invalid HTTP_HOST header:
I am getting Error DisallowedHost at / Invalid HTTP_HOST header: `'www.example.com'`. You may need to add 'www.example.com' to ALLOWED_HOSTS. in my Django project which is deployed on IIS Windows server. Sometimes it works fine and sometimes it throws an error. Even I have set DEBUG = False. I got an error page as it appears in DEBUG = True mode. Sometimes It works fine, and sometimes it throws an error. Please help me to solve this problem permanently. -
How to convert a function defined outside the tasks.py to a Celery task and make the Celery worker to process it in Django
I am trying to use Celery in my Django Project say "MySite" . My directory structure is as follows mysite - appliactions - api -tasks.py -urls.py -apps.py -__init__.py -v0 -__init__.py -urls.py -views.py -utils.py -v1 -__init__.py -urls.py -views.py -utils.py - backbone -tasks.py -urls.py -apps.py -views.py -models.py -__init__.py -mysite - settings.py I have two applications api and backbone. I have created tasks.py in api directory which has various Celery tasks defined. Also I have various functions defined in the utils.py of v0 and v1 directories. The above-mentioned structure is just a mere representation of the actual project. The project is much bigger and complicated. How can I run a function defined in utils.py as a Celery task without moving the location of function to tasks.py ?. -
received a naive datetime while time zone support is active
I am trying to insert some records to a Django Model which include some old dates in unix ctime Format. I am comverting it to YYYY-MM-DD hh:mm:ss and saving it to a model in datetime field. While running a import job ( Function which is converting the unix dates to YYYY-MM-DD hh:mm:ss) and saving it , I am getting a warning below C:\Python\Python36\lib\site-packages\django\db\models\fields\__init__.py:1421: RuntimeWarning: DateTimeField SensorRecords.aqdate received a naive datetime (2012-07-06 05:00:00) while time zone support is active. RuntimeWarning) How should I import it so to avoid this ? This is my Converter Function def ctodatetime (ctimeinput): etime=time.ctime(int(ctimeinput)) btime=datetime.datetime.strptime(etime,"%a %b %d %H:%M:%S %Y") print(btime) return btime