Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: ImportError: No module named context_processors
I have one django 1.9 deployment that frequently gets this error: Internal Server Error: Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 174, in get_response response = self.process_exception_by_middleware(e, request) File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 172, in get_response response = response.render() File "/usr/lib/python2.7/site-packages/django/template/response.py", line 160, in render self.content = self.rendered_content File "/usr/lib/python2.7/site-packages/django/template/response.py", line 137, in rendered_content content = template.render(context, self._request) File "/usr/lib/python2.7/site-packages/django/template/backends/django.py", line 95, in render return self.template.render(context) File "/usr/lib/python2.7/site-packages/django/template/base.py", line 204, in render with context.bind_template(self): File "/usr/lib64/python2.7/contextlib.py", line 17, in __enter__ return self.gen.next() File "/usr/lib/python2.7/site-packages/django/template/context.py", line 256, in bind_template processors = (template.engine.template_context_processors + File "/usr/lib/python2.7/site-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/lib/python2.7/site-packages/django/template/engine.py", line 105, in template_context_processors return tuple(import_string(path) for path in context_processors) File "/usr/lib/python2.7/site-packages/django/template/engine.py", line 105, in <genexpr> return tuple(import_string(path) for path in context_processors) File "/usr/lib/python2.7/site-packages/django/utils/module_loading.py", line 20, in import_string module = import_module(module_path) File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named context_processors Here is my TEMPLATES list: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'motor/ui/templates')], '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', 'context_processors.config', 'ui.context_processors.navigation', 'core.appmngr.context_processor', ], }, }, ] And my MIDDLEWARE_CLASSES: MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'middleware.LastSiteUrl', ] Only this one site gets these … -
Django - Issue during split views.py file
I'm developing a Django application (Django 1.10 + Python 2.7.9) and I would split my views.py file in a sub-directory. I searched a lot about this topic and I have found posts and SO questions, but when I try to replicate them, I faced this error: RuntimeError: Model class models.Evento doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Before split-attempt, the application worked well. Follow my project structure: -gest_fest -gest_fest_app -gest_fest -views -__init__.py -eventi.py -models.py -urls.py views.__init__.py from eventi import eventi_view views.eventi.py from django.shortcuts import render from models import Evento def eventi_view(request): events = Evento.objects.all() return render(request, 'eventi/eventi.html', {'eventi': events}) models.py from __future__ import unicode_literals from django.db import models class Evento(models.Model): id_evento = models.AutoField(primary_key=True) titolo = models.CharField(max_length=45) urls.py from django.conf.urls import url from views.eventi import eventi_view urlpatterns = [ url(r'^eventi/$', eventi_view, name='eventi') ] Settings.py information BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ROOT_URLCONF = 'gest_fest_app.urls' STATIC_URL = '/gest_fest/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "/gest_fest/static/") ] I have found some solutions that suggest using relative imports, but I would utilize the absolute ones. What i'm missing? If I missed some usuful information about the project, I will edit it. Sorry for trivial question, but I'm a novel in Django. Thanks in advance -
Many-to-many relationship with itself can't utilize the related name attribute
I am trying to make a Twitter clone. The app has a series of users, each of which has a user profile. The UserProfile model is as follows class UserProfiles(models.Model): authenticated_user = models.OneToOneField(User, related_name="user_profile") handle = models.CharField(max_length=50) display_name = models.CharField(max_length=50) following = models.ManyToManyField("self", related_name="followers", null=True) def __str__(self): return self.authenticated_user.handle The "following" attribute is a many-to-many relationship with UserProfiles, as each user profile can follow many other profiles, and many profiles can be following another profile. If I have an instance of UserProfiles, we'll call it current_user, I can find how many profiles it's following by doing current_user.following.count I also want to be able to tell the user how many people are following them. Since the related_name argument is set to "followers," it seems reasonable that I can get a count of followers by doing current_user.followers.count This, however, returns an error, "'UserProfiles' object has no attribute 'followers'" Why won't what I did work? What can I do instead? -
get_table_pagination() takes exactly 2 arguments (1 given)
I update from Django 1.6 to Django 1.10.5, the aplication run normal, but i have this problem with django tables2 reports, i have this method: #class ExportMe(SingleTableView): class ExportMe(ReportTableView): template_name = "export.html" classes_autorizadas_para_export = [ 'name1','name2','name3'] @method_decorator(user_passes_test(lambda u: u.is_staff, login_url='/404/')) def dispatch(self, request, *args, **kwargs): entity_name = self.kwargs['entity'] #try: if entity_name in self.classes_autorizadas_para_export: class_factory = TableClassFactory() self.table_class = class_factory.build(entity_name) self.model = globals()[entity_name] return super(ExportMe,self).dispatch(request, *args, **kwargs) else: raise Http404() #except: # raise Http404() When i use SingleTableView, this is worked, but when i used ReportTableView, i have this problem. This is a Type Error: TypeError at /export/BolsaProjeto/ get_table_pagination() takes exactly 2 arguments (1 given) Request Method: GET Request URL: http://localhost:8000/export/BolsaProjeto/ Django Version: 1.10.5 Exception Type: TypeError Exception Value: get_table_pagination() takes exactly 2 arguments (1 given) Exception Location: /home/sniper/sniper/python/local/lib/python2.7/site-packages/django_tables2_reports/views.py in get_table, line 34 Python Executable: /home/sniper/sniper/python/bin/python Python Version: 2.7.9 Python Path: ['/home/sniper/Final/sniper', '/home/sniper/Final/sniper', '/home/sniper/sniper/python/lib/python2.7', '/home/sniper/sniper/python/lib/python2.7/plat-x86_64-linux-gnu', '/home/sniper/sniper/python/lib/python2.7/lib-tk', '/home/sniper/sniper/python/lib/python2.7/lib-old', '/home/sniper/sniper/python/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/home/sniper/sniper/python/local/lib/python2.7/site-packages', '/home/sniper/sniper/python/lib/python2.7/site-packages'] Server time: Tue, 21 Feb 2017 17:49:48 -0300 <\pre> This is the url i use: url(r'^export/(?P\w+)/$', siteviews.ExportMe.as_view(), name="export"), <\pre> I think the problem is with django reports. -
Django TokenAuthentication - exntending JWT obtain_jwt_token
I have a Django REST app and token authentication powered by Django REST framework JWT Auth Let me formulate my high-level goal: My goal is to generate a token for the user if he provides correct credentials AND THEN immediately after successful login I want to perform some additional set of operations. For simplicity, let's say I want to print "Hello" to the console. Right now my code looks like this: from rest_framework_jwt.views import obtain_jwt_token urlpatterns = [ url(r'^api-token-auth/', obtain_jwt_token), ] What I want to do is the following Get the token that obtain_jwt_token generates If authentication was successful, do some additional operations and return the token to the user. I feel lost in the jungles of all this Django architecture related to authentication classes. Do I understand correctly that if I am using third-party packages like Django JWT, I have no power on login process and there's no way to perform additional operations after the user logs in? And if I want to have more power on login process, I have to do all the job that Django JWT developers have done from scratch? Can I somehow add some operations ON TOP of Django JWT's obtain_jwt_token ? -
Attempt to read form field value throwns keyerror when used with jQuery datepicker
I am new to Django framework and am running into the following issue. Any help to resolve the issue will be much appreciated. Background: I am using the jQuery datePicker to gather date input. I am able to see the calendar show up on the (Appointment) form and select a date from the calendar. However, once submitted, attempt to extract the selected date, in the post processing function, throws a keyerror. I don't know if this has anything to do with the fact that I didn't manually enter "perfDate", but rather made a selection on the calendar. The Django debugs show that the POST data as shown here- enter image description here Following are my form, template and views files: forms.py: class DateInput(forms.DateInput): input_type = 'date' class AppointmentForm(forms.Form): class Meta: model = Appointment widgets = { 'perfDate': forms.DateInput(attrs={'class':'datepicker'}), } datePicker.html: <!doctype html> <html lang="en"> <head> ... JS code... </head> <body> <form action="/users/makeReservation/" method="post"> {% csrf_token %} <!--{{ form.date }} --> <p>Desired date:<p> <input name="perfDate" type="text" id="id_date"></p> <!-- The rest of my form --> <input type="submit" value="Reserve" /> </form> </body> views.py: def makeReservation(request): if request.method == 'POST': aptForm = AppointmentForm(request.POST) # Have we been provided with a valid form? if aptForm.is_valid(): … -
CSS not reloading sometimes Django
I'm working on a project in Django and I'm trying to clean some of the CSS up. The project is called 'rs'. The path to the stylesheet in the project folder is rsinterface/static/rsinterface/style.css. At the top of my file, I include static files using {% load staticfiles %}. I then link the stylesheet using the line <link rel="stylesheet" type="text/css" href="{% static 'rsinterface/style.css' %}" /> I made some changes to the stylesheet that should be immediately visible, saved and closed the stylesheet, reloaded the page, and nothing was changed. There was some stylesheet that was loaded, as all the previously existing styling stayed the same, but the edits I made were not reflected. I didn't revert any changes, and roughly an hour later I reloaded the page again and the changes were there. I then changed the stylesheet again and, once again, the page didn't change. Ever since then its been intermittent in actually changing the page. The one way I found to always make the style changes go through is by modifying the css file's name each time, but this leads to issues with version control software. Is there an explanation for this phenomenon, and is there any other workaround … -
Python export datetime to csv
I have this code" import csv def export_failures_all(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="failures.csv"' writer = csv.writer(response, delimiter=';', dialect = 'excel') response.write(u'\ufeff'.encode('utf8')) writer.writerow(['Maszyna', 'Wydział', 'Opis', 'Data dodania', 'Data rozpoczęcia naprawy', 'Data zakończenia naprawy', 'Zgłaszający', 'Przyjęte przez', 'Status']) awarie = Awaria.objects.all().values_list('maszyna__nazwa', 'wydzial__nazwa', 'description', 'add_date', 'repair_date', 'remove_date', 'user__username', 'sur__username', 'status__nazwa').order_by('-id') for awaria in awarie: writer.writerow(awaria) return response The problem I have it's with 'add_date', 'repair_date', 'remove_date' because theu are DateTimeField and in csv file they are with seconds: 2017-02-14 09:50:19.271833+00:00 2017-02-14 08:38:09.362218+00:00 and I want like this: 2017-02-14 09:50 2017-02-14 08:38 Any ideas how to achieve it? -
Difference between two dates python/Django
I need to know how to get the time elapsed between the edit_date(a column from one of my models) and datetime.now(). My edit_date column is under the DateTimeField format. (I'm using Python 2.7 and Django 1.10) This is the function I'm trying to do: def time_in_status(request): for item in Reporteots.objects.exclude(edit_date__exact=None): date_format = "%Y-%m-%d %H:%M:%S" a = datetime.now() b = item.edit_date c = a - b dif = divmod(c.days * 86400 + c.minute, 60) days = str(dif) print days The only thing I'm getting from this fuction are the minutes elapsed and seconds. What I need is to get this date in the following format: Time_elapsed = 3d 47m 23s Any ideas? let me know if I'm not clear of if you need more information Thanks for your attention, -
Django redirect when i login
I created login page [this is url (127.0.0.1)] when i singin redirect me to dashboard 127.0.0.1/dashboard but when i go to 127.0.0.1 i see login site.I want to create redirect to 127.0.0.1/dashboard when i'm logged. I use Django authentication system. How I can do it ? this is my url urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^account/', include('account.urls')), url(r'', auth_views.login, name='login'), ] It seems to me that I have to take advantage of the session, but I'm not sure -
Routing Django ORM Based on URL Parameter
We have a scenario where we have 4 databases that are exact duplicates of each other in terms of structure and functionality. Each database represents a different division within our company. We are using DRF to prove a REST API for these databases. My goal is to define the same Models/Serializers/Views and reuse them for every database. We then allow the developer to specify a "server" url parameter in their request. The app then selects the correct database based on that server parameter. We already have multiple databases in our app and a router.py configured. I assume the best way to solve this problem is to add some logic in the db_for_read and db_for_write methods. My question is that I am not familiar with these methods/class. How can I pass the server parameter from the Django view into this router so one of the routing methods can access it and select the corresponding database? Or is there another way to implement this that I am missing? -
haystack autocomplete raising odd error
Okay, so I am trying to implement autocomplete on a search field using haystack and solr in my django project but I keep running into 'reduce() of empty sequence with no initial value' error. I'm not sure how this can be becuase when I rebuild my index I see that it indexes over 200 triples in my DB. I'm not sure I am understanding the SQS module correctly and I was hoping someone could point me in the right direction. I want to use the Triple model fields as the autocomplete suggestions in a search from. my model, index and view: MODEL: # Create your models here. class Triple(models.Model): studies = models.ForeignKey(Studies, on_delete=models.CASCADE) Subject = models.CharField(max_length=550, default='') Predicate = models.CharField(max_length=550, default='') Object = models.CharField(max_length=550, default='') updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) def __unicode__(self): return '%s %s %s' % (self.Subject, self.Predicate, self.Object) def __str__(self): return '%s %s %s' % (self.Subject, self.Predicate, self.Object) def get_absolute_url(self): return reverse("queries:detail", kwargs={"id": self.id}) INDEX: class TripleIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) link = indexes.CharField(model_attr='studies') content_auto = indexes.EdgeNgramField(model_attr='Object') def get_model(self): return Triple def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.all() the problem in my view seems to stem from … -
Django REST - overriding obtain_auth_token
I have a Django 1.9 project and am using Django Rest auth to implement authentication system. Now my goal is to override obtain_auth_token.To do this, I am overriding ObtainAuthToken this way (according to what I read here): class CustomObtainAuthToken(ObtainAuthToken): throttle_classes = () permission_classes = () authentication_classes = () def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}) The problem is with token, created = Token.objects.get_or_create(user=user) where I end up with (1146, "Table 'android_blend.authtoken_token' doesn't exist") error. Well, it's not that unclear to me why Django yields this error. The question is, how do I properly generate a token without using any database tables? -
Django Logout View Type Error with python 2.7.11
I have a logout view: class LogoutView(generic.RedirectView): url = reverse_lazy("home") def get(self, request, *args, **kwargs): logout(request) return super(self).get(request, *args, **kwargs) And on the line return super(self).get(request, *args, **kwargs) there is the following error: must be type, not LogoutView How do I fix this error? Thank you in advance. -
Go above BASE_DIR in django
I am new to Django, Quite Confused here. This is BASE_DIR BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) └── MY_PROJECT │ MY_APP ├── BASE_DIR │ ├── settings.py │ │ /** ALL OTHER FILES **/ └── manage.py Now, How should I access my App Directory in a BASE_DIR file ?? Thank you! -
django rest framework how to internationalize fields
I have followed the Django documentation for setting up internationalization. I require to return a translation of various choices fields depending on the language requested. For example I have the following choices fields; CHOICE_TYPES = (('short', _('Short Term')),('long', _('Long Term')), ('mixed', _('Mixed')),) I have setup my Locale and .po files as per the documentation. For example; msgid "Short Term" msgstr "단기계약" I am requesting the language using the Accept-Language header on a request. But it seems that Django is not seeing the locale or there is another step I haven't undertaken for DRF. Django does see the language request as I am using django-hvad for model translations and they are returned correctly. Any help would be appreciated. -
"No action selected" says Django-admin when deleting objects
I've created a simple model Product with couple of fields and then went to admin.py. I've registered the Product, make some fields list_editable and created a new action duplicate. def duplicate(modeladmin, request, queryset): number = int(request.POST['number']) product = queryset.first() for i in xrange(number): product.id = None product.save() class DuplicateActionForm(ActionForm): number = forms.IntegerField() class ProductAdmin(admin.ModelAdmin): list_display = ('id','name','color','memory','ga_url','gs_url',) list_editable = ('color','memory','name','ga_url','gs_url',) action_form = DuplicateActionForm # actions = [duplicate,] admin.site.register(Product,ProductAdmin) When actions attribute of ProductAdmin class is not commented, I can duplicate objects. The problem is that I can't delete them. When I check row and select delete selected, it says: No action selected. This is caused by line: action_form = DuplicateActionForm because if actions = [duplicate,] is commented, I can't delete objects correctly until I comment action_form = DuplicateActionForm Do you know where is the problem? -
Is it ever necessary to instantiate new HttpRequest objects in Django?
I have a view that authenticates a user. If the user is authenticated, the program should call another view with the request and user as parameters. def home(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: return index(request, user) else: context = {'error_message': "That username and password don't exist in our system."} return render(request, 'list/home.html', context) So, when index gets called, the request is the same instance as the request send to the home view, right? My concern is that the request is still a POST request when it should be a GET request. Is this a misconception? Should I create a new request object and send it to index? Thanks. -
Expose a Django app's models at the module level
I've made a django app, which is designed to be easily pluggable, and only has 1 view, and 1 model that project planning to use the app need to be aware of. For ease, I'd like to just make the view and model available from the app-level. So rather than: from mything.views import MyView from mything.models import MyModel You can instead just do: from mything import MyView, MyModel I changed the __init__.py file in the app to be like this: from .views import MyView from .models import MyModel Of course I get the old django.core.exceptions.AppRegistryNotReady raised, since it's attempting to run the models.py code before the apps are loaded. So I came up with the following workaround, and I'm wondering if it's a reasonable pattern to use or not. Now in __init__.py I have: def _expose_items(): from .views import MyView from .models import MyModel globals()['MyView'] = MyView globals()['MyModel'] = MyModel And in my app's apps.py: from . import _expose_items class MyThingConfig(AppConfig): name = 'mything' def ready(self): _expose_items() So now indeed, I can directly import the view and model from the outside. Is this useful, or horrible? -
Allow user to specify model field on creation, but declare read-only for update
I have a model with a name field. Instances can be created via the REST interface (POST requests). The JSON serializer (ModelSerializer) specifies which fields are visible and editable on the client side. I am looking for a way to declare the name field read-only in PUT and PATCH requests, so that a request that comes with a modified name value causes an error (or, at least, silently uses the unmodified value), while a value can still be specified by the user at creation time. One solution would be to override the put() and patch() methods in the view, but this would cause code duplication; furthermore, it seems cleaner to me to enforce this behavior on the model level. So, I could add the necessary treatment and exception raising to the model's save() method, but as this is a pretty standard issue, I was wondering if there is a more idiomatic way to do this. While I was looking for solutions for this, I mainly found information on how to make the Django admin forms behave in such a way. However, my question is about REST operations and writability constraints on the model, not about the form presentation. -
How to make django URL system and directory system work under a particular folder and url?
I am very new to django. I have apache2 working with django. The root url of the website is mydomain.com I want to use django as a sub-website working under apache's static website with the domain mydomain.com/django. How to make the URL system produce mydomain.com/django/myapp/3/answer instead of mydomain.com/myapp/3/answer? Do I have to change every url in project_folder/urls.py to url(r'^django/blablabla') How to make django look for files under mydomain.com/django/static/ instead of mydomain.com/static/? Thank you so much! -
Tesseract on Heroku
How can I add Tesseract on Heroku for Django app? I found one thred , here But it's depricated. Can anyone suggest alternative solution ? -
How to implement Nginx 'Service Unavailable' with SSL?
Recently I converted my Nginx/Gunicorn/Django website 'mysite' to SSL and the SSL connectivity works perfectly. With the previous non-SSL version of the site, I had created some directives in my Nginx config file that restricted access to the site when I am doing maintenance and it worked correctly. However, now that I've converted the site to SSL, those directives no longer work and I can't figure out why. Is the problem with the rewrite commands? Here's my config file: # /etc/nginx/sites-available/mysite.conf server_tokens off; upstream mysite_server { server 127.0.0.1:8000 fail_timeout=0; } server { server_name web01.mysite.com; listen 80; return 301 https://web01.mysite.com$request_uri; } server { server_name web01.mysite.com; listen 443 ssl; ssl_certificate /srv/ssl/mysite.com/ssl-bundle.crt; ssl_certificate_key /srv/ssl/mysite.com/mysite.com.key; ssl_session_timeout 1d; ssl_session_cache shared:SSL:50m; ssl_session_tickets off; ssl_dhparam /srv/ssl/mysite.com/dhparam.pem; ssl_ciphers '<ciphers are here>'; ssl_prefer_server_ciphers on; add_header Strict-Transport-Security "max-age=15768000; includeSubDomains;"; ssl_stapling on; ssl_stapling_verify on; client_max_body_size 4G; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; location / { root /srv/http/mysite.com/repo; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://mysite_server; break; } } location /static/ { proxy_pass http://<file_server_ip_addr>; } location /media/ { proxy_pass http://<file_server_ip_addr>; } ### START 503 SERVICE UNAVAILABLE BLOCK ### # Uncomment directives to invoke "503 Service Temporarily # Unavailable" page # Uncomment this conditional to limit … -
Cant get related set
Why cant I use page.item_set to get the related items for the page model? 'Page' object has no attribute 'item_set' class Page(models.Model): survey = models.ForeignKey(Survey) title = models.CharField(max_length=256) parent = models.ForeignKey("Page", blank=True, null=True, related_name="parent_page") def __unicode__(self): return self.title class Item(models.Model): page = models.ForeignKey(Page, related_name="item") key = models.CharField(max_length=256) value = models.CharField(max_length=256) image = models.ImageField(upload_to="builder/item", null=True, blank=True) options = models.ManyToManyField(Option, blank=True) goto = models.ForeignKey(Page, null=True, blank=True, related_name="goto_page") def __unicode__(self): return self.value -
how we can store and use public key to encrypt data?
from django.shortcuts import render from .models import verify from django.shortcuts import get_object_or_404, redirect, render from django.utils import timezone from django.contrib.auth import authenticate, login import Crypto from Crypto.PublicKey import RSA from Crypto import Random def client(request): if request.method == "POST": username = request.POST.get('uname') password = request.POST.get('psw') publickey="""MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDWxkvhycmo4VK+NOIUewg6/y6G o8R/OUUrBSRz5RvoduiWMNidOjMocA9Lnhr48AtXrqd23EBfmak2XemNpofmjl8P 3A8LNSStDu3KJ+44iYS/pCBfM1IXuZg3Z3ZwZVRTqkugNPRC2H8Lkiq8EoAu1Owz Mr0ZRsuCFrDw+c4yoQIDAQAB""" encrypted_username = publickey.encrypt(username, 32) encrypted_password = publickey.encrypt(password, 32) f=open("encrypt.txt","w") f.write(encrypted_username) f.write("\n") f.write(encrypted_password) f.close() print(username) print(password) '''random_generator = Random.new().read key = RSA.generate(1024, random_generator) #generate pub and priv key publickey = key.publickey() # pub key export for exchange encrypted_username = publickey.encrypt(username, 32) print(encrypted_username) encrypted_password = publickey.encrypt(password, 32) print(encrypted_password)''' Error: AttributeError at /check 'str' object has no attribute 'encrypt' Request Method: POST Request URL: http://127.0.0.1:8000/check Django Version: 1.8.4 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'encrypt' Exception Location: /home/ubuntu/BEPRO/validate/client.py in client, line 20 Python Executable: /usr/bin/python Python Version: 2.7.6 Python Path: ['/home/ubuntu/BEPRO', '/usr/local/lib/python2.7/dist-packages/virtualenv-13.1.2-py2.7.egg', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode'] Server time: Tue, 21 Feb 2017 21:35:43 +0530