Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-allauth; how to just redirect to a page if the user's email is invalid
I'm trying to limit the email to a specific domain. My custom adapter is like this class CustomSocialAccountAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin): user = sociallogin.user if not user.email.split('@')[1] == "example.com": what I want to do is just to redirect to home page without allowing the user to log in. But seems like when I use redirect method, the user who has invalid domain is also logged in. Anyone who can give me tips? -
i recieve mail from same mail domain which is host mail in django
here is settings.py of my app EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'hk7206210@gmail.com' EMAIL_HOST_PASSWORD = '*********' EMAIL_PORT = '587' EMAIL_USE_TLS = True forms.py from django import forms class contactForm(forms.Form): name = forms.CharField(required= True,max_length = 100,help_text = '100 character Max.') email = forms.EmailField(required = True) comment = forms.CharField(widget = forms.Textarea) views.py from django.shortcuts import render from .forms import contactForm from django.core.mail import send_mail from django.conf import settings # Create your views here. def contact(request): form = contactForm(request.POST or None) if form.is_valid(): name = form.cleaned_data['name'] comment = form.cleaned_data['comment'] subject = 'Message from Matrimonial.com' message = '%s %s' %(comment,name) emailFrom = form.cleaned_data['email'] emailTo = [settings.EMAIL_HOST_USER] send_mail(subject, message,emailFrom,emailTo) context = locals() template = 'contact.html' return render(request,template,context) Problem is sender and reciever is from same email address from hk7206210@gmail.com and to is also hk7206210@gmail.com i search alot but can't find the solution,help me out from this bug -
AngularJS: ng-repeat not showing data
index.html: {% load staticfiles %} <html ng-app = "myModule"> <head> <script src = '{% static "scripts/angular.js" %}'> </script> <script src = '{% static "scripts/application.js" %}'> </script> </head> <body ng-controller = "myController"> Table: Message: {{ message }} <table> <tr ng-repeat = "t in technologies track by $index"> <td> {{ t.name }} </td> </tr> </table> </body> </html> application.js: // Create a module var myApp = angular.module("myModule", []); // Create a controller. Attach model to the scope. var myContoller = function ($scope, $http, $log) { var technologies = [{name: "C", likes: 0, dislikes: 0}, {name: "Perl", likes: 0, dislikes: 0}, {name: "Java", likes: 0, dislikes: 0}, {name: "Python", likes: 0, dislikes: 0}]; $scope.technologies = technologies; $scope.message = 'AngularJS table'; } // Register the controller with the module myApp.controller("myController", myContoller); When I opened index.html, No data from the model gets displayed. Am I missing something obvious? I am only showing the html and controller files here. But the code is part of a Django project. -
GeoDjango. Admin not showing map location for point = models.PointField() in created instances
I am trying to create member instances in a very simple way to practice GeoDjango. I am able to create the instances but they are not showing correctly in the admin map (See images Below) below are my models.py from django.contrib.gis.db import models class Member(models.Model): name = models.CharField(max_length=150) image = models.ImageField() lat = models.FloatField() lon = models.FloatField() point = models.PointField() objects = models.GeoManager() def __str__(self): return self.name below is my views.py class MemberCreate(CreateView): model = Member fields = ('name', 'image', 'lat', 'lon') def form_valid(self, form, *args, **kwargs): self.object = form.save(commit=False) self.object.point = fromstr('POINT(%s %s)'%(self.object.lat, self.object.lon), srid=4326) self.object.save() return redirect('member:all_members') The model and views are successfully creating the model instance on my admin.py below is the code for admin.py from django.contrib.gis import admin from .models import Member admin.site.register(Member, admin.OSMGeoAdmin) The point on Admin of my GeoDjango Project See Below The place where the point actually is on the internet( Notice same lat, lon See Below) How can I fix this -
How to get someone up to speed in Django template language with no programming background
I've been struggling with this issue for a while and after some searches, I've decided to ask here for help or any tips or advices. I am creating a Website (in future, Web API using ReST for Mobile apps) with Django and I have someone who has been doing UI and Graphics for a couple of websites, android apps and games, etc. The guy does not know any programming language, and his background is Graphics/3D modeling, but knows HTML/CSS and a bit of JS. Using Dreamweaver and Maya, he can create good-looking websites and useful UI without writing a single line of code. I tried to show him how Django Template language works but he gets confused here and there. I tried looking for resources on how Django template system works or some useful tutorials for its front-end, but the problem is, the documentation on Django website is for version 1.7 and we are using Django 2.1 and it needs some understanding of Python and Django. Also, I want to give him something solid to learn and work with, so in the future he can handle web front-end templates in Django easily. Are there any resources (Website, documentation, tutorial, etc.) β¦ -
How to use cookie csrf in django?
Hello I have a frontend application which was migrated to django and for csrf protection I am using the methodology of copying csrf token from cookies to header of my post request. Django keeps complaining about invalid csrf token despite that the request contais the csrf token from cookies. In my settings.py I have explicitly specified: CSRF_USE_SESSIONS = False to make sure that cookie-based csrf is used according docs -
Django: Conflict between django-debug-toolbar and Huey
Today, I noticed that there is some conflict between django-debug-toolbar and huey. In general, when you run manage.py run_huey you get immeditately some output like [2018-08-17 17:47:25,040] INFO:huey.consumer:MainThread:Huey consumer started with 1 thread, PID 2389 [2018-08-17 17:47:25,041] INFO:huey.consumer:MainThread:Scheduler runs every 1 second(s). [2018-08-17 17:47:25,041] INFO:huey.consumer:MainThread:Periodic tasks are enabled. [2018-08-17 17:47:25,041] INFO:huey.consumer:MainThread:UTC is enabled. ... Now, add this to your settings file: INSTALLED_APPS += [ 'debug_toolbar', ] MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware', ] And suddenly when you run manage.py run_huey again, you do not get any output at all: python manage.py run_huey Can someone reproduce that and what could be the cause? System information Django 2.1, Python 3.7, Huey 1.10.2, Django Debug Toolbar 1.9.1 -
Django Sqlite3 programming error
I am very new to Django. I have created a sample project with Python v3.6 and Django V2.1. Initially, I have was using default sqlite3 database but now we have planned to change that into Mysql. For that, I have installed all the necessary plugin. On the other hand, I didn't create any table with sqlite3 except admin. It is working fine if it was in default database when I change that into MySQL I am getting error which I can't resolve for a week :-( System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000000003A93C80> Traceback (most recent call last): File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\django\db\backends\base\base.py", line 2 16, in ensure_connection self.connect() File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\django\db\backends\base\base.py", line 1 94, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\django\db\backends\mysql\base.py", line 227, in get_new_connection return Database.connect(**conn_params) File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\MySQLdb\__init__.py", line 86, in Connec t return Connection(*args, **kwargs) File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\MySQLdb\connections.py", line 204, in __ init__ super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (2059, "Authentication plugin 'caching_sha2_password' cannot be loaded: The speci fied module could not be found.\r\n") self.connect() File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\django\db\utils.py", line 89, in __exit_ _ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\django\db\backends\base\base.py", line 2 16, in ensure_connection self.connect() File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\django\db\backends\base\base.py", line 1 94, in connect self.connection = self.get_new_connection(conn_params) β¦ -
Django - Multiple data values in fusion pie charts
I want to add multiple data values in my pie charts taking model fields. currently i am doing this: dataSource['data'] = [] # Iterate through the data in `Revenue` model and insert in to the `dataSource['data']` list. for key in items.objects.all(): data = {} data['label'] = key.name data['value'] = key.sr dataSource['data'].append(data) and i want to add more values something like this: (this is JSON format of adding multiple data values) "data": [ { "label": "Venezuela", "value": "290" }, { "label": "Saudi", "value": "260" }, ] Any guide how will I add more values fetching from django models in my chart? -
Django Rest Framework what is the meaning of arguments being passed to the ModelSerializer?
I am trying to understand the arguments which are being passed into the serializers.ListUserSerializer(). I understand that last_five is the data to be returned through the serializer. Where I fail to understand is where this model has a to-many relationship. From reading the DRF documentation, many=True is passed when the model has a to-many relationship. However, I do not understand how this is specifying the to-many relationship. I see a couple of possibilities . . . one to many between current user and all other users one to many between current user and last_five Users query Also I am not quite understanding the context argument. I think that it is simply the request call to the api being included in the payload to the client. The code base for this is here class ExploreUsers(APIView): def get(self, request, format=None): # the "-date_joined" specifies descending order vs "date_joined" last_five = models.User.objects.all().order_by('-date_joined')[:5] # many=True provides to-many relationship from one user to many users serializer = serializers.ListUserSerializer( last_five, many=True, context={"request": request}) return Response(data=serializer.data, status=status.HTTP_200_OK) -
django cannot import login from django.contrib.auth.views
I try to build a login function for my page. To edit the urls.py as followed, it keeps remind that "cannot import name 'login' from 'django.contrib.auth.views' ". How could I deal with the problem? Thx! from django.contrib.auth.views import login from django.urls import path from . import views app_name = "users" urlpatterns = [ path("login/", login, {"template_name": "users/login.html"}, name="login"), ] -
Django app names are not translated in CMS
I have a Django application in which I'm willing to translate app names appearing in Django CMS. Models are translated but not app names As i have searched i found that i have to add verbose_name to AppConfig class in apps.py for each app i add to application: class CoreConfig(AppConfig): name = 'core' verbose_name = _("core") but it does not change anything in cms after i makemessage and compilemessage it. Even if i delete this class nothing changes, framework doesn't yield Django Version: 2.0.3 Any clues? -
requesting a url from clients ip
Is there any way that without rendering template I make a request from python module and that request is made from client ip When ajax calls are made in django templates the requests hit are hit by clients ip but when I make request via method below import requests x = requests.get("http://ip-api.com/json/") When I get the response from x it always gives the ip on which django website is hosted. for e.g if my website is hosted on 139.12.3.245 when i print ip it always gives (139.12.3.245) but I want to hit the api from clients side as we are able to do in ajax I want to hit an api from clients ip without rendering a template.How can I do that?or is it not possible? -
how to decrypt a encrypted data from database in django?
from django.contrib.auth.models import User u = User.objects.get(username='test') user.password u'sha1$c6755$66fc32b05c2be8acc9f75eac3d87d3a88f513802 -
Django; canot load static files
I've been working on Django and my static files cannot loaded. My project structure is like this blog/ |___apps/ | |__static/ | | |__css/ | | |__js/ | | | |__templates/ | | |__base.html | | |__feeds/ | | | |__feeds/ | |___blog/ settings.py my settings.py is like this APPS_DIR = os.path.join(BASE_DIR, 'apps') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(APPS_DIR, 'static'), ) The weird thing is only for index.html, static files can be loaded even though html files are inside templates/feeds/. there might be fault in my urls.py because the error says like Not Found: /feeds/static/css/styles.css seems like Django tries to find static files inside static/feeds/. urls.py is like this urlpatterns = [ path('', views.index, name='index'), path('feeds/', include([ path('list', views.list_entry, name='list_entry'), I don't want to create app name folder inside static if possible. How can I fix this? -
How can I send data from HDFS through Django backend to Angular 5 frontend?
I download file from Hadoop to Django backend and store file in this way: import shutil import requests url = 'http://112.138.0.12:9870/webhdfs/v1/user/username/1.jpg?op=OPEN&user.name=username' response = requests.get(url, stream=True) with open('img.png', 'wb') as out_file: shutil.copyfileobj(response.raw, out_file) del response I don't need to store file in backend local system and I want to send this file to Angular 5 frontend where user will save this file in own local system. At the moment I get error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte. I wonder whether I do this in a proper and most efficient way to allow downloading large files in a short time. Do you have an idea how can I do this? DJANGO: views.py: class DownloadFileView(GenericAPIView): serializer_class = UserNameSerializer def get(self, request): key = request.META.get('HTTP_AUTHORIZATION').split()[1] user_id = Token.objects.get(key=key).user_id user_name = User.objects.get(id=user_id).username response = download_files(user_name) return Response(response) def download_files(user_name): response = requests.get('http://112.138.0.12:9870/webhdfs/v1/user/' + user_name + '/1.jpg?op=OPEN&user.name=username', stream=True) return response.raw ANGULAR: DownloadFile(){ this.userService.DownloadFiles().subscribe((data : any) => { const blob = new Blob([data], { type: 'application/octet-stream'}); fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob)); } } DownloadFiles() { this.token = localStorage.getItem('userToken') var reqHeader = new HttpHeaders({ 'Content-Type': 'application/octet-stream', 'Authorization': 'token ' + this.token }); console.log(reqHeader) return this.http.get(this.rootURL + 'download/', { headers: reqHeader}); } -
Using a Custom User the Password Validation from settings are ignored on registration
In Django I created a custom User. My issues is that the default validators are not working, any password is accepted. I expected that the default password validators will work, because I'm inheriting the default Model/Form clases. In Django settings I have: AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 12, } }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] The Custom User implementation: class User(AbstractBaseUser, MetaData, PermissionsMixin): account = models.ForeignKey(Account, blank=True, null=True, related_name='owner', on_delete=models.CASCADE) email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_confirmed = models.BooleanField(default=False) # email confirmed is_active = models.BooleanField(default=False) # can't login is_staff = models.BooleanField(default=False) # staff user non super is_superuser = models.BooleanField(default=False) # superuser USERNAME_FIELD = 'email' # username used for login REQUIRED_FIELDS = ['first_name', 'last_name'] objects = UserManager() class UserManager(BaseUserManager): def create_user(self, email, first_name, last_name, password=None, is_confirmed=False, is_active=False, is_staff=False, is_superuser=False): if not email: raise ValueError('User must have an Email Address') if not password: raise ValueError('User must have a Password set') if not first_name: raise ValueError('User must have a First Name') if not last_name: raise ValueError('User must have a Last Name') user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name, ) user.set_password(password) user.is_confirmed = is_confirmed user.is_active = is_active user.is_staff = β¦ -
How to get the value of a Django Model Field object
I got a model field object using field_object = MyModel._meta.get_field(field_name). How can I get the value (content) of the field object? -
create directory in docker compose
enter image description here how can i solve this problem,i am using docker ,django,and nginx,how can i create the directory in docker with docker-compose ,,,thanks a lot i tried to write "mkdir /var/log/webvision2" in the docker-compose file ,but it does not work admin1@admin1-Vostro-5568:~/Code/webvision_docker$ sudo docker-compose up [sudo] admin1 ηε―η οΌ Starting ps_v Recreating dg_v Recreating ng_v Attaching to ps_v, dg_v, ng_v ps_v | 2018-08-18 04:26:09.299 UTC 1 LOG: listening on IPv4 address "0.0.0.0", port 5432 ps_v | 2018-08-18 04:26:09.299 UTC 1 LOG: listening on IPv6 address "::", port 5432 dg_v | Traceback (most recent call last): ps_v | 2018-08-18 04:26:09.312 UTC 1 LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" dg_v | File "/usr/local/lib/python3.5/logging/config.py", line 558, in configure dg_v | handler = self.configure_handler(handlers[name]) dg_v | File "/usr/local/lib/python3.5/logging/config.py", line 731, in configure_handler ps_v | 2018-08-18 04:26:09.438 UTC [23] LOG: database system was shut down at 2018-08-17 10:04:24 UTC dg_v | result = factory(**kwargs) ps_v | 2018-08-18 04:26:09.478 UTC 1 LOG: database system is ready to accept connections dg_v | File "/usr/local/lib/python3.5/logging/init.py", line 1014, in init dg_v | StreamHandler.init(self, self._open()) dg_v | File "/usr/local/lib/python3.5/logging/init.py", line 1043, in _open dg_v | return open(self.baseFilename, self.mode, encoding=self.encoding) dg_v | FileNotFoundError: [Errno 2] No such file or directory: '/var/log/webvision2/django_crontab.log' β¦ -
Receive JSON Object from ReactJS on my Django BackEnd
I'm trying to get a list of upload files and at the same time a JSON Object from ReactJS FrontEnd to my Django BackEnd, in views.py @csrf_exempt def simple_upload(request): if request.method == 'POST' and request.FILES.getlist('myfile'): my_json = json.loads(request.POST.get('myjson')) print("JSON: ",my_json) myfile = request.FILES.getlist('myfile') for i in myfile: ... #my code in my_template.html if have a dropzone <div class="dropzone"> <div class="content"> <img src="{% static 'core/img/upload.svg' %}" class="upload"> <span class="filename"></span> <input type="file" name="myfile" class="input" multiple> <input type="text" name="myjson" class="input"> </div> </div> What should I do? Thanks -
In Django ,how to access the data of dictionary inside lists of a dictionary from views.py in index.html(template)
views.py eanList=[12345678,123400348] dict_pass={'eanList':[12345678,123400348], '12345678':[{'Ean_code':12345678,'Img_url':http://img.jpg,'Product_title':mobilephone}{'market':amazon,'price':5000}{'market':flipkart,'price':5700}], '123400348':[{'Ean_code':123400348,'Img_url':http://img2.jpg,'Product_title':mobilephone2}{'market':amazon,'price':7000}{'market':flipkart,'price':8700}]} return render(request,'first_app/index.html',{'dict_pass':dict_pass,'eanlist':eanList}) index.html {% for ean in eanlist %} {{ dict_pass.ean.1.Product_Title}} {{ dict_pass.ean.1.Img_url}} -
net::ERR_ABORTED Can Django file access a folder?
net::ERR_ABORTED happens.Application's structure is βββ top β βββ __init__.py β βββ __pycache__ β β βββ __init__.cpython-36.pyc β βββ admin.py β βββ apps.py β βββ migrations β β βββ __init__.py β β βββ __pycache__ β β βββ __init__.cpython-36.pyc β βββ models.py β βββ static β β βββ app β β βββ top.css β βββ templates β β βββ top.html β βββ tests.py β βββ urls.py β βββ views.py βββ db.sqlite3 βββ test-folder β βββ test.js βββ app β βββ settings.py β βββ urls.py β βββ wsgi.py βββ manage.py Now in top.html of top/templates/top.html I wrote <html lang="ja"> <head> <meta charset="UTF-8"> <title>Top</title> <script src="../test-folder/test.js"></script> </head> γ» γ» γ» but when I run the appliction,GET http://127.0.0.1:8000/top/test-folder/test.js net::ERR_ABORTED error happens.I think the way of access <script src="../test-folder/test.js"> is right,so I cannot understand why such an error happens.I wrote urls.py of app, from django.contrib import admin from django.urls import include, path urlpatterns = [ path('top/', include('top.urls')), path('admin/', admin.site.urls), ] in top/urls.py from django.urls import path from . import views app_name = 'top' urlpatterns = [ path('', views.index, name='index'), ] so I did not write the url of test-folder,so is it wrong?I want to access test.js of test-folder in top.html,so how should i fix this? -
What Happens GET requests on Media Files
I have a Django project with a media folder. If I type: <audio src="/path/to/media/file/in/django/project"></audio> and the user plays the file, what happens to the file? Is a temporary copy of the audio file created? Does it get deleted after? Where is it stored if a copy is created? -
Django Serializer - Decide which fields are serialized at runtime
I am using DRF and have a model which is serialized. There are times when I want to include all the fields in the data that is sent to the api end point, and times when I want just a sub-set of the properties (for instance list view vs edit view). Is it possible to declare all the fields in one serializer, and then specify only a subset when calling the serializer. Here is an example of what I would like to do: queryset = Foo.objects.filter(active=True) FooSerializer(queryset, many=True, fields=["id", "title"]) I could then use this output to populate a the options of an HTML select element. Meanwhile FooSerializer looks like this: class FooSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() class Meta: model = ProgressNoteCustomType fields = ( 'id', 'title', 'modified', 'active', 'user' ) read_only_fields = ['id'] While I could write another serializer, that just has the id and title field in the Meta definition, it's not DRY. Then I have another scenario where I want to display a list view where the user can click on an item and edit it - here I want to display just title, modified, and active. Writing something like FooSerializer(queryset, many=True, fields=["id", "title", "active"]) seems like the β¦ -
One model object per user Django
I don't want to extend my userprofile. I made a new model with name, contact and email. The problem : With createview the user is able to create multiple instances of the user_info model. Is there any chance we can limit user to make only one user_info and update the same everytime. models.py class user_info(models.Model): booked_by = models.CharField(max_length=100) Name = models.CharField(max_length=40) contact = models.IntegerField() email = models.EmailField() views.py class user_info_create(LoginRequiredMixin,CreateView): login_url = 'Mel:user_login' form_class = user_infoform template_name = 'Mel/user_info_form.html' def form_valid(self, form): form.instance.booked_by = self.request.user return super(user_info_create, self).form_valid(form) class user_info_detail(LoginRequiredMixin,DetailView): login_url = 'Mel:user_login' model = user_info context_object_name = "book" def get_queryset(self): return user_info.objects.filter(booked_by=self.request.user)