Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Configure dockerized django app with EC2 and RDS
I am trying to deploy my dockerized django application which uses a RDS database to an EC2 instance. I set up RDS and EC2. Now I am trying to deploy there. I run the migrations first but I get the recurrent message: Waiting for PostgreSQL to become available... Waiting for PostgreSQL to become available... Waiting for PostgreSQL to become available... Waiting for PostgreSQL to become available... Waiting for PostgreSQL to become available... So something is not set up correctly. This is my config: base.py DATABASES = { # 'default': env.db('DATABASE_URL'), # This was the default value, but modification below seemed necessary 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env("POSTGRES_DB"), 'USER': env("POSTGRES_USER"), 'PASSWORD': env("POSTGRES_PASSWORD"), 'HOST': env("POSTGRES_HOST"), 'PORT': env("POSTGRES_PORT"), } } services: django: build: context: . dockerfile: ./compose/production/django/Dockerfile image: myprojcect_production_django env_file: - ./.envs/.production/.django - ./.envs/.production/.postgres command: /start caddy: build: context: . dockerfile: ./compose/production/caddy/Dockerfile image: myproject_production_caddy depends_on: - django volumes: - production_caddy:/root/.caddy env_file: - ./.envs/.production/.caddy ports: - "0.0.0.0:80:80" - "0.0.0.0:443:443" And finally in my environment files I have the info about my database instance: POSTGRES_DB=NameOfRDSInstance POSTGRES_HOST=EndpointOfRDSInstance POSTGRES_PASSWORD=passwod POSTGRES_PORT=5432 POSTGRES_USER=username I am not sure what to change in my configs. Also this app is running fine on Heroku with the same RDS database. I want to … -
unable to install mysqlclient for django in virtual environment
I am new to django I have created virtual enviroment of python3.6 while installing mysqlclient in virtual environment, it is showing bellow error (myVirtualEnv) [root@avinash helloWorld]# pip install mysqlclient Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/d0/97/7326248ac8d5049968bf4ec708a5d3d4806e412a42e74160d7f266a3e03a/mysqlclient-1.4.6.tar.gz Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/avinash/pythonProjects/myVirtualEnv/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-o154owc4/mysqlclient/setup.py'"'"'; __file__='"'"'/tmp/pip-install-o154owc4/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-vbtdntog --python-tag cp36 cwd: /tmp/pip-install-o154owc4/mysqlclient/ Complete output (30 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.6 creating build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.6/MySQLdb creating build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants running build_ext building 'MySQLdb._mysql' extension creating build/temp.linux-x86_64-3.6 creating build/temp.linux-x86_64-3.6/MySQLdb gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -Dversion_info=(1,4,6,'final',0) -D__version__=1.4.6 -I/usr/include/mysql -I/usr/include/mysql/mysql -I/usr/include/python3.6m -c MySQLdb/_mysql.c -o build/temp.linux-x86_64-3.6/MySQLdb/_mysql.o gcc -pthread -shared -Wl,-z,relro -g build/temp.linux-x86_64-3.6/MySQLdb/_mysql.o -L/usr/lib64/ -L/usr/lib64 -lmariadb … -
Django Logs out automatically when loggin in another django application targeting the same database
I am developing two different django projects targeting the same database. The problem is that whenever both of the projects are up and running, whenever I log in into one site, I am automatically logged out of the other. And whenever I log in the other I am logged out of the previous. I would like to user to remain logged in in the second website, but somehow django is not allowing that. I know that I could use some single sign on library but that is not the way I want to solve the problem at this point in time. My assumption is that whenever I log in Django changes the session key and is automatically logged out of the other site. My login is very simple as follows: def user_login(request, *args, **kwargs): form = UserLoginForm(request.POST or None) if form.is_valid(): # form.save() username_ = form.cleaned_data.get('username') user_obj = User.objects.get(username__iexact=username_) login (request, user_obj) return HttpResponseRedirect('/stations/process_list') return render(request, 'usermanagement/login.html', {'form': form }) How can I login without changing the session or wihtout being kicked out of the the other site? -
Postgresql DB not getting pushed to heroku server
I've followed every step to deploy my django app to heroku. But there seems to be an error with the databases. I have several models in my models.py. I already run all the commands like: heroku run python manage.py migrate , and also pushed my project to heroku using: git push heroku master I also have the requirements.tx file, the .gitignore file and the Procfile. The only problem seems to be with the databases. The exact error i am getting is: DoesNotExist at /home/ Logged matching query does not exist. where Logged is a model(table) settings.py: import os import django_heroku import dj_database_url BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'movr-ll5=08tw)ms51cs%^t0fl2t1e0o8f+ujz*f-fa*hb8ymj' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['eduvision1.herokuapp.com'] INSTALLED_APPS = [ 'testapp', 'Link1', 'Link2', 'Link3', 'Link4', 'Link5', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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 = 'testing.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'testing.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, … -
Django formset shows up in 1 app but not in the other
So I have this Django app relate. I want to use formset to display as many Topics I can. My problem is when I render the template nothing shows up. However, when I moved the relevant lines of code to another Django app which also uses formset, the formset works perfectly well. As much as I would want to move to the other app I wish I could try to develop from relate. I was thinking maybe there are implementations/imports that the other app has that allows it to implement my formset. But I examined everything and I haven't found any that I know of that can prevent my formset from working. I would really appreciate your help. Thanks in advance! models.py class Topic(models.Model): name = models.CharField(max_length=250) concepts = models.TextField() def __str__(self): return self.name forms.py class TopicForm(ModelForm): class Meta: model = Topic fields = ['name', 'concepts',] views.py def relate_topics(request, method="POST"): TopicFormSet = formset_factory(TopicForm, extra=2, max_num=10, can_delete=True) if request.method == "GET": formset = TopicFormSet(request.GET or None) elif request.method == "POST": formset = TopicFormSet(request.POST) if formset.is_valid(): for form in formset: form.save() return redirect('index') return render(request, 'relate/relate_topics.html', {'formset': formset,}) relate_topics.html <h1>Hey</h1> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} … -
Django not displaying two DetailView
Whenever I click on job_title link in index.html, django redirects me to detail url and from there it redirects to DetailView in views.py file and finally it opens detail.html file. Same thing I am doing for category link. But it gives me an error: No job found matching the query. (Page not Found Raised by: JobPanel.views.DetailView). I'm getting right slugs from the database to index.html. urls.py path('<slug:detail_slug>/', DetailView.as_view(), name='detail'), path('<slug:cat_slug>/', CategoryView.as_view(), name='category'), views.py class DetailView(generic.DetailView): model = Job template_name = 'JobPanel/detail.html' slug_url_kwarg = 'detail_slug' slug_field = 'slug' class CategoryView(generic.DetailView): model = Job template_name = 'JobPanel/category.html' slug_url_kwarg = 'cat_slug' slug_field = 'slug' index.html <a href="{% url 'jobpanel:detail' job.slug %}">{{ job.job_title }}</a> <br> {% for cat in job.categories.all %} <a href="{% url 'jobpanel:category' cat.slug %}">{{ cat }}</a> {% endfor %} models.py class Category(models.Model): category = models.CharField(max_length=100) slug = models.SlugField(unique=True) def __str__(self): return self.category class Job(models.Model): job_title = models.CharField(max_length=250) job_description = models.TextField() slug = models.SlugField(unique=True) -
Django Notifications Mark as read like face book
Hello I would like to create a notification . I am using django notification In this all the notifications are displaying and there is a cross bar with it . Once the user click the cross bar notification mark as deleted and it will not display again in the notification But I would like to display it like facebook Once the user check the notification Notifications icon will not show notification number (like 2 notifications) but they can read the notifications even if they click on it This is the view class NotificationFilterDataApi(ListAPIView): """ List of all Filter Records """ serializer_class = NotificationSerializer # overriding the method def get_queryset(self, *args, **kwargs): queryset_list = self.request.user.notifications.unread() filtered_dict = clean_filter_dict(self.request.GET.dict()) filter_query = NotificationFilter(filtered_dict, queryset=queryset_list) return filter_query.qs def list(self, request, *args, **kwargs): # call the original 'list' to get the original response response = super(NotificationFilterDataApi, self).list( request, *args, **kwargs) custome_data = notification_data_refactor(response.data) response.data = custome_data return_data = {"status": True, "data": response.data, "count": len(response.data)} response.data = return_data # return response with this custom representation return response def notification_data_refactor(notification_data): for each_notification in notification_data: id = each_notification.get('id') notification = None try: notification = Notification.objects.get(id=id) except Notification.DoesNotExist: logger.error("Notification not fount") each_notification.update( { "timeslice": notification.timesince() } ) return notification_data … -
How to call different functions of different apps by user agent in django?
I have the following Django project structure wherein I have two functions named 'get_profile' on both views. I want to open get_profile function from app1 in case if the user agent is desktop otherwise from app2. project --urls.py --app1 -- views.py -- urls.py --app2 -- views.py --urls.py Any suggestions on this would be highly appreciated. -
nginx/django file download permission
i have a django website running on ubuntu nginx where a user can upload image and another user can download the image. Problem is when i upload image from frontend then another user can view the image but can't download the original image and when i upload the image from backend its downloadable. i need to change file permission every time to download the image 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; client_max_body_size 100M; 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; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } default settings: server { listen 80; server_name 159.65.156.40; location = /favicon.ico { access_log off; log_not_found off; } location /static { root /home/tboss/liveimage; client_max_body_size 100M; } location /media/ { root /home/tboss/liveimage; } location / { include proxy_params; proxy_pass http://unix:/home/tboss/liveimage/liveimage.sock; } } -
How to make a django model with tree-data structure?
I am a beginner in python-django developing. I am building a new sample project and face this problem. This is my current models.py project code class DBItem(models.Model): orlHost = models.TextField() orlPort = models.TextField() orlServiceName = models.TextField() orlSchemaName = models.TextField() orlUserName = models.TextField() orlPassword = models.TextField() mysqlHost = models.TextField() mysqlPort = models.TextField() mysqlDatabaseName = models.TextField() mysqlUserName = models.TextField() mysqlPassword= models.TextField() def _str_(self): return self.orlHost but I want to make this structure with tree-style(parent-children): like this { "SourceDB": { "IsFile": true, "FilePath": "src.sql", "Host": "192.168.0.110", "Port": "1521", "ServiceName": "orcl.local", "SchemaName": "Test", "UserName": "oracle", "Password": "oracle" }, "DestinationDB": { "IsFile": true, "FilePath": "dst.sql", "Host": "192.168.0.110", "Port": "1521", "DatabaseName": "Test", "UserName": "root", "Password": "123456" } } how come I have to build the models.py(class DBItem) for this structure? -
Changing the contents of an input in a django form with request data in __init__()
I've got a django form which contains a TypedMultipleChoiceField containing a group of users. I got the users from the auth User model, but I want to remove the current logged in user form the choices. I've been trying to do this by bringing in the request data into the form's init method and then deleting the logged in user from the choices list, but for some reason the form still renders the logged in user in the list of choices. Code below: Views.py class IndexView(LoginRequiredMixin, generic.ListView, generic.edit.FormMixin): def get_form_kwargs(self): kwargs = super(IndexView, self).get_form_kwargs() kwargs.update({'request': self.request}) return kwargs def get_queryset(self): return Project.objects.filter(owner=self.request.user.id).order_by('begin_date') form_class = CreateProject context_object_name = 'project_list' template_name = 'projects/project_index.html' forms.py class CreateProject(forms.Form): contributor_id = forms.TypedMultipleChoiceField(choices=list(User.objects.values_list('id','username')), required=False, empty_value=[]) def __init__(self, *args, **kwargs): self.request = kwargs.pop("request") super(CreateProject, self).__init__(*args, **kwargs) choices = self.fields['contributor_id'].choices del choices[choices.index((self.request.user.id, self.request.user.username))] When I put in a pdb.set_trace() into the init method and check the state of the form fields after performing the delete everything looks correct. What am I doing wrong? For reference, I used this for the get_form_kwargs in views and init in forms. -
Error: 'Select a valid choice. That choice is not one of the available choices' when trying to submit a ModelForm
I am getting the error 'Select a valid choice. That choice is not one of the available choices' when trying to submit a ModelForm. The values being passed though from the front end look to be correct (the PK for each) and all required values are being provided yet it still doesn't return me any cleaned data I am still quite new to Django and googling hasn't got me results that work (Also I am using crispy forms for styling the front end) forms.py code = forms.CharField(required=True) itemtype = forms.ModelChoiceField(required=True, queryset=ItemType.objects.all()) location = forms.ModelChoiceField(required=True, queryset=Location.objects.all()) parent = forms.ModelChoiceField(required=False, queryset=Item.objects.all()) class Meta: model = Item fields = ['code', 'itemtype', 'location', 'parent'] def __init__(self, *args, **kwargs): super(CreateItemWithParentForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs = {'class': 'form-control'} self.fields['itemtype'].label_from_instance = lambda obj: "{0}".format(obj.name) self.fields['location'].label_from_instance = lambda obj: "{0}".format(obj.address) self.fields['parent'].label_from_instance = lambda obj: "{0}".format(obj.code) self.helper = FormHelper(self) self.helper.form_show_labels = True self.helper.form_id = 'createitemform' self.helper.layout = Layout( Fieldset("Create New Item", Field('code', css_class="mt-2", placeholder="Code", name="code", id="code"), Field('itemtype', css_class="mt-2", name="itemtype", placeholder="Item type", css_id="itemtype"), Field('location', css_class="mt-2", name="location", placeholder="Location", css_id="location"), Field('parent', css_class="mt-2", name="parent", placeholder="Parent Item", css_id="parent"), Button('createitemformbutton', 'Submit', css_class="btn-light"), css_class='border', ) ) views.py class CreateItemWithParent(FormView): """ create a new item with specified parent """ template_name = 'add_item.html' form_class = … -
Setting value of Django M2M through relationship via ModelForm
I am working on a set of product / category relationships in a Django application. A product can belong to any category and needs to be ordered within that category, I am trying to do this using a Many to Many relationship with a "through=" option. When a POST request is made via Ajax it takes the form of b'ordered_products=4&ordered_products=5', I received an error straight after the forms __init__ call that "5 is not one of the available choices" where 5 is the valid id of anOrderedCategoryManagedProduct object. # models.py class Category(models.Model): name = models.CharField(max_length=128) slug = models.SlugField(max_length=128, unique=True) class Product(models.Model): name = models.CharField(max_length=128) category_management = models.ManyToManyField( Category, related_name="category_managed_products", through="OrderedCategoryManagedProduct", blank=True, verbose_name="Category Management", ) class OrderedCategoryManagedProduct(SortableModel): category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name="cm_products" ) product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name="cm_categories" ) class Meta: ordering = ["sort_order"] def get_ordering_queryset(self): return self.product.category_management() class SortableModel(models.Model): sort_order = models.IntegerField(db_index=True, null=True) class Meta: abstract = True # views.py # POST = <QueryDict: {'ordered_products': [5, 4]}> @staff_member_required @permission_required("menu.manage_menus") def ajax_reorder_menu_items(request, category_pk): category = get_object_or_404(Category, pk=category_pk) form = ReorderCategoryProductsForm(request.POST, instance=category) status = 200 ctx = {} if form.is_valid(): form.save() elif form.errors: status = 400 ctx = {"error": form.errors} return JsonResponse(ctx, status=status) #forms.py class ReorderCategoryProductsForm(forms.ModelForm): ordered_products = OrderedModelMultipleChoiceField( queryset=OrderedCategoryManagedProduct.objects.none() … -
After for loop i get printed only one string path to image folder instead of multiple strings of images, python
I have iterated over folder media/images that containsall paths to that folder images using os.walk() function. After I did for in loop i get only one image in that folder and there is more then 115 i think of images of Dota2 heroes. I will show you the code and print screen so you can closely look. I think i made a mistake with for in loop some were but I new to python. insert_heroes.py (lines 15 to 18 are the one that iterate over my media/images folder.) import requests import json import os API_URL = 'http://127.0.0.1:8000' if __name__ == '__main__': r = requests.get("https://api.opendota.com/api/heroes") all_heroes_info = json.loads(r.content.decode('UTF-8')) for hero_info in all_heroes_info: name = hero_info['localized_name'] hero_type = hero_info['primary_attr'] for root, dirs, files in os.walk("../../media/images/", topdown=False): for image in files: pass print(image) keys = [name] values = [image] # dictionary = dist(zip(keys, values)) # print(dictionary) # print(keys) mutation_create_hero = ''' mutation ($name: String!, $heroType: String!, $image: String!) { createHero(name: $name, heroType: $heroType, image: $image) { name image } } ''' variables = {'name': name, 'heroType': hero_type, 'image': image} # localhost_api_response = requests.post( # '{}/graphql/'.format(API_URL), # json={ # 'query': mutation_create_hero, # 'variables': variables # } # ) What i get is this, when … -
Celery timeout in Django
There are altogether eight tasks running in celery in different periods. All of them are event-driven tasks. After a certain event, they got fired. And the particular task works continuously until certain conditions were satisfied. I have registered a task which checks for certain conditions for almost two minutes. This task works fine most of the time. But sometimes the expected behavior of the task is not attained. The signature of the task is as below: tasks.py import time from celery import shared_task @shared_task() def some_celery_task(a, b): main_time_end = time.time() + 120 while time.time() < main_time_end: ... # some db operations here with given function arguments 'a' and 'b' # this part of the task get execute most of the time if time.time() > main_time_end: ... # some db operations here. # this part is the part of the task that doesn't get executed sometimes views.py # the other part of the view not mentioned here # only the task invoked part some_celery_task.apply_async(args=(5, 9), countdown=0) I am confused about the celery task timeout scenarios. Does that mean the task will stop from where it timeouts or will retry automatically? It will be a great help if any clear idea about … -
I want to respond images with Django
I want Django to display an image when accessed. For example, I want to display only the image as a response, such as when accessing the image below. And I want to do the url as a normal URL without using .jpeg or .png. sample But now, no matter what method you try, it doesn't work. from django.http import HttpResponse import os from django.core.files import File import codecs def image(request): file_name = os.path.join( os.path.dirname(__file__), '12.jpg' ) try: with open(file_name, "rb") as f: a = f.read() return HttpResponse(a, content_type="image/jpeg") except IOError: red = Image.new('RGBA', (1, 1), (255, 0, 0, 0)) response = HttpResponse(content_type="image/jpeg") red.save(response, "JPEG") return response urlpatterns = [ url('image', image) ] With the above code, the following error occurs. 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte -
How to set multiple STATIC_URL for the same static data?
An already developed front end is making calls to the same static data files using different URLs GET /static/images/1.png and also using sometimes this: GET /SomeDirName/static/images/1.png Setting my STATIC_URL to "/static/" serve only the requests similar to the first example. Is it possible to redirect the GET from the second example? Or how can I handle it? Please note that Im not asking how to set STATICFILES_DIRS. -
google SMTP is giving error on sending mail
I am using python Django to send mail to a user when user login and using django.core.mail(send mail) but it's working on localhost and successfully sending emails to the user but when I host my site on Heroku it's giving some errors. settings.py # email config EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # During deployment only EMAIL_HOST = config('EMAIL_HOST') EMAIL_PORT = 587 EMAIL_HOST_USER = config('EMAIL_USER') EMAIL_HOST_PASSWORD = config('EMAIL_USER_PASSWORD') EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'Masjid Matrimonial Team <noreply@example.com>' Views.py currenttime=datetime.now() subject = "New Login Alert" message="You have loged into your account on "+ currenttime.strftime('%A %d %B,%Y %I:%M %p') recipient_list = [useris.appuser.email] send_mail( subject, message, email_from, recipient_list )email_from = settings.EMAIL_HOST_USER -
django requests,get not working for HTTPS URLs
I'm trying to call an api import requests response = requests.get('https://example.com/api/details/') But it does not give any response. I recently added SSL certificate for this url. it was working fine with http before I added SSL certificate. What am i doing wrong? -
Error on deploying django + uwsgi + nginx
I'm trying to deploy a django project with uWSGI and nginx. I have the next configuration files: uwsgi.ini [uwsgi] #Django-related settings chdir = /home/amlalchy/api_aml_platform module = api.wsgi #static-map = /static=/home/amlalchy/api_aml_platform/services/static #Process-related settings master = true processes = 10 # The socket(use the full path to be safe) socket = /tmp/aml.sock chmod-socket = 664 uid = www-data gid = www-data # Clear environment on exit vacuum = true uwsgi.service [Unit] Description=uWSGI Emperor service After=network.target [Service] #User=amlalchy #Group=www-data ExecStartPre=/bin/bash -c 'mkdir -p /run/uwsgi; chown amlalchy:www-data /run/uwsgi' ExecStart=/bin/bash -c 'cd /home/amlalchy/api_aml_platform && source /home/amlalchy/anaconda3/bin/activate AmlPlatform && uwsgi --ini /etc/uwsgi/sites/uwsgi.ini' Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all [Install] WantedBy=multi-user.target api.conf for the nginx configuration server { listen 80; server_name server.prueba.com; charset utf-8; client_max_body_size 128M; location = /favicon.ico { access_log off; log_not_found off; } location /static { root /home/amlalchy/api_aml_platform/services; } location /media { root /home/amlalchy/api_aml_platform; } location / { include uwsgi_params; uwsgi_pass unix:/tmp/aml.sock; uwsgi_read_timeout 300s; uwsgi_send_timeout 300s; } } I'm getting this error in /var/log/enginx/error.log : 2020/01/13 10:30:12 [error] 12641#12641: *1 open() "/home/amlalchy/api_aml_platform/services/static/css/global.css" failed (2: No such file or directory), client: 127.0.0.1, server: server.prueba.com, request: "GET /static/css/global.css HTTP/1.1", host: "127.0.0.1", referrer: "http://127.0.0.1/api/login/ I am newbie and I don't know what I'm missing because the static files exists... so … -
Why request.Get.get() method is not working in Django
I'm trying to make a Text Analyzer website using Django3.0.2 in a virtual env running on python3.7.4 . I want to fetch the data entered inside text box by the user to ge printed on my console. For some reason request.Get.get() method is not working and I'm seeing AttributeError. template : <body> <h3> Enter your text here </h3> <form action="/remvpc" method="get"> <textarea name="text" id="" cols="30" rows="10" spellcheck="false" style="margin: 0px; width: 673px; height: 393px;"> </textarea> <br> <button type="submit"> Anazlyze text </button> </form> </body> views.py from django.http import HttpResponse from django.shortcuts import render def remove_pun(request): dj_text = request.Get.get('text','default') print(dj_text) return HttpResponse("""remove punctuation <a href="/"> Back </a>""")` urls.py file of project from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('remvpc/', views.remove_pun, name='remove-pun'), ] ERROR Environment: Request Method: GET Request URL: http://127.0.0.1:8000/remvpc/?text=++++++++ Django Version: 3.0.2 Python Version: 3.7.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed 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'] Traceback (most recent call last): File "/home/ankur/.local/share/virtualenvs/django_project_1-4W4x1zxU/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/ankur/.local/share/virtualenvs/django_project_1-4W4x1zxU/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/ankur/.local/share/virtualenvs/django_project_1-4W4x1zxU/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ankur/DEV_1/django_project_1/src/django_project_1/views.py", line 17, … -
how to get redirected to the exact url in django
when I’m trying to go to url like this $.get("getdetailofselectedcustmor/", function(){ }) in my js code , I’m redirected to 'current url + getdetailofselectedcustmor', but what I’m looking for is just to get redirected to 'localhost:8000/getdetailofselectedcustmor/', how can I do that? -
Matching current user's id with a field in django Models
I want to fetch data from models, by filtering it with current logged in user whose id is already present in the employee model. How do I achieve this? Models.py from django.db import models from django.contrib.auth.models import User import django import datetime # Create your models here. class vendor(models.Model): id = models.CharField(max_length=20, primary_key=True) name = models.CharField(max_length=30) class employee(models.Model): name = models.OneToOneField(User, on_delete=models.CASCADE) id = models.CharField(max_length=20, primary_key=True) balance = models.IntegerField(default=0) class transaction(models.Model): vendor_id = models.ForeignKey(vendor, on_delete=models.CASCADE) emp_id = models.ForeignKey(employee, on_delete=models.CASCADE) debit = models.IntegerField() credit = models.IntegerField() timestamp = models.DateField(("Date"), default=datetime.date.today) views.py: def updatingBalance(request): if request.method=="POST": ven_id = request.POST["groupOfDefaultRadios"] amount = request.POST["amt"] print("..................debg 1") print("User Id is {} and employee id = {}".format(User.id, id)) x = employee.objects.get(id = User.id) x.balance = x.balance - amount p = transaction(vendor_id =int(ven_id), emp_id = request.User.id, debit=amount, credit=0) p.save() y = employee.objects.filter(id = User.id) return render(request, 'profiles/userLogin.html/', {'model':y}) return render(request, 'profiles/userLogin.html/') -
Debugging CreateView in Django 3
I am trying to debug CreateView in Django 3.0.1. Basically I am using the same form for CreateView and UpdateView. The form uses a custom textarea (a markdown editor) so what I have is this: views.py class SoccerCreate(views.LoginRequiredMixin, views.StaffuserRequiredMixin,CreateView): login_url = loginUrl form_class = SoccerForm success_url = reverse_lazy('soccer-list') template_name = 'soccer_form.html' class SoccerUpdate(views.LoginRequiredMixin, views.StaffuserRequiredMixin,UpdateView): login_url = loginUrl model = Soccer form_class = SoccerForm success_url = reverse_lazy('soccer-list') template_name = 'soccer_form.html' and in the soccer_form.html <form action="" method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <button>Save</button> </form> <script> var inscrybmde = new InscrybMDE({ element: $("#id_body")[0] }); </script> and forms.py class SoccerForm (forms.ModelForm): class Meta: model = Soccer exclude = ['app_name',] Now Update works fine but create doesn't. The only error I get is in the js console "An invalid form control with name='body' is not focusable." but I don't think the issue is related to js because the same form works fine with UpdateView (this said it looks like the form never gets posted...) So the question is how can I debug a CreateView e.g. check if the input is correct etc ? I have also tried to copy all the text/fields from a record I edited and it still doesn't … -
TypeError at Django html file
html = t.render(Context({'current_date': now}))