Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
After logging in (in my Django app) I get the 403 error
When I run my Django application (via python manage.py runserver) I get the login screen, however when I try to login it redirect me to the page that says: Forbidden (403) CSRF verification failed. Request aborted. Here is my settings.py """ Django settings for my_app project. Generated by 'django-admin startproject' using Django 2.1.5. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '...' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cooking_book' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'my_app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.static', 'django.template.context_processors.media', ], }, }, ] WSGI_APPLICATION = 'my_app.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), … -
Set django admin to display all the columns of the database
I am using django to create a website for my school project, but the thing is django admin doesn't represent its database like xamp does (tables, rows columns), instead it displays just one column. Is there anyway I can set it to bring out all the information in the database just like in xamp or wamp -
How create nested object in drf with validation?
I want to create nested objects with django-rest-framework serializers(drf). Initially, I create such serializers: class CollectionCreateSerializer(ModelSerializer): citizens = CitizenSerializer(many=True) ## Some definition of serializer fields def create(self, validated_data): collection = Collection.objects.create() citizens = validated_data.pop('citizens') for citizen in citizens: citizen_serializer = CitizenSerializer(data=citizen, context={'citizens': citizens) citizen_serializer.is_valid(raise_exception=True) citizen_serializer.save() return collection class CitizenSerializer(serializers.ModelSerializer): ## Some defenition of serializer fields def validate(self, attrs): print('in validate citizen') citizens = self.context['citizens'] ## Some validation logic with citizens context return super().validate(attrs) But that did not work, because validate method calls from create method, and before it when validation of collection happens. And the problem is that in the first case context contains 'request' and some other info. And in the second case context contains defined in create method context. So validate method on each citizen called twice with different context info. Then I tried to delete is_valid method from create method. And the next logical error occurred: You must call `.is_valid()` before calling `.save()`. Then I tried to make citizens value real-only to prevent internal validation. But then the citizens field is not included in the validated data in the create method. So I expect that some flag that turns off the internal nested objects validation? Or maybe … -
I need that when I click on an article <> it’s called the name of the article
I need that when I click on an article <> it’s called the name of the article For example, now, when I click on an article, I go to url address news / 1, but I need instead of 1, there was a name similar to this picture. Or here’s another premiere, I call the article “How to Skip School” and url the address will be like this news/how-to-skip-school views.py class ArticleIndex(ListView): model = Articles template_name = 'news/posts.html' def ArticleDetailView(request, pk): tag=None Articles.objects.filter(pk=pk).update(view=F('view') + 1) Articles.objects.all() article_details = Articles.objects.filter(pk=pk).first() if request.method == 'POST': comment_form = Comments(request.POST) comment_form.save() else: comment_form = Comments() commentss = CommentModel.objects.all() return render(request, 'news/post.html', {'article_details': article_details, 'comment_form': comment_form, 'comments': commentss, 'tag': tag }) urls.py path('', ArticleIndex.as_view(), name='articles_list'), path('<int:pk>/', views.ArticleDetailView, name='article_detail'), models.py class Articles(models.Model): title = models.CharField(max_length= 200) post = models.TextField() date = models.DateTimeField() img = models.ImageField(upload_to='', default="default_value",verbose_name='Каритинка 260х180') tags = TaggableManager() article_like = models.IntegerField(default='0') article_dislike = models.IntegerField(default='0') view = models.IntegerField(default='0') datesArticle = models.DateTimeField(auto_now=True) class Meta: ordering = ['-datesArticle'] def __str__(self): return self.title -
djongo.sql2mongo.SQLDecodeError: FAILED SQL: SELECT COUNT(*) FROM with mongodb django
I getting the below error on a select query with MongoDb in Django. SELECT COUNT(*) FROM (SELECT DISTINCT "datacollection_computed_host_details"."id" AS Col1, "datacollection_computed_host_details"."HOST" AS Col2, "datacollection_computed_host_details"."TYP" AS Col3, "datacollection_computed_host_details"."isBM" AS Col4, "datacollection_computed_host_details"."Kernal" AS Col5, "datacollection_computed_host_details"."os_version" AS Col6, "datacollection_computed_host_details"."SID" AS Col7, "datacollection_computed_host_details"."DBSID" AS Col8, "datacollection_computed_host_details"."IS_VLAB" AS Col9, "datacollection_computed_host_details"."ZHCODE" AS Col10, "datacollection_computed_host_details"."DC" AS Col11, "datacollection_computed_host_details"."SYSTEMROLE" AS Col12, "datacollection_computed_host_details"."MEMORY" AS Col13, "datacollection_computed_host_details"."EUDP" AS Col14 FROM "datacollection_computed_host_details" WHERE ("datacollection_computed_host_details"."IS_VLAB" = %(0)s AND "datacollection_computed_host_details"."SID" iLIKE %(1)s)) subquery ERROR : djongo.sql2mongo.SQLDecodeError: Version: 1.2.33 Django Version 2.1.8 Python 3.7.2 Background : I am working on a Django project that uses rest_framework_datatables for Datatable integration. I am able to receive the data in frontend and able to sort the data. But when I apply the search I am getting 500 in the Django side. It will be really great if you help me to solve this problem. I am stuck for more than a week 😥. I think its a MongoDB error : I saw reply in https://github.com/nesdis/djongo/issues/156 Since i am new to django and MongoDB i am unable to perform your solution. MongoDB error : djongo.sql2mongo.SQLDecodeError: FAILED SQL: SELECT COUNT(*) FROM (SELECT DISTINCT "datacollection_computed_host_details"."id" AS Col1, "datacollection_computed_host_details"."HOST" AS Col2, "datacollection_computed_host_details"."TYP" AS Col3, "datacollection_computed_host_details"."isBM" AS Col4, "datacollection_computed_host_details"."Kernal" AS Col5, … -
How to add link fields to serializer dynamically
I would like to create a general serializer for a ManyToMany link, which will include linked models data. from rest_framework import serializers def get_model_serializer(model, fields_to_serialize): class BaseSerializer(serializers.ModelSerializer): class Meta: model = model fields = fields_to_serialize return BaseSerializer def get_many_to_many_serializer(many_to_many_model, first_model, second_model, fields_to_serialize) serializer = get_model_serializer(many_to_many_model, fields_to_serialize) class BaseSerializer(serializer): pass # only when I directly set the attributes upon class definition it works #attendee = get_model_serializer(first_model)() #operation = get_model_serializer(second_model)() # This does not work setattr(BaseSerializer, first_model.__name__.lower(), get_model_serializer(first_model)()) setattr(BaseSerializer, second_model.__name__.lower(), get_model_serializer(second_model)()) #Or this #setattr(BaseSerializer, 'operation', get_model_serializer(first_model)()) #setattr(BaseSerializer, 'attendee', get_model_serializer(second_model)()) return BaseSerializer The problem is, that when I set the attribute using setattr, the linked models are not serialized. I guess there is some magic upon class creation or whatever? Any ideas, how can I go around this? -
Managing Accessibility of a user to other users profile pages
I'm new to django Need some advise to manage social network like website. Here is a problem. When a user logged in, in the all users page he sees himself among users. Need to manage that logged in user sees only other users. Thanks a lot -
Python Django | How to run and time running of other python scripts in background and see their log
I am new to Django and i would like to get an advise from someone experienced in it. What i am trying to do is basic application for controlling other Python scripts. For example, i have script n.1. I come to the application and click to run script n.1. The application will write me the log from the script (all the prints() or errors from the interpreter). But because the script n.1 can run long time i can leave the application and the script will continue running. When i came back to the application part, which controls script n.1., i would liked to see as it continues running with the whole log from the beggining. My idea is i will have to run these scripts asynchronous, right? What can i use in Django? What would be the best way to achieve this goal? There can run multiple this scripts in the background. Also i need solution, where it would be possible to run these scripts regularly in certain time the user sets. -
nginx Returning 500 for POST Image Request with Django Rest Framework
Preface I have done a lot of research for solutions to similar problems I have been having, but have still yet to solve this major problem I am experiencing. As a last resort, as a lot of cases seem application-specific, I have decided to create a post here with my configuration in the hope that someone may see a possible solution. Framework Django 2.1.7 nginx/1.14.2 djangorestframework==3.9.2 The Problem On my local setup of my server with the above framework, I can POST an image through my client app (specifically a react-native app, which is likely not important information) just fine. However, when trying to make the same POST request with the same image and URL path to my remote server, it returns the following 500 error (snapshotted from Google Chrome Console debugger). I have strongly deduced that nginx is the culprit for just image uploads, as the django logs of my remote server show no indication that it has even received the POST request, as my local server does. A normal POST request without image uploading, however, works just fine on both the remote and local server. What I Have Tried As found in other posts, I have increased the … -
slugify() got an unexpected keyword argument 'allow_unicode'
When I want to create new object from product I got this error: slugify() got an unexpected keyword argument 'allow_unicode' This is my models: class BaseModel(models.Model): created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True,) slug = models.SlugField(null=True, blank=True, unique=True, allow_unicode=True, max_length=255) class Meta: abstract = True class Product(BaseModel): author = models.ForeignKey(User) title = models.CharField() # overwrite your model save method def save(self, *args, **kwargs): title = self.title # allow_unicode=True for support utf-8 languages self.slug = slugify(title, allow_unicode=True) super(Product, self).save(*args, **kwargs) I also ran the same pattern for other app(blog) ,and there I didn't run into this problem. What's wrong with this app? -
404 error after submitting form with ImageField on Django admin
I have created a Django admin using documentation tutorial. I have created a model Author and added 2 CharFields and one ImageField. If I want to add a new author, the page admin/app/author/add/ works. I add everything and then, when I press Submit, I will be redirected on the same page admin/app/author/add/, but I will get the following error: Page not found (404) Request Method: POST Request URL: ******/admin/app/author/add/ Raised by: django.contrib.admin.options.add_view Using the URLconf defined in ******.urls, Django tried these URL patterns, in this order: - admin/ - app/ [name='index'] The current path, app/author/add/, didn't match any of these. The requested URL is admin/app/author/add/, but for some reason it searches for app/author/add/. I tried to remove the ImageField and everything works fine, so I assume that the problem is ImageField. I have installed Pillow. I have done everything about static and media files deployment. class Author(models.Model): name = models.CharField(max_length=200) role = models.CharField(max_length=200) image = models.ImageField(upload_to='images/authors/', blank=True, null=True) def __str__(self): return self.name -
Trouble configuring Django+Celery on Heroku
I am trying to configure Celery task of a Django project on Heroku but I am facing issues. I have set CLOUDAMQP_URL properly in settings.py and configure worker configuration in Procfile, but I am getting WORKER TIMEOUT error message. Procfile web: gunicorn my_django_app.wsgi --log-file - worker: python manage.py celery worker --loglevel=info Settings.py ... # Celery BROKER_URL = os.environ.get("CLOUDAMQP_URL", "django://") #CELERY_BROKER_URL = 'amqp://localhost' BROKER_POOL_LIMIT = 1 BROKER_CONNECTION_MAX_RETRIES = 100 CELERY_TASK_SERIALIZER="json" CELERY_RESULT_SERIALIZER="json" CELERY_RESULT_BACKEND = "amqp://" Error Log 2019-08-03T15:31:08.732032+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=POST path="/train/" host=my-heroku-app.herokuapp.com request_id=d287u05d-c146-4144-ba4r-a447328g539f fwd="112.124.212.243" dyno=web.1 connect=0ms service=30001ms status=503 bytes=0 protocol=https 2019-08-03T15:31:09.539823+00:00 app[web.1]: [2019-08-03 15:31:09 +0000] [4] [CRITICAL] WORKER TIMEOUT (pid:11) 2019-08-03T15:31:09.541096+00:00 app[web.1]: [2019-08-03 15:31:09 +0000] [11] [INFO] Worker exiting (pid: 11) 2019-08-03T15:31:09.951975+00:00 app[web.1]: [2019-08-03 15:31:09 +0000] [28] [INFO] Booting worker with pid: 28 Can anybody tell me what I am missing, Thank you. -
Django CSRF Causes Server To Bug Out After Bad URL Requests
When I send an Ajax request that includes a CSRF token to an invalid URL and then follow it up with any request afterwards, body data from the first Ajax request is prepended to the next request, making the request invalid. If that second request is coming from a new browser window, the “invalid CSRF” page is returned even though it is the first time opening the home page of my site from a fresh window. The following requests are then processed correctly assuming they’re valid. The problem occurs any time a request with an csrf token header is sent to an invalid URL. Not sure how to solve this other than removing CSRF altogether which is not preferable. Django 2.1.4 Python 3.7 I started a project and reproduced the bug with minimal code. It is definitely a bug in the CSRF code I think.. Here is the entire project: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> Test worked <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <script> var token = "{{csrf_token}}"; var conf = { type: "POST", url: "bad", data: {title: "Title Here"}, headers: { "X-CSRFToken": token } } function badSubmit() { $.ajax(conf); }; </script> </body> </html> After running that … -
International phone number widget doesn't appear even though it was loaded successfully?
I have a Django app where I want to use the intl-tel-input widget. in the console it shows that it was loaded successfully and when I inspect the page the input tag looks like this : <input type="tel" name="Telephone_no" id="phone" class="textinput textInput form-control"> and the in the css file I changed the place to load images successfully like this ../images/ ( the place of the flags.png) and in the pagess I inserted this : <script> var input = document.querySelector("#phone"); window.intlTelInput(input); </script> but the widget never shows up. what can I do? -
Can't delete user, "FOREIGN KEY constraint failed"
I tried to register user and it cause some error, after that I could not delete those users and it said "IntegrityError at /admin/auth/user/ FOREIGN KEY constraint failed" (I'm using settings.AUTH_USER_MODEL) Could somebody help me out? -
Facing issue in configuring domain name to Django webserver
I have created the Django web app and deployed to ec2 instance using Nginx and supervisor it is working fine. I bout new domain and I configured its AWS route 53. I am able to see my domain name is mapping for aws instance. But when I try to access the Django web app it's giving 404. I have updated the server_name parm in my Nginx config server { listen 80; server_name equitynotify.com; location { include proxy_params; proxy_pass http://unix:/**/***/***/source/prod/boo-gateway/boogateway/app.sock; } location /static/ { autoindex on; alias /******/path; } Even I added the domain name is allowed hots of Django settings file still it's not working. Any idea whats I am missing -
Django - Most efficent display of list values (ForeignKey or ChoiceField)
I am designing a Django model, but found myself using many ForeignKey relations, and consequently started to have slow loading times (specially inside the Admin panel). However most of these ForeignKey relations are just to display a name field. class Field1(models.Model): name = models.CharField(max_length=250) class Field2(models.Model): name = models.CharField(max_length=250) class Field3(models.Model): name = models.CharField(max_length=250) ... class Main(models.Model): ... field1 = models.ForeignKey(Field1, on_delete=models.CASCADE) field2 = models.ForeignKey(Field2, on_delete=models.CASCADE) field3 = models.ForeignKey(Field3, on_delete=models.CASCADE) I could change these fields to ChoiceField but I would hard-code the choices inside models.py (not ideal) I imagine it would be possible to do something like this, but would it be faster/more efficient?: class Fields(models.Model): name = models.CharField(max_length=250) class ListValues(models.Model): type = models.ForeignKey('Fields', on_delete=models.CASCADE) name = models.CharField(max_length=250) class Main(models.Model): ... field1 = models.CharField(choices=ListValues.objects.get(type__name='Field1'), on_delete=models.CASCADE) field2 = models.CharField(choices=ListValues.objects.get(type__name='Field2'), on_delete=models.CASCADE) field3 = models.CharField(choices=ListValues.objects.get(type__name='Field3'), on_delete=models.CASCADE) Any insights would be helpful. Thank you. -
DJango Dependant Dropdown Showing Invalid Choices Error
I tried to create the dependant dropdown following the most famous tutorial for it : https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html. Although I am still getting the invalid choice error. How am i supposed to correct it? -
How to restrict my students to don't access teacher area in django?
I'm creating a website where there is two types of users Students and teachers. I had created one register and login page for authentication. Now by default all the users who sign up will be the students and can access the videos and also accessing teachers area. (i did the coding till here) If someone want to be the teacher there, then they have to submit there documents. After the verification , they can access teachers page. The problem is that i don't know How to give authorization to these user manually from admin panel so that they can access to specific (teachers) page? I had google it alot but dont understand how to do this thing.(suffering from 1 week) My whole website is ready but i dont know how to restrict all the users from teachers page and after there documents verification, how to give permission to access the teachers page. Any django developer can give the answers Please help me , i'm loosing my hope because i dont find any tutorial on this topic since 1 week Please help. Thanking you to all in advance for reading this question please share this if you don't know the answer. … -
is there any way to build a tracking pixel bu using javascript and use django in your backend?
I want to build a customer data platform, and the first thing that I need is the tracking pixel that will send the data back to django framework. but I don't know-how.I need someone to please guide me. I try building the tracking code but I don't even think it is correct. this is my tracking code that a user is going to put in his website <script type="text/javascript"> (function(i,z,a,l){ i._mgc=i._mgc||[]; i._mgc.push(['_trackpageview']); a=z.createElement('script'); a.type='text/javascript'; a.async=true; a.src='https://cdn.yourwebsite.com/js/pixel.js'; l=z.getElementByTagName('script')[0] z.parentNode.insertBefore(a,z); })(window,document); </script> and again what I don't know is that what is going to be inside pixel.js, thanks. -
Nginx + gunicorn show 502 randomly
My system has an issue recently, it worked fine before without any issues. From Nginx error log, I see there is a lot of error: connect() to unix:/home/ubuntu/site/site.sock failed (11: Resource temporarily unavailable) while connecting to upstream, client: 10.0.14.213, server: www.example.com, request: "GET /favicon.ico HTTP/1.1", upstream: "http://unix:/home/ubuntu/site/site.sock:/favicon.ico", host: "www.example.com", referrer: "https://www.example.com/tin-tuc/" These errors are from many randomly requests, not all requests. I still able to access the website, but sometimes get 502 bad request. It uses 2 VPS for web application. Each one has Nginx working as proxy pass to web application (Python + Django) using Socket. This is Nginx config (/etc/nginx/nginx.conf): user www-data; worker_processes auto; worker_rlimit_nofile 100480; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 1024; } http { sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; server_tokens off; include /etc/nginx/mime.types; default_type application/octet-stream; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ssl_ciphers "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA256:ECD$ access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; client_body_buffer_size 100k; client_header_buffer_size 100k; client_max_body_size 10M; large_client_header_buffers 4 100k; add_header X-Frame-Options SAMEORIGIN; add_header X-Content-Type-Options nosniff; add_header X-XSS-Protection "1; mode=block"; add_header Strict-Transport-Security "max-age=31536000; includeSubdomains;"; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } Nginx site config (/etc/nginx/sites-available/default): server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; # Add index.php to the list … -
How to use paypal correctly in server side django?
in my e commerce site I need to add on line payments I followed this docs: https://developer.paypal.com/docs/checkout/integrate/ this process is new for me so I could not understand how it works for example is this code for buttons generate success or fail redirect urls after payment process? how to connect between user order and payment process , how to confirm if payment done or no? and return response to client about that? this code in server side i couldn't understand how to use it and how to connect it with pay buttons https://developer.paypal.com/docs/checkout/integrate/#6-verify-the-transaction any one can help please? thanks in advance -
Django show many to many relation in User model
Here is the model: class Product(models.Model): title = models.CharField(max_length=60) price = models.DecimalField(max_digits=6, decimal_places=2) images = ArrayField(models.TextField()) user = models.ManyToManyField(User, related_name='products') how can I show that relation inside Admin Panel in User form here: -
How to solve the problem of AUTH_USER_MODEL?
I have code but whenever I makemigrations, it gives me error of "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'users.User' that has not been installed. How to solve this issue? settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'users.apps.UsersConfig', 'firstapp.apps.FirstappConfig', 'crispy_forms', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] AUTH_USER_MODEL = 'users.User' admin.py from django.contrib.auth.admin import UserAdmin admin.site.register(User, UserAdmin) models.py class User(forms.ModelForm): Id_card_number = models.CharField(max_length=15) forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True)._unique = True Id_card_number = forms.CharField(max_length=15, required=True)._unique = True class Meta: model = User fields =['username','email','password1','password2','Id_card_number'] -
The future of Django? Django channels?
i'm a django developer since the first releases, and now, starting from 2017 i'm starting to use Django channels in my projects. The standard django MVT pattern is one of my favourite: linear, precise and very easy to manage/understand, i think that the lifecycle of Django app it's one of the best one developed (as far i know)... i think that the Django channels are the way to go for the future: a little "difficult" to learn for beginners, but definitively the way to go for modern async web-apps. I think that is better to include the channels to the "battery-pack-included" base of the framework in order to make the async "approach" easy to know, use and better document on the official django docs. What the Python-Django devs think about my thought?