Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
nginx Error 502 upstream prematurely closed connection while reading response header from upstream
I've been banging my head on this issue for days now and have finally reached a brick wall. When i navigate to the page in the browser, the page with hang for a few seconds, before getting the 502 Bad Gateway Screen. Any ideas anyone??? url https://sv1.stream05.xyz/link/?driveId=0BwHxX3yoJoeuYzZlNm1jYVhwWWs According to NGINX logs, NGINX says: 2020/11/04 18:56:31 [error] 14920#14920: *15 upstream prematurely closed connection while reading response header from upstream, client: 141.101.84.6, server: sv1.stream05.xyz, request: "GET /link/?driveId=0BwHxX3yoJoeuYzZlNm1jYVhwWWs HTTP/1.1", upstream: "http://127.0.0.1:6868/link/?driveId=0BwHxX3yoJoeuYzZlNm1jYVhwWWs", host: "sv1.stream05.xyz" nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; upstream LoadBalancer { server 127.0.0.1:6666; } upstream ProxyStream { server 127.0.0.1:6868; } server { listen 80; server_name proxy.stream05.xyz; location / { proxy_pass http://LoadBalancer; proxy_http_version 1.1; proxy_send_timeout 600; proxy_read_timeout 600; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } … -
Django check form field attribute in template
I need to check if a form field is disabled in the template. The field is disabled depending on some other factors but I've simplified it below. class MyForm(forms.Form): quantity = forms.IntegerField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['quantity'].disabled = True Then in the template I'd like to do something like this: {% if form.quantity.disabled is True %} ... {% endif %} -
How can I add a user to a predefined group on signup, using django and django-allauth?
I am using django-allauth. My users/formy.py contains this code: class CustomUserCreationForm(UserCreationForm): success_url = '/connections/' class Meta: model = User fields = ('email','password1') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) del self.fields['password2'] What do I need to modify to add the new user to a specific group, for example, a group called "basicuser"? -
import CSV as database Django
I'm trying to import data from a CSV file. I'm using this code: from django.db import models import csv # Create your models here. class Image(models.Model): name = models.IntegerField() # field - instance - row description = models.TextField(max_length=700) # field - instance - row mode = models.CharField(max_length=255) # field - instance - row celltype = models.CharField(max_length=255) # field - instance - row component = models.CharField(max_length=255) # field - instance - row doi = models.CharField(max_length=255) # field - instance - row organism = models.CharField(max_length=255) # field - instance - row def deleteAll(self): for img in self.objects.all(): img.delete() def ImportData(self): path = '/Users/macbookair/Downloads/source_project/images.csv' reader = csv.reader(open(path), delimiter=";", quotechar='"') next(reader) for row in reader: print(row) image = Image() image.name = row[1] image.description = row[2] image.mode = row[3] image.celltype = row[4] image.component = row[5] image.doi = row[6] image.organism = row[7] image.save() my CSV file looks like this: please click here But when I go to console to check my Image model, I find that it is empty! I'm checking this way: in console: python manage.py shell from myApp.models import Image image.objects.all() and I get: <QuerySet []> I already made the migrations using: python manage.py makemigrations myApp python manage.py migrate am I missing something? -
Django Locale not working after deploying to server
when i test it locally the translations do worked, but when I deploy it on a server it doesn't work. Some of the words do get translated but it's not from my locale, it's django's default translation. In settings.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] LANGUAGE_CODE = 'en-us' # LANGUAGE_CODE = 'zh-hans' # i also tried just putting language code as zh-hans but still ntg gets translated. TIME_ZONE = 'Asia/Kuala_Lumpur' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) For the LOCALE_PATHS it is correct as i put print(LOCALE_PATHS) in the settings and it gave me the right path to my locale "home/username/django_project/locale" I did do python manage.py makemessages -l zh_hans as well as python manage.py compilemessages and restarted my server but still the same. Btw I'm using AWS ubuntu and apache2. (Not apache problem as i tried python manage.py runserver 0.0.0.0:8000 before i even installed apache and it's still the same) My dev comp is windows and my server is ubuntu (not sure how it may help but yea) and there is no error at all there's just no translation. what could be the problem ? can … -
django display used template name in template
During development of projects with many model classes, views and forms, the wish to get the rendered template name, the used model class and form/view classes beeing displayed during template rendering in development mode arises. Is there a way to provide such information out of the box with the provided django toolbox ? This kind of information revealed during rendering of a template is only useful during development, of course, and should be disabled in production mode. -
When I try to start the Django server, the command line doesn't prompt anything
When I run python manage.py runserver it doesn't prompt anything. I don't get any errors, it just won't run. Does anyone know how to fix that? -
Django app on Nginx + Gunicorn. POST request failure - "500 Internal Server Error". Why?
I have a CentOS 7 VDS server with a Django app running on Nginx + Gunicorn setup. This application should be able to receive POST requests with medium size .docx files or large amount of text via textarea. And my problem is whenever I make POST request with files of any size OR with text larger than certain point (approx. 3/4 of A4 page) Nginx instantly throws 500 Internal Server Error. It does work with smaller texts in textarea just fine, though. I figured Nginx doesn't even send any request to Gunicorn server. Here's my nginx.conf file: worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; # Load dynamic modules. See /usr/share/doc/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; client_max_body_size 32M; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 10000; include /etc/nginx/mime.types; default_type application/octet-stream; # Load modular configuration files from the /etc/nginx/conf.d directory. # See http://nginx.org/en/docs/ngx_core_module.html#include # for more information. include /etc/nginx/conf.d/*.conf; server { client_max_body_size 32M; listen 80; server_name mysite.com; #либо ip, либо доменное имя access_log /var/log/nginx/example.log; location = /favicon.ico { access_log off; log_not_found off;} location /static/ { root /somepath/myapp/; expires 30d; } … -
Is there another way to annotate Count/Sum in existing queryset?
Let me illustrate the problem with canonical models Book&Author. Here is the view: class Report(ListView): ... def get_queryset(self): ... # calculating of filters return Book.objects.filter(status='published', date= ... a bunch of filters) So that we have a queryset with all necessary filters. It might be used in another functions, for example, to get the number of books: def books_number(self): qs = self.get_queryset() return qs.count() or cost of all these books: def summa(self): qs = self.get_queryset() return qs.aggregate(Sum('price')) Now, I want to get number of books by each Author and their costs and I would be happy with something like this: def authors_info(self): qs = self.get_queryset() return Author.objects.annotate(books_number=Count( use qs somehow ... ), books_cost = Sum( use qs over field 'price' somehow ...) ) but I haven't yet found a way to do that. Well, to get it working I used this: def authors_info(self): ... # calculating of THE SAME filters AGAIN q_ = Q(status='published', date= ... a bunch of filters) count_ = Count('book', filter=q_) sum_ = Sum('book__price', filter=q_) return Author.objects.annotate(books_number=count_, books_cost=sum_) but it definitely contradicts with DRY principle. Is still there more tidy way to get queryset in one function and to annotate it in another function? -
Chatting app like facebook can make by Go language? [closed]
I want to make a chatting app like facebook but I have no idea about it like login and send, receive massages. -
How I LOGIN in other website through my form
I tring to post in https://login.microsoftonline.com/common/login with login and password directly from my website form like it: <form method="post" action="https://login.microsoftonline.com/common/login" enctype="multipart/form-data" target="_blank"> <div> <label>Choose a file</label> <input type="text" id="file" name="login"> </div> <div> <label >Choose a file</label> <input type="text" name="passwd"> </div> <div> <button>GO To Sharepont</button> </div> </form> But when I clik in the button return erro from microsoft is missing a TOKEN. How can I login in other site through my site form? -
Django allauth Sendgrid django error IncompleteRead(0 bytes read, 116 more expected)
I am using Django allauth to verify users after email however I keep getting the error: IncompleteRead(0 bytes read, 116 more expected) Currently, my view for the signup view for handling after post request is: if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): storage = messages.get_messages(request) for _ in storage: pass for _ in list(storage._loaded_messages): del storage._loaded_messages[0] user = form.save(commit=False) #user.is_active = False user.save() send_email_confirmation(request, user, True) return redirect('main:user_login') My Sendgrid settings is: SENDGRID_API_KEY = 'myaapikey' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'my username' EMAIL_HOST_PASSWORD = 'mypassword' DEFAULT_FROM_EMAIL = DEFAULT_EMAIL And my allauth is: AUTH_USER_MODEL = 'main.Profile' ACCOUNT_EMAIL_VERIFICATION='mandatory' ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_EMAIL_REQUIRED= True ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = False ACCOUNT_EMAIL_SUBJECT_PREFIX = "JoinCampus " SOCIALACCOUNT_ADAPTER = 'main.adapters.SocialAccountAdapter' When I use the Django Email backend the email is being sent however when I use Sendgrid it doesn't work. However, if I use sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) The emails are being send successfully. -
Redirect user to another form based on their response in the current form
My user is completing a sign up form. If they indicate that they are an 'expert'(choice field) in the form displayed using the SignUpView, I want them to be redirected to the ExpertInformationView, otherwise I want them to be redirected to my homepage. How can I do this? # views.py class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' class ExpertInformationView(FormView): template_name = 'info_form.html' form_class = ExpertUserInformationForm success_url = reverse_lazy('information') # models.py class CustomUser(AbstractUser): __USER_STATUS = [('Member', 'Member'), ('Expert', 'Expert')] user_status = models.CharField( max_length=20, choices=__USER_STATUS, default=__USER_STATUS[0], # 'Member' ) phone_number = models.CharField(null=True, blank=True, max_length=30) -
Is there a way to make a depend dropdown in django open edx registration?
i'm working in OpenEdx and i'm trying to make a registration page that contains custom fields, state and city. here is my models.py: class City(models.Model): name = models.CharField('city', max_length=100, blank=True) uf = models.CharField('UF', max_length=2, choices=STATE_CHOICES) def __str__(self): return self.name class Meta: ordering = ('name',) verbose_name = 'cidade' verbose_name_plural = 'cidades' class UserProfileExtras(models.Model): user = models.OneToOneField( USER_MODEL, null=True, on_delete=models.CASCADE ) state = models.CharField( verbose_name="State", choices=STATE_CHOICES, max_length=100, ) city = models.CharField( verbose_name="Cidade", choices=CITY_CHOICES, max_length=100, null=True, ) and forms.py: class UserProfileExtrasForm(ModelForm): class Meta(object): model = UserProfileExtras fields = ('state', 'city') def __init__(self, *args, **kwargs): super(UserProfileExtrasForm, self).__init__(*args, **kwargs) self.fields['state'].label = _(u"Estado") self.fields['state'].error_messages = { "required": _(u"Selecione seu Estado."), "invalid": _(u"Estado inválido."), } self.fields['city'].label = _(u"Cidade") self.fields['city'].error_messages = { "required": _(u"Selecione sua cidade."), "invalid": _(u"Cidade inválida"), } i want to make the city dropdown appears only the selected state's cities thanks -
The QuerySet value for an exact lookup must be limited to one result
hello guys iam having issue in the underlying section as iam tring to print this comment section my models.py file iam trying to get the detailed page of any single post which contains post and comment form and previous comments but i am getting this errorThe QuerySet value for an exact lookup must be limited to one result using slicing. from django.db import models class Category(models.Model): name=models.CharField(max_length=60) def __str__(self): return self.name class Post(models.Model): title=models.CharField(max_length=60) body=models.CharField(max_length=500) created_on = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) categories = models.ManyToManyField('Category', related_name='posts') def __str__(self): return self.title class Comment(models.Model): author = models.CharField(max_length=60) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) post = models.ForeignKey('Post', on_delete=models.CASCADE) def __str__(self): return self.body And my views.py file is from django.shortcuts import render from django.http import HttpResponse from .models import * from .form import CommentForm def blog_index(request): post=Post.objects.all().order_by('created_on') context={ 'post':post } return render(request,'blog/blog_index.html',context) def blog_detail(request,id): posts = Post.objects.filter(categories__name__contains=category).order_by('-created_on') form = CommentForm() if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comment( author=form.cleaned_data["author"], body=form.cleaned_data["body"], post=posts ) comment.save() comments = Comment.objects.filter(post=posts) context = { "post": posts, "comments": comments, "form": form, } return render(request, "blog/blog_details.html", context) def category(request,Category): posts = Post.objects.filter(categories__name__contains=category).order_by('-created_on') context = { "category": category, "posts": posts } return render(request, "blog/blog_category.html", context) -
Django Admin Abstract Class
I have searched and come across answers for admin model for abstract database model. I am looking for abstract admin class, i.e. not database model class. I have some common admin functionality I wish to put in a abstract, class then inherit from it. Note: the getter_for_related_field is from https://github.com/PetrDlouhy/django-related-admin, since for some odd reason the Django team things foreign keys in list displays is a rare use case. class FactAdminAbstract(admin.ModelAdmin): foo__bar = getter_for_related_field( "foo__bar ", short_description="Foo Bar" ) foo__baz = getter_for_related_field( "foo__baz ", short_description="Foo Baz" ) date_hierarchy = "created" # Remove the delete selected bulk action def get_actions(self, request): actions = super().get_actions(request) if "delete_selected" in actions: del actions["delete_selected"] return actions @classmethod def build_list_display(cls, *custom): cls.list_display = ( "created", *custom, "foo__bar", "foo__baz", ) cls.list_display_links = cls.list_display @classmethod def build_list_filter(cls, *custom): cls.list_filter = ( "created_utc", *custom, "foo__bar", "foo__baz", ) Then trying to use it like: @admin.register(Cannon) class CannonAdmin(FactAdminAbstract): FactAdminAbstract.build_list_display('cannon_ball') FactAdminAbstract.build_list_filter('cannon_ball') @admin.register(Pogo) class PogoAdmin(FactAdminAbstract): FactAdminAbstract.build_list_display('pogo_stick') FactAdminAbstract.build_list_filter('pogo_stick') But then it seems like Django blurs the models, and combines the two instances that both inherit from the same abstract base class. <class 'CannonAdmin'>: (admin.E108) The value of 'list_display[1]' refers to 'pogo_stick', which is not a callable, an attribute of 'CannonAdmin', or an attribute or … -
How can I log local variables of the view function in Django when DEBUG is off?
I'm trying to implement something like Django's yellow exception HTML page, where it has the stacktrace, local and global variables. And I want to log that info to a file on production where DEBUG=False. I tried a custom middleware and only managed to log the stacktrace and the global variables, but most importantly I need to log the local variables of the views function or view class -
How to extract a variable from html(Jinja2) to python for modify a variable?
The situation is the next. I have a variable got from input in the html(jinja2) but I need to export it to python for change a variable that is in my python file. <input type="number" name="DateO"/> <input type="number" name="DateT"/> I want to take "DateO" and "DateT" for a python variable. pdt: I'm using Django -
Why is it not possible to use the AsyncClient to login without using sync_to_async?
According to the documentation about testing async functions in Django 3.1, it should be possible to simply await the async client methods in an async context without having to wrap it in sync_to_async or database_sync_to_async as it implements all methods. Is there a way around this? The first request works, but the second and third do not. class TestAsyncClient(TransactionTestCase): def setUp(self): self.async_client = AsyncClient() self.user = get_user_model().objects.create_user("user_a@example.com", "passwd_a") async def test_async_login(self): """Use the async client to login without using sync_to_async""" request = await self.async_client.get("/") self.assertTrue(request) logged_in = await self.async_client.login( username="user_a@example.com", password="passwd_a" ) self.assertTrue(logged_in) logged_in = await self.async_client.force_login(self.user) self.assertTrue(logged_in) -
Add user group as class name to body tag? Django/Wagtail
Is there a way of editing the body tag classes so that when each user logs in their group name is included in the html body class name. I want to do this so i can edit fields and permissions with javascript as some features that i need are not possible with standard Wagtail. Thanks -
How to create dict in django model having same brokers who having diffrenet boats?
Models.py :. class Match(models.Model): rep_broker = models.ForeignKey('account.User', related_name='rep_broker',on_delete=models.CASCADE,blank=True,null=True) boat = models.ForeignKey('boat.Boat', related_name='matches', on_delete=models.CASCADE) How to query the Match model to get the output like "rep_broker have 3 boats matching" table example: broker1 | boat1 broker1 | boat2 broker2 | boat3 output : broker1 have 2 boats matching broker2 have 1 boat matching Output should be in dictionary. -
How to run django_cron from crontab
With the below command, I am trying to run django_cron from the CLI (as it is not working from crontab). sudo -u www-data /path/to/venv/bin/python3 /path/to/web/manage.py runcrons my_custom_app.cron.myCronCommand --force --settings=mysite.settings.dev Annoyingly though, it is telling me that it cannot connect to an sqlite database, this is even though my sites base.py settings files (which dev inherits) is using mysql (and the browser shows it working just fine). So I imagine I must be not using the --settings command correctly, as I would have thought that this command would tell it to use the file in mysite/settings/dev.py. Any pointers would be greatly appreciated. -
Django 3.1.1 Static files Not Found
Currently having an issue where my static resources aren't loading after I host on Heroku. This is the error I'm getting: DevTools Error My urls.py: urlpatterns = [ path('', include('doppelganger.urls')), path('admin/', admin.site.urls), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "doppelganger/static"), ] Directory structure: project setting.py urls.py wsgi.py doppelganger static js img css Django version: 3.1.1 Python version: 3.8.6 I have tried running python manage.py collectstatic and I'm still seeing the same errors. Any other suggestion I can try to help fix "GET /static/css/beta_main.css HTTP/1.1" 404 Not found ? -
How can I get all results containing elasticsearch-dsl query keyword?
When I query my PostDocument it returns the results that only contain full words from the query. For example if there were 4 posts: "Post 1" "Post 2" "Posts 3" "Po 4" and I query it with: posts = PostDocument.search().query('match', body="Post") it will return items 1 and 2, if body="Po" it will return only item 4. How can I write the query so it returns all the results that contain the keyword? For example if I did this body="Po" I would get all 4 items. -
PostListView is missing a QuerySet. Define PostListView.model, PostListView.queryset, or override PostListView.get_queryset()
I am facing this error i need help. I am trying to add two models in a single class view to be displayed in a same template here is my django view code. class PostListView(ListView): template_name = 'blog/videography.html' ordering = ['-date_posted'] paginate_by = 5 def get_context_data(self, **kwargs): context = super(ProjectListView, self).get_context_data(**kwargs) context['videosleft'] = VideoLeft.objects.all() context['videosright'] = VideoRight.objects.all() return context def videography(request): context = { 'videosleft': VideoLeft.objects.all(), 'videosright': VideoRight.objects.all() } return render(request, 'blog/videography.html', context) here is my django model code. class VideoLeft(models.Model): titlel = models.CharField(default='Enter A Name Identification !', max_length=200) linkleft = models.URLField(max_length=1000) contentleft = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.titlel def get_absolute_url(self): return reverse('video-detail', kwargs={'pk': self.pk}) class VideoRight(models.Model): titler = models.CharField(default='Enter A Name Identification !', max_length=200) linkright = models.URLField(max_length=1000) contentright = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.titler def get_absolute_url(self): return reverse('video-detail', kwargs={'pk': self.pk}) here is my django url code. here is my django url code. here is my django url code. here is my django url code. here is my django url code. urlpatterns = [ path('', views.home, name='blog-home'), # path('video/<int:pk>/', PostDetailView.as_view(), name='video-detail'), path('video/new/', PostCreateView.as_view(), name='video-create'), path('video/<int:pk>/update/', PostUpdateView.as_view(), name='video-update'), path('video/<int:pk>/delete/', PostDeleteView.as_view(), name='video-delete'), path('photography/', views.photography, name='blog-photography'), path('articles/', views.articles, name='blog-articles'), …