Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Writing Django signup form tests for checking new user creation
Implemented a custom user model in Django and allows user to signup using the url http://127.0.0.1:8000/users/signup/. A GET request on this url is displayed like this: I have written tests for this page. Tests for get is working as expected. I wrote test for post with the intention that the post would create a user in the test database. After which I could write tests to confirm if an user is created and whether the username matches and so on. But it seems the user is not getting created. Below are my tests class SignUpPageTests(TestCase): def setUp(self) -> None: self.username = 'testuser' self.email = 'testuser@email.com' self.age = 20 self.password = 'password' def test_signup_page_url(self): response = self.client.get("/users/signup/") self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, template_name='signup.html') def test_signup_page_view_name(self): response = self.client.get(reverse('signup')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, template_name='signup.html') def test_signup_form(self): response = self.client.post(reverse('signup'), data={ 'username': self.username, 'email': self.email, 'age': self.age, 'password1': self.password, 'password2': self.password }) self.assertEqual(response.status_code, 200) users = get_user_model().objects.all() self.assertEqual(users.count(), 1) The users.count() turns out to be 0 and my test is failing. Where am I going wrong? -
Django: When is on_delete=DO_NOTHING useful?
When using a ForeignKey in a Django model, you can specify the on_delete argument, which defaults to CASCADE. There are multiple other options available and one of it is DO_NOTHING. The description for this option in the Django documentation is as follows: DO_NOTHING [source] Take no action. If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add an SQL ON DELETE constraint to the database field. Honestly, I do not fully understand what it actually does and when it's useful to choose DO_NOTHING. Can someone provide an example and explain the effect? -
Django's post_delete signal not being called
I've used signals a lot of times, however, I have a post_delete signal that is not being called: @receiver(post_delete, sender=Book) def book_deleted(sender, instance, **kwargs): .... The signal is being imported, so it should be called, however, when I do: book = Book.objects.get(id=book_id) book.delete() the signal is not being called, what may be going on? Thanks in advance -
submit form without refreshing the page
I created form contains title, content and image. I try to submit that form without refreshing the whole page using with django with ajax. When I submit the form POST method is okay but I get another GET method showing this error. GET http://127.0.0.1:8000/media/default.jpg [HTTP/1.1 404 Not Found 8ms] And I didn't declare default image in my model.py. Here is my views.py def posts(request): posts = Post.objects.filter(posted_date__lte=timezone.now()).order_by('-posted_date') if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() else: form = PostForm() args = { 'form': form, 'posts': posts, } if request.is_ajax(): html = render_to_string('posts/post-section.html', context=args, request=request) return JsonResponse({'pos':html}) return render(request, 'posts/posts.html', args) also here is my ajax $(document).on('submit', '.post-form', function(event){ event.preventDefault(); console.log($(this).serialize()); $.ajax({ type: 'POST', url: $(this).attr('action'), data: $(this).serialize(), dataType: 'json', success: function(response){ $('.post-section').html(response['pos']); }, error: function(rs, e){ console.log(rs.responseText); }, }); }); What should I do to submit that post without refreshing the page? -
Why isn't the method in my sub-classed form being called
I have a form which I am subclassing in order to change one method (get_json_filename). The form is something like class BackgroundForm(BetterModelForm): ... def get_json_filename(self): print("FRONT") return os.path.realpath(PROJECT_ROOT + '/form_data/background_info/' + self.curr_context['instrument'] + '_front.json') #Initiation of form. Set values, page format according to crispy forms, store variables delivered by views.py, and organize fields on the form. def __init__(self, *args, **kwargs): self.curr_context = kwargs.pop('context', None) super(BackgroundForm, self).__init__(*args, **kwargs) self.filename = self.get_json_filename() .... .... And my subclassed from is simply class BackpageBackgroundForm(BackgroundForm): def get_json_filename(self): print("BACK") return os.path.realpath(PROJECT_ROOT + '/form_data/background_info/' + self.curr_context['instrument'] + '_back.json') The get_json_filename called when using the subclassed form is the method from the original form. How do I fix this? -
Django cascade deletion not calling signal
I have a model: class Book(models.Model): ... And another model: class Chapter(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) Then I have a post_delete signal defined on Chapter. The signal is successfuly called when I delete a chapter, how ever, it is not being called when I delete a book. What should I have to do in order to get the signal called when deleting the chapters as result of deleting a book in cascade mode? Thanks in advance -
Activating and deactivating comments not working properly in panel admin
After activate a comment by checking the active box to showing that comment to the user on template, everything seems good but after deactivating that comment again, it makes a new instance or in another word copying that comment in panel admin as an active, it's like duplicating the comments after unchecking the active box. I am using Postgresql database, Is that possible this issue came from database? models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=False) class Meta: ordering = ('created',) def __str__(self): return 'Comment by {} on {}'.format(self.name, self.post) forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('name', 'email', 'body') views.py def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) # List of active comments for this post comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': # A comment was posted comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() else: comment_form = CommentForm() … -
Django - DoesNotExist
I am getting this error after I deployed my app to pythonanywhere. Everything worked fine in development. File "/home/AndrewsBRN/django_todo_app/memberships/models.py", line 47, in post_save_usermembership_create free_membership = Membership.objects.get(membership_type='Free') File "/usr/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/lib/python3.7/site-packages/django/db/models/query.py", line 399, in get self.model._meta.object_name memberships.models.DoesNotExist: Membership matching query does not exist. I tried to remove 'django.contrib.sites' as per another solution to this error here on SO, but that does not work. memberships/models.py from django.conf import settings from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from datetime import datetime import stripe stripe.api_key = settings.STRIPE_SECRET_KEY MEMBERSHIP_CHOICES = ( ('Enterprise', 'ent'), ('Professional', 'pro'), ('Free', 'free') ) class Membership(models.Model): slug = models.SlugField() membership_type = models.CharField( choices=MEMBERSHIP_CHOICES, default='Free', max_length=30) price = models.IntegerField(default=15) stripe_plan_id = models.CharField(max_length=40) def __str__(self): return self.membership_type class UserMembership(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) stripe_customer_id = models.CharField(max_length=40) membership = models.ForeignKey( Membership, on_delete=models.SET_NULL, null=True) website = models.URLField(default='', blank=True) member = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username def post_save_usermembership_create(sender, instance, created, *args, **kwargs): user_membership, created = UserMembership.objects.get_or_create( user=instance) if user_membership.stripe_customer_id is None or user_membership.stripe_customer_id == '': new_customer_id = stripe.Customer.create(email=instance.email) free_membership = Membership.objects.get(membership_type='Free') user_membership.stripe_customer_id = new_customer_id['id'] user_membership.membership = free_membership user_membership.save() post_save.connect(post_save_usermembership_create, sender=settings.AUTH_USER_MODEL) settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '***' LANGUAGE_CODE = 'en-us' … -
How to write a mptt custom manager to filter active fields on get_queryset method?
I have a model 'Category' based on mptt model. I want to filter my queryset on basis of a field 'active'. But I dont want to change it in admin level. i.e let i have a model 'all_objects' which will be TreeManager and 'objects' which will be 'modifiedTreeManager' returning only active queryset. I want to use objects in my views and all_objects in admin. I tried doing it but some methods like instance.get_descendants() working on the basis of 'all_objects' and not with 'objects'. class modifiedTreeManager(TreeManager): def get_queryset(self): return super(modifiedTreeManager, self).get_queryset().filter(active=True) class Category(MPTTModel): ... active=models.BooleanField(default=True) all_objects = TreeManager() objects = modifiedTreeManager() I also tried to change the _tree_manager value to objects but i dont know how to do it and if there will be any result of doing so. -
What Do you Return in Django if Ajax Request is successful?
I have made an Ajax request from a Javascript File to my Python views file in django which is successful but I am unsure what should be my return value. data_from_ajax = request.POST['data'] # do something with the data return ? I have tried returning HttpResponse("success") but the Ajax call in javascript still runs the error function. What is the correct return value for a successful ajax request? -
bootstrap datepicker not loading django
i have this jquery error while loading: base.html: {% load static%} <!doctype html> 3<html lang="en"> <head> <meta charset="utf-8"> <title>Celebizz</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Site Description Here"> <link href= {% static 'main_site/css/bootstrap.css' %} rel="stylesheet" type="text/css" media="all" /> <link href={% static "main_site/css/stack-interface.css" %} rel="stylesheet" type="text/css" media="all" /> <link href={% static "main_site/css/socicon.css" %} rel="stylesheet" type="text/css" media="all" /> <link href={% static "main_site/css/lightbox.min.css" %} rel="stylesheet" type="text/css" media="all" /> <link href={% static "main_site/css/flickity.css" %} rel="stylesheet" type="text/css" media="all" /> <link href={% static "main_site/css/iconsmind.css" %} rel="stylesheet" type="text/css" media="all" /> <link href={% static "main_site/css/jquery.steps.css" %} rel="stylesheet" type="text/css" media="all" /> <link href={% static "main_site/css/theme.css" %} rel="stylesheet" type="text/css" media="all" /> <link href={% static "main_site/css/custom.css" %} rel="stylesheet" type="text/css" media="all" /> <link href="https://fonts.googleapis.com/css?family=Open+Sans:200,300,400,400i,500,600,700%7CMerriweather:300,300i" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <script src={% static "main_site/js/jquery-3.1.1.min.js" %}></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <style> .my-nav{ background-color: rgb(28, 18, 157) !important } li.dropdown:hover > ul.dropdown-menu { display: block; } .nav-font{ color:white !important; } </style> </head> <!--end bar--> <!--end of notification--> <div class="nav-container "> <div class="bar bar--sm visible-xs"> <div class="container"> <div class="row"> <div class="col-3 col-md-2"> <a href={% url 'mainsite-index' %}> <img class="logo logo-dark" alt="logo" src={% static "main_site/img/logo.png" %} /> <img class="logo logo-light" alt="logo" src={% static "main_site/img/logo.png" %} /> </a> </div> <div class="col-9 col-md-10 text-right"> <a href="#" class="hamburger-toggle" data-toggle-class="#menu1;hidden-xs"> <i …