Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: is_valid() method is always false why?
Everytime i get the stu_name variable value from form without using is_valid() function then stu_name is always return value enter by user but with is_valid() stu_name is always None.I do some experiments and i found that is_valid() is always return false but why? This is views.py file code. from django.shortcuts import render from django.http import HttpResponse from .models import student from .forms import student_data def my_data(request): stu_name=None myform=student_data(request.POST) if (request.method=="POST" and myform.is_valid()): stu_name=myform.cleaned_data['user'] else: myform=student_data return render(request,'show.html',{'student':stu_name}) This is my html file where the form code is written. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div> <form action="/payment/show/" method="POST"> {% csrf_token %} <label for="">Name</label> <input type="text" name="user" required> <label for="">ID</label> <input type="number" required> <label for="">Address</label> <input type="text" required> <button type="submit">Add Me</button> </form> </div> </body> </html> forms.py file code. from django import forms class student_data(forms.Form): name=forms.CharField(widget=forms.TextInput,max_length=20) id=forms.IntegerField(widget=forms.NumberInput,max_value=6) address=forms.CharField(widget=forms.TextInput,max_length=50) -
Is it possible to refer to button in this way?
Is it possible to turn to a certain button on an HTML page and dictate certain actions to it and if no how? views.py if request.method == 'POST': if request.POST.get('abc'): ...... if request.POST.get('bbc'): ..... html <form action="{% url 'new_channel' %}" method = "post"> {% csrf_token %} <button name="abc" type="submit"></button> ....... <button name="bbc" type="submit"></button> </form> Thanks in advance. -
Flutter Connection refused ,errno = 111
Django is the backend, i checked everything and it works fine.Mongodb is connected too ,tried 10.0.2.2 and localhost option too.Same problem . Can anybody help? E/flutter (26845): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: SocketException: OS Error: Connection refused, errno = 111, address = 127.0.0.1, port = 58759 E/flutter (26845): #0 IOClient.send (package:http/src/io_client.dart:33:24) E/flutter (26845): <asynchronous suspension> E/flutter (26845): #1 BaseClient._sendUnstreamed (package:http/src/base_client.dart:176:38) E/flutter (26845): #2 BaseClient.post (package:http/src/base_client.dart:58:7) E/flutter (26845): #3 post.<anonymous closure> (package:http/http.dart:70:16) E/flutter (26845): #4 _withClient (package:http/http.dart:166:20) E/flutter (26845): #5 post (package:http/http.dart:69:5) E/flutter (26845): #6 _SignupScreenState.createUser (package:socialmediaproject/screens/signup_screen.dart:25:42) E/flutter (26845): #7 _SignupScreenState.build.<anonymous closure>.<anonymous closure> (package:socialmediaproject/screens/signup_screen.dart:152:42) E/flutter (26845): #8 State.setState (package:flutter/src/widgets/framework.dart:1148:30) E/flutter (26845): #9 _SignupScreenState.build.<anonymous closure> (package:socialmediaproject/screens/signup_screen.dart:151:27) E/flutter (26845): #10 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14) E/flutter (26845): #11 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36) E/flutter (26845): #12 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24) E/flutter (26845): #13 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11) E/flutter (26845): #14 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5) E/flutter (26845): #15 BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:236:7) E/flutter (26845): #16 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27) E/flutter (26845): #17 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:222:20) E/flutter (26845): #18 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22) E/flutter (26845): #19 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7) E/flutter (26845): #20 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7) E/flutter (26845): #21 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7) E/flutter (26845): #22 _rootRunUnary (dart:async/zone.dart:1138:13) E/flutter (26845): #23 _CustomZone.runUnary (dart:async/zone.dart:1031:19) E/flutter (26845): #24 _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7) E/flutter (26845): #25 _invoke1 (dart:ui/hooks.dart:273:10) E/flutter (26845): #26 _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5) E/flutter (26845): -
ModuleNotFoundError: No module named 'moviepy' in Django although installed
I have installed MoviePy within the virtual environment like this: (env)$: sudo pip install ez_setup Requirement already satisfied: ez_setup in /usr/local/lib/python2.7/dist-packages (env)$: sudo pip install moviepy Requirement already satisfied: moviepy in /usr/local/lib/python2.7/dist-packages Requirement already satisfied: decorator<5.0,>=4.0.2 in /usr/local/lib/python2.7/dist-packages (from moviepy) Requirement already satisfied: numpy in /usr/local/lib/python2.7/dist-packages (from moviepy) Requirement already satisfied: proglog<=1.0.0 in /usr/local/lib/python2.7/dist-packages (from moviepy) Requirement already satisfied: requests<3.0,>=2.8.1 in /home/ac3l1k/.local/lib/python2.7/site-packages (from moviepy) Requirement already satisfied: tqdm<5.0,>=4.11.2 in /usr/local/lib/python2.7/dist-packages (from moviepy) Requirement already satisfied: imageio<2.5,>=2.0 in /usr/local/lib/python2.7/dist-packages (from moviepy) Requirement already satisfied: idna<2.8,>=2.5 in /home/ac3l1k/.local/lib/python2.7/site-packages (from requests<3.0,>=2.8.1->moviepy) Requirement already satisfied: urllib3<1.25,>=1.21.1 in /home/ac3l1k/.local/lib/python2.7/site-packages (from requests<3.0,>=2.8.1->moviepy) Requirement already satisfied: certifi>=2017.4.17 in /home/ac3l1k/.local/lib/python2.7/site-packages (from requests<3.0,>=2.8.1->moviepy) Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /home/ac3l1k/.local/lib/python2.7/site-packages (from requests<3.0,>=2.8.1->moviepy) Requirement already satisfied: enum34 in /home/ac3l1k/.local/lib/python2.7/site-packages (from imageio<2.5,>=2.0->moviepy) Requirement already satisfied: futures in /usr/local/lib/python2.7/dist-packages (from imageio<2.5,>=2.0->moviepy) Requirement already satisfied: pillow in /usr/lib/python2.7/dist-packages (from imageio<2.5,>=2.0->moviepy) The installations are successful as you can see in the outputs above. But when I use moviepy in my models.py of my Django project, then I get: ModuleNotFoundError: No module named 'moviepy' The command pip freeze gives me the following list of installed modules: cffi==1.13.2 cryptography==2.8 dj-database-url==0.5.0 Django==2.2.7 django-extensions==2.2.5 django-filter==2.2.0 django-secure==1.0.1 django-sslserver==0.22 djangorestframework==3.10.3 ez-setup==0.9 Pillow==6.2.1 pkg-resources==0.0.0 pycparser==2.19 pyOpenSSL==19.1.0 pytz==2019.3 six==1.13.0 sqlparse==0.3.0 The moviepy module … -
Djanog loging page [closed]
Hallo, the dropdown list cannot be opened on the login page. I used: the Django authentication system django.contrib.auth, bootstrap-4.2.1.min.js jquery-3.3.1.min.js popper-1.12.9.min.js <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle active" href="#" id="dropdown-projects" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">{% trans 'base.projects' %}</a> <div class="dropdown-menu" aria-labelledby="dropdown-user"> <a class="dropdown-item" href="{% url 'projects:index' %}">{% trans 'base.overview' %}</a> <span class="dropdown-item">------------</span> {% for project in projects %} <a class="dropdown-item" href="{% url 'projects:detail' project.id %}">{{project.project_number}} {{project.unmod_name}}</a> {% endfor %} </div> </li> -
Google Cloud Storage Signed URL with Google App Engine using Django with Search Filters
I have the following model with relevant fields. When I create an api with all the model fields returning correctly, I need to add a dynamic field for the "signed url" for providing access for a particular authorized user along with actual google storage url : class VideoEntityFilterSerializer(serializers.ModelSerializer): class Meta: model = Entity fields = ('uuid', 'description', 'url', 'segment_start', 'segment_end', 'confidence', 'username', 'userid', 'videouuid', 'videotitle') class VideoEntityList(generics.ListAPIView): model = Entity serializer_class = VideoEntityFilterSerializer queryset = Entity.objects.all() filter_backends = [filters.SearchFilter] search_fields = ['videouuid', ] pagination_class = StandardResultsSetPagination How can I achieve this ? -
Intermediate data - Class methods vs functions [closed]
After my app receives data from an external source a lot of functions are called on the data. This to make normalizations, calculations etc. before the data is saved in a Model. What is best practice? To use functions to transform the data e.g. intermed = normalize(intermed intermed = calculate_totals(intermed) To create a special Class with methods e.g. intermed = IntermediateClass() intermed.title.normalize() To create intermediate fields in the ModelClass, that don't get saved to the db. mymodel.calculate_temp_totals() mymodel.save() Any ideas. Thanks in advance. -
CORS headers working on one browser, and not another
I can't work out why I'm getting a CORS failure on one browser and not another. Backend : Django with rest apis & CORS - localhost:8000 Frontend : Elm running on a python simple HTTP server - localhost:1234 Machine 1: Works fine with both Vivaldi and Chrome. But don't see the headers in the inspection Content-Length: 435 Content-type: text/html Date: Wed, 25 Mar 2020 11:41:31 GMT Last-Modified: Tue, 24 Mar 2020 19:48:48 GMT Server: SimpleHTTP/0.6 Python/3.8.1 Machine 2: Works fine with chrome, but Vivaldi gets a CORS error: Access to XMLHttpRequest at 'http://localhost:8000/api/adventures/1' from origin 'http://localhost:1234' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Chrome inspection response headers: Access-Control-Allow-Origin: * Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS Content-Length: 157 Content-Type: application/json Date: Wed, 25 Mar 2020 12:11:00 GMT Server: WSGIServer/0.2 CPython/3.8.0 Vary: Accept, Origin, Cookie X-Content-Type-Options: nosniff X-Frame-Options: DENY Which I found odd - different server!! (the django server???) - so I shut down all python processes (virtual envs, the current server), then started them up again. Then I see it's the same as the other headers, with no cors info, but still works! Content-Length: 435 Content-type: text/html Date: Wed, 25 Mar 2020 … -
React Native (Android) with Django Rest Framework - TypeError: Network Request Failed
Trying to set up fetch request for the first time in react native, but I end up with an error screen. I have already made sure my server is running on my inet address but the device just wouldn't send the fetch request. The Django server is running on 192.168.0.10 (port 8000) which is my inet address. Also, I am using an externally connected Android device (via USB). Registration.js componentDidMount() { fetch('http://192.168.0.10:8000/api/registration1/', { // fetch('http://10.0.2.2:8000/api/registration1/', { method: 'GET', // or 'PUT' headers: { 'Content-Type': 'application/json', Accept: 'application/json', }, }) .then(response => { console.log('I AM IN'); return response.json(); }) .then(data => { console.log('Success:', data); }) .catch(error => { console.error('Error:', error); }); console.log(' COMPONENT DID MOUNT OVER'); } I have enabled http support in my android.manifest file. Android.manifest <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.phone_app"> <uses-permission android:name="android.permission.INTERNET" /> <application android:name=".MainApplication" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="false" android:usesCleartextTraffic="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="@string/app_name" android:configChanges="keyboard|keyboardHidden|orientation|screenSize" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" /> </application> </manifest> Here's the error I get: -
Wagtail-API: django-filter (2.2.0) doesn't seem to work with the api
I tried to get django-filter running with the wagtail-api but it doesn't seem to work. Maybe i did something wrong. Thanks in advance for your help. This my class i used for api/v2: class MyPageClass(PagesAPIEndpoint): model = HomePage PagesAPIEndpoint.filter_backends = (filters.DjangoFilterBackend,) PagesAPIEndpoint.filterset_fields = { 'title': ['icontains'], 'id': ['exact'], } class Meta: fields = ( 'title', 'id', 'tags', ) I tried also this version for the api/v2: class MyPageClass(PagesAPIEndpoint): model = HomePage filter_backends = (filters.DjangoFilterBackend,) filterset_fields = { 'title': ['icontains'], 'id': ['exact'], } class Meta: fields = ( 'title', 'id', 'tags', ) And this is my code for my custom endpoint for the pages: class WebPageListAPIView(ListAPIView): queryset = WebPage.objects.all() serializer_class = PagesSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_fields = { 'profiles': ['exact'], 'tags': ['exact'], } Normally if i use django-filter it will show up the filter button in the api browser but not with the PagesAPIEndpoint. Image without Filter Button based on PagesAPIEndpoint Image with Filter Button based on my own Endpoint -
Python Django safe increment / decrement
I want to build an api for a article amount management system for my store. With this I need to safely increment or decrement the amount of an article and log it with the user who executed it to the database. It should look like this: from django.db import models from django.contrib.auth.models import User class Article(models.Model): name = models.CharField(...) amount_in_store = models.IntegerField(...) ... class ArticleAmountChange(models.Model): article = mdoels.ForeignKey(Article, ...) amount_change = models.IntegerField(...) user = models.ForeignKey(User, ...) ... But how can I guarantee the amount_in_store will always be the sum of all amount_changes for this article and still have a great performance? So I don't want to query over all ArticleAmountChange and sum the amount_changes because after some time of use there will be thousands of ArticleAmountChanges. Can you help me? -
I do not know how to make email confirmation for DRF and JWT
I stack with my challange. I am making DRF registration with JWT, and now need to confirm it with email. I do not have any idea, how to realize it -
Django: reverse_lazy() with a generic view
I have two generic views (CreateView and DetailView). In my CreateView after saving my form I want redirect to the DetailView to display my newly created object. But an error occured : Reverse for 'questions.views.DisplayQuestions' not found. 'questions.views.DisplayQuestions' is not a valid view function or pattern name. How can I call my DetailView with reverse_lazy ? .views: class DisplayQuestions(ListView): model = Question context_object_name = "all_questions" template_name = "questions/home.html" def get_queryset(self): return Question.objects.order_by(self.kwargs['display_type']) @method_decorator(login_required, name='dispatch') class CreateQuestion(CreateView): model = Question template_name = 'questions/nouveau.html' form_class = QuestionForm def get_success_url(self): return reverse_lazy(DisplayQuestion) # <-- This doesn't work !!! def form_valid(self, form): self.object = form.save(commit=False) self.object.profil = self.request.user.profil self.object = form.save() return HttpResponseRedirect(self.get_success_url()) .urls: urlpatterns = [ url(r'^nouveau$', views.CreateQuestion.as_view()), url(r'(?P<display_type>\w+)', views.DisplayQuestions.as_view()),] .forms: class QuestionForm(forms.ModelForm): class Meta: model = Question fields = ('question','categorie',) ``` -
Django Dev Server Module Whitenoise Not found
I'm trying to use Whitenoise in dev as suggested per the docs, but when I run the django dev server with the whitenoise module loaded in INSTALLED_APPS and MIDDLEWARE, as such: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth.backends.ModelBackend', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', ...other MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Yet when I make sure the module is installed using pip install whitenose, I get the error: ModuleNotFoundError: No module named 'whitenoise' Yet when I try pip install whitenoise I get: Requirement already satisfied: whitenoise in /Users/USERNAME/Development/venv/yourdash/lib/python3.7/site-packages (5.0.1) So I'm forced to run during dev without whitenoise. But because of this, I do run into issues as a result of different static files between dev/prod. So how can I ensure whitenoise will run while using the django dev server? -
Cannot access to the second user
I am learning Django 2.2 using chart js, I trying to display my user skill when changing the id in the URL. I have 2 users, it is working for the first but not the second. Here is the error: Profile matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8080/skills/2/ Django Version: 2.2 Exception Type: DoesNotExist Exception Value: Profile matching query does not exist. Here is my profile model, Profile => models.py : from django.db import models from django.contrib.auth.models import User from django.core.validators import FileExtensionValidator # Create your models here. class Profile(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) website = models.URLField(blank=True) avatar = models.ImageField(upload_to='uploads/img', validators=[FileExtensionValidator(allowed_extensions=['png'])], blank=True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) @property def get_created(self): return self.created.strftime("%m/%d/%Y, %H:%M:%S") def __str__(self): return "{}-{}".format(self.name, self.get_created) Here is my Skills models, Skills => models.py from django.db import models from profiles.models import Profile from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. class Skill(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) name = models.CharField(max_length=220) score = models.PositiveIntegerField( validators=[MinValueValidator(1), MaxValueValidator(5)]) def __str__(self): return "{}-{}-{}".format(self.user, self.name, self.score) Here is my Skills url, Skills => urls.py: from django.urls import path from .views import skill_view, UserChartView app_name = 'skills' urlpatterns = [ path('', skill_view, name='my-skills'), path('<profile_id>/', UserChartView.as_view(), name='user-skills'), ] Here … -
How to setup a model as default value of a OneToOne field in Django
I added a new model to my existing design to handle the new requirements. To do the migrations, existing data requires default values to keep up with new model designs. How to assign an empty object as default value. class NewModel(models.Model): somedata = models.IntegerField(default=0) class TheExistingModel(models.Model): data1 = models.IntegerField(default=0) newfield = models.OneToOneField(NewModel, on_delete=models.CASCADE, default= "?" ) The new field is added to the existing model and it requires a default value so that existing data in the database are updated. Also when new TheExistingModel instance is created the respective NewModel has to created. -
Django - which create() method to override before saving incoming data as object
I have the following model in my models.py file: class Video(models.Model): created = models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=100, blank=True) video = models.FileField(upload_to='Videos/', blank=True) gif = models.FileField(upload_to='Images/', blank=True) class Meta: ordering = ('created', ) Before Django creates an instance of this model, I want to set the gif field on the Django site. So, the data comes to Django from the client site with the field video set, and based on the video field's content I want to fill the gif field. For that, which create() method do I need to override for this task? The create() method of my VideoSerializer class in serializers.py : def create(self, validated_data): return Video(**validated_data) Or the create() method of my VideoCreate class in views.py: class VideoCreate(generics.CreateAPIView): queryset = Video.objects.all() serializer_class = VideoSerializer parser_classes = (MultiPartParser, ) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) Hope someone can help -
How can i call kotlin file function or function which is in .kt file from java script?
How can i call kotlin file function or function which is in .kt file from JavaScript file? In other words how can i import kotlin class in javaScript/.js file? -
How to fix this error django.db.utils.OperationalError: could not translate host name "db" to address . Docker
I am using Pyscopg. DOCKER-COMPOSE: version: '3.7' services: web: build: . command: python3 /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db2 db2: image: postgres:11 SETTINGS.PY: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db2', 'PORT': 5432 } } Getting this Error: django.db.utils.OperationalError: could not translate host name "db2" to address: Temporary failure in name resolution -
how to create charts based on fields in django
Hi I'm trying to create charts showing data counts for the country, gender, and organization fields which would change as I filter the data, can anyone help me with this, I'm still new with web development, and this is my first project. I want to show this in the index.html file index.html <!DOCTYPE html> <html lang="en"> {% load widget_tweaks %} <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="description" content="" /> <meta name="author" content="" /> <title>Dashboard - SB Admin</title> <link href="static/css/styles.css" rel="stylesheet" /> <link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css" rel="stylesheet" crossorigin="anonymous" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/js/all.min.js" crossorigin="anonymous"></script> </head> <body class="sb-nav-fixed"> <nav class="sb-topnav navbar navbar-expand navbar-dark bg-dark"> <a class="navbar-brand" href="index.html">Start Bootstrap</a><button class="btn btn-link btn-sm order-1 order-lg-0" id="sidebarToggle" href="#"><i class="fas fa-bars"></i></button ><!-- Navbar Search--> <!-- Navbar--> <ul class="navbar-nav ml-auto ml-md-0"> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" id="userDropdown" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><i class="fas fa-user fa-fw"></i></a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="userDropdown"> <a class="dropdown-item" href="#">Settings</a><a class="dropdown-item" href="#">Activity Log</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="login.html">Logout</a> </div> </li> </ul> </nav> <div id="layoutSidenav"> <div id="layoutSidenav_nav"> <nav class="sb-sidenav accordion sb-sidenav-dark" id="sidenavAccordion"> <div class="sb-sidenav-menu"> <div class="nav"> <div class="sb-sidenav-menu-heading">Core</div> <a class="nav-link" href="index.html" ><div class="sb-nav-link-icon"><i class="fas fa-tachometer-alt"></i></div> Dashboard</a > <div class="sb-sidenav-menu-heading">Interface</div> <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseLayouts" aria-expanded="false" aria-controls="collapseLayouts" ><div class="sb-nav-link-icon"><i class="fas … -
what should i do to remove the error of importing nltk as i have already installed it?
I have installed nltk and now it's not working, and I need assistance figuring out what's wrong. Installed via pip it is showing the error that " Please use the NLTK Downloader to obtain the resource" how to solve this? -
How to use django-hosts with Nginx
I have created one Django app which has two apps named "api" and "consumer". Now I want to use subdomains for both of this app. Like api.server.com and server.com. I searched online and found django-hosts so I implemented in my localhost and its working fine. After that I deployed it on AWS EC2 instance and created subdomain in Godaddy and point both root domain and subdomain to my instance IP. Root domain is working fine but when I try to go api.server.com, it shows me default Welcome to Nginx screen. Please help me with this issue. nginx.conf server{ server_name server.com, api.server.com; access_log /var/log/nginx/example.log; location /static/ { alias /home/path/to/static/; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } -
Django save default value in Proxy Model
Different proxy models should be different in type. If I query those models I the right ones. I am trying to save a default type field in a proxy model. I don't want to set it everytime in the view. This does not work. The type field is always "TYPE1". models.py: class MyModel(models.Model): class ModelType(models.TextChoices): TYPE1 = 'TYPE1', _('TYPE1') TYPE2 = 'TYPE2', _('TYPE2') type = models.CharField(max_length=100, choices=ModelType.choices, default='TYPE1') class Type2Manager(models.Manager): def get_queryset(self): return super(Type2Manager, self).get_queryset().filter(type='TYPE2') def save(self, *args, **kwargs): kwargs.update({'type': 'TYPE2'}) return super(Type2Manager, self).save(*args, **kwargs) class Type2ProxyModel(MyModel): class Meta: proxy = True objects = Type2Manager() views.py: def create_type2_model(request): form = Type2Form(request.POST, initial={}) f = form.save(commit=False) f.save() forms.py: class Type2Form(ModelForm): class Meta: model = Type2ProxyModel -
Nginx rewrite after proxy pass
I am using Django + Gunicorn to serve files and nginx as a static file server, you can see a part of the configuration file below location /static/ { root /some/folder; } location / { proxy_pass http://127.0.0.1:8080; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; } What I want to do is to access static files without putting /static/ into url. As I see it, if there is initially no /static/ in the url, than the request should be passed down to Django (/). If there is /static/, than then it should be cut away and the appropriate static file should be served. I heard this can be achieved with rewrite directive, however, I don't understand, how to make such a check for /static/ presence -
Django: How to correctyl use signals to send automatic email to user when new account is created?
I develop a Django porject and I use Django Authentification I have added an Profile models that is linked to User and Site models I want to use signal to send automatic email with username and password (plaintext) to user when user account is created I face many to problems: as User is linked to Site model by FK, site attribute in Profile can't be NULL; I resolved it for the moment adding a default value but it is not satisfactory User instance is created in two steps: first username and password are registered and if username and password are valid, user instance is created and in a second admin form we can set other attribute and particularly email -> currently, signal post_save is send after username and password are registered; I would like email to be send when USer instance is complete registered because I need email to be available... When created, password is encoded by pbkdf2/sha256 so kwargs['instance'].password return encoded password; How can I send user plaintext password? models.py class Profile(SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE pro_ide = models.AutoField(primary_key = True) user = models.OneToOneField(User, on_delete = models.CASCADE) site = models.ForeignKey(Site,default=1, on_delete = models.CASCADE) ... class Meta: db_table = 'adm_pro' verbose_name_plural …