Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Strange GET requests to my site
In the last days, Google Analytics is showing me some strange GET methods that have been requested on my website. I have no clue if it is done by robots or humans or if it is some kind of attack or something harmless. It is coming from different countries, which for me is even more confusing because it seems like it is not only one person/robot. Some examples of these urls are: /en/?lipi=urn:li:page:d_flagship3_feed;ipLRICUhTrGXGdPXnW0tnQ== /en/?lipi=urn:li:page:d_flagship3_feed;3kcVPzepRVGxY7MZjonjig== /en/?lipi=urn:li:page:d_flagship3_feed;mFWFR+VMS0SHqJTkYN87EA== /en/?_sm_pdc=1&_sm_rid=7MV6JrjR5MSrPHJMDDrtjMMQZVz6lqJrH02kZVk Does anybody has an idea what that is? -
UpdateView in Django shows blank forms instead of Database previous data
I'm using UpdateView to edit data using forms. After I click edit the pop up using modal is showing the forms with blank data! It doesn't retrieve the previous data that was in the Database. Anyone know what should I add? I am stuck with this edit for about a week :( If anyone has a clue I will be greatful! Thank you! view.py- from django.shortcuts import render_to_response from django.shortcuts import get_object_or_404 from django.shortcuts import render, redirect from django.template import RequestContext from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView from DevOpsWeb.forms import HomeForm from DevOpsWeb.models import serverlist from django.core.urlresolvers import reverse_lazy from simple_search import search_filter from django.db.models import Q class HomeView(TemplateView): template_name = 'serverlist.html' def get(self, request): form = HomeForm() query = request.GET.get("q") posts = serverlist.objects.all() if query: posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query)) else: posts = serverlist.objects.all() args = {'form' : form, 'posts' : posts} return render(request, self.template_name, args) def post(self,request): form = HomeForm(request.POST) posts = serverlist.objects.all() if form.is_valid(): # Checks if validation of the forms passed post = form.save(commit=False) #if not form.cleaned_data['ServerName']: #post.servername = " " post.save() #text = form.cleaned_data['ServerName'] form = HomeForm() return redirect('serverlist') args = {'form': form, 'text' … -
Django admin interface FormAdmin not registering second Form override
I had an issue a while back with a clean() method, which is now working. But when I added a second Form into the mix, no code from that clean() method seems to fire at all. I tried copying the previous one that does work down to the last detail, but only the first one works. Here is the code: from django.contrib import admin from .models import Provider, Employer, Person, Learnership, Qualification, Unit_Standard, Alternate_Id_Type_Id from django import forms class PersonForm(forms.ModelForm): class Meta: model = Person fields = '__all__' def clean(self): person_alternate_id = self.cleaned_data.get('person_alternate_id') alternate_id_type_id = self.cleaned_data.get('alternate_id_type_id') if person_alternate_id is not None and alternate_id_type_id == 533: raise forms.ValidationError("Invalid Type ID") if person_alternate_id is None and alternate_id_type_id != 533: raise forms.ValidationError("Invalid Type ID") ... return self.cleaned_data class PersonAdmin(admin.ModelAdmin): form = PersonForm admin.site.register(Person, PersonAdmin) For reference, this one still works perfectly: class ProviderForm(forms.ModelForm): class Meta: model = Provider fields = '__all__' def clean(self): provider_start_date = self.cleaned_data.get('provider_start_date') provider_end_date = self.cleaned_data.get('provider_end_date') if provider_start_date > provider_end_date: raise forms.ValidationError("Start date can't be after end date") .... return self.cleaned_data class ProviderAdmin(admin.ModelAdmin): form = ProviderForm admin.site.register(Provider, ProviderAdmin) There don't appear to be any error messages at all, so I'm not sure how to debug it - there is just … -
Large Files Uploading on Angular 4+ to Django
Currently I am uploading file using angular2-http-file-upload and send it to django back-end and it work fine with small files here is how I done it but when uploading large file 35Mb-600Mb its throwing exception from django sometimes it run fine local server but on cloud it always throwing exception my-upload-item.ts import { UploadItem } from 'angular2-http-file-upload'; export class MyUploadItem extends UploadItem { constructor(file: any) { super(); this.url = 'http://127.0.0.1:8000/training/save/'; this.file = file; } } my-component.ts submit2() { // /////////////// // Upload File // /////////////// let uploadTrainingFile = (<HTMLInputElement>window.document.getElementById('fileInput1')).files[0]; console.log('file tarining ', uploadTrainingFile); let myUploadItem1 = new MyUploadItem(uploadTrainingFile); myUploadItem1.formData = { FormDataKey: 'Form Data Value', 'category': this.category, 'type': 'Training File' }; // (optional) form data can be sent with file this.uploaderService.onSuccessUpload = (item, response, status, headers) => { // success callback console.log('successs ', response.path, response.type); console.log('seed step') }; this.uploaderService.onErrorUpload = (item, response, status, headers) => { // error callback console.log('error ', response); }; this.uploaderService.onCompleteUpload = (item, response, status, headers) => { // complete callback, called regardless of success or failure console.log('callback ', response); }; this.uploaderService.onProgressUpload = (item, percentComplete) => { // progress callback console.log('progresss ', percentComplete) }; if (typeof uploadTrainingFile != 'undefined' ) { this.uploaderService.upload(myUploadItem1); console.log('uploaded'); // if (this.uploaderService.onProgressUpload) } … -
Check Google In App Subscription Renewal Status
I have to implement Google In App susbscription in my app. In server side, I want to validate subscription status of user. The response of subscription is as follow { "kind": "androidpublisher#subscriptionPurchase", "startTimeMillis": long, "expiryTimeMillis": long, "autoRenewing": boolean, "priceCurrencyCode": string, "priceAmountMicros": long, "countryCode": string, "developerPayload": string, "paymentState": integer, "cancelReason": integer, "userCancellationTimeMillis": long, "orderId": string } Google has api to validate subscription status. Its response is as follow. { "kind": "androidpublisher#subscriptionPurchase", "startTimeMillis": long, "expiryTimeMillis": long, "autoRenewing": boolean, "priceCurrencyCode": string, "priceAmountMicros": long, "countryCode": string, "developerPayload": string, "paymentState": integer, "cancelReason": integer, "userCancellationTimeMillis": long, "orderId": string } I want to check user subscription status by using this API. The question I want to ask how will I know that user subscription has been renewed by this response. If user get subscription for one month and after one month, subscription will be renewed automatically. I have receipt for old subscription in my database and I will be using same OrderId to check subscription status. How will I new that subscription has been renewed for that particular orderId. -
Delete Objects after Saving - Django
I have a problem about Delete Object after savings Django I have model Like: class Reaction(models.Model): REACT_TYPES = ( (LIKE, 'Like'), (LOVE, 'Love'), ) user = models.ForeignKey(User) react_type = models.CharField(max_length=100, choices=REACT_TYPES, default='LIKE') How can I write a def save() with: When saving, It will remove the available object with THE SAME user, react_type. If no have the same object, it will be created. My code is work!! def save(self, force_insert=False, force_update=False, *args, **kwargs): user = Reaction.objects.filter(user=self.user) react_type = Reaction.objects.filter(user=self.react_type) # Model delete if exist if self.id.exists() & self.react_type.exists() : self.Reaction.delete() # Model create if not exist else : self.Reaction.create() Sorry because I'm not good with Django. -
Role of kafka consumer, seperate service or Django component?
I'm designing a web log analytic. And I found an architect with Django(Back-end & front-end)+ kafka + spark. I also found some same system from this link:http://thevivekpandey.github.io/posts/2017-09-19-high-velocity-data-ingestion.html with below architect But I confuse about the role of kafka-consumer. It will is a service, independent to Django, right? So If I want to plot real-time data to front-end chart, how to I attached to Django. It will too ridiculous if I place both kafka-consumer & producer in Django. Request from sdk come to Django by pass to kafa topic (producer) and return Django (consumer) for process. Why we don't go directly. It looks simple and better. Please help me to understand the role of kafka consumer, where it should belong? and how to connect to my front-end. Thanks & best Regards, Jame -
Django get Data from API
i'm using Django Rest Framework (DRF) to build API in my project. And i want to get the data from API URL in my views.py. This is my services.py import requests import json def get_user(username, first_name): url = 'http://localhost:8000/api/v1/users/' # headers = {'Accept':'application/json', 'Content-Type':'application/json'} params = {'username': username, 'first_name': first_name} r = requests.get(url, params=params) data=str(r) user_list = json.dumps(data) return user_list and this is my views.py class test(APIView): permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] def get(self,request): lists = services.get_user('Fahmi', 'Fahmi') return Response({"success": True, "content": lists}) And i got an error below From postman : { "content": "\"<Response [401]>\"", "success": true } From terminal : "GET /api/v1/users/?username=Fahmi&first_name=Fahmi HTTP/1.1" 401 58 What is wrong in my code? -
ModuleNotFoundError: Trying to import model from models folder into a view in views folder
I am new to the Django framework and I have some questions regarding importing of modules. Below is my file structure: MyLife - MyLife - finance - models - __init__.py - category.py - views - __init__.py - category.py I am trying to import the models.category into my views.category. models.__init__.py: from .base_model import BaseModel from .category import Category from .client import Client from .entry import Entry from .rule import Rule from .wish_list_item import WishListItem __all__ = ['BaseModel', 'Category', 'Client', 'Entry', 'Rule', 'WishListItem'] views.category.py: from django.shortcuts import render from MyLife.finance.models import Category def category(request): all_categories = Category.objects.all() return render(request, 'finance/category.html', {'list_categories': all_categories}) models.category.py: from django.db import models from .base_model import BaseModel class Category(BaseModel): description = models.CharField(max_length=50) def __str__(self): return self.description Here is my stack trace error: File "/Users/AKJ/Coding/MyLife/MyLife/finance/urls.py", line 3, in <module> from . import views File "/Users/AKJ/Coding/MyLife/MyLife/finance/views/__init__.py", line 3, in <module> from . category import category File "/Users/AKJ/Coding/MyLife/MyLife/finance/views/category.py", line 3, in <module> from MyLife.finance.models import Category ModuleNotFoundError: No module named 'MyLife.finance' I am not sure what is wrong and if i am missing something out. I heard a lot about init.py to help reduce the namespace, however, i seem to have problems and i do not really understand the other stackoverflow … -
Using https as standard with django project
I am learning django and trying to complete my first webapp. I am using shopify api & boilder plate (starter code) and am having an issue with the final step of auth. Specifically, the redirect URL -- it's using HTTP:// when it should NOT and I don't know how to change it.. #in my view def authenticate(request): shop = request.GET.get('shop') print('shop:', shop) if shop: scope = settings.SHOPIFY_API_SCOPE redirect_uri = request.build_absolute_uri(reverse('shopify_app_finalize')) #try this with new store url? print('redirect url', redirect_uri) # this equals http://myherokuapp.com/login/finalize/ permission_url = shopify.Session(shop.strip()).create_permission_url(scope, redirect_uri) return redirect(permission_url) return redirect(_return_address(request)) Which is a problem because my app uses the Embedded Shopify SDK which causes this error to occur at the point of this request Refused to frame 'http://my.herokuapp.com/' because it violates the following Content Security Policy directive: "child-src 'self' https://* shopify-pos://*". Note that 'frame-src' was not explicitly set, so 'child-src' is used as a fallback. How do i change the URL to use HTTPS? Thank you so much in advance. Please let me know if I can share any other details but my code is practically identical to that starter code -
how to upload image to django application from android using okhttp3
File sourceFile = new File(str_image); Log.d("TAG", "File...::::" + sourceFile + " : " + sourceFile.exists()); final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/jpeg"); String filename = str_image.substring(str_image.lastIndexOf("/")+1); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("listing_image", filename, RequestBody.create(MEDIA_TYPE_PNG, new File(str_image)) .addFormDataPart("bussinessName", str_businessName) .addFormDataPart("services",str_Services) .addFormDataPart("create_new","1") .addFormDataPart("referer",str_referer) .addFormDataPart("link","-1") .build(); Request request = new Request.Builder() .url(URL_UPLOAD_IMAGE) .post(requestBody) .build(); OkHttpClient client = new OkHttpClient(); Response response = client.newCall(request).execute(); String res = response.body().string(); Log.e("TAG", "Error: " + res); return new JSONObject(res); This my uploading code using okhttp in android app And Below code is the request header when i am trying to upload image from web interface. Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8 Accept-Encoding:gzip, deflate Accept-Language:en-US,en;q=0.8 Cache-Control:no-cache Connection:keep-alive Content-Length:2867997 Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryNgoNfg2kEYAAQDeH Here i am uploading the image to django rest api -
UnicodeDecodeError: 'utf8' codec can't decode byte 0xc7 in position 27: invalid continuation byte django
I'm trying to upload my django project to Google Cloud Platform. When I run python manage.py runserver an error occurs. Until a while ago, it worked well. After fixing codes of just one file 'setting.py' the error occurred. Here's a screenshot image below. I did my best to find the solution on Google and Stackoverflow, and I tried hard for find something wrong in my code, but I couldn't find anything. Here's my directory structure, my main codes, and Project interpreter settings below. (Because I never changed other codes in my project and the amount of codes are too many, I won't upload all the codes in my django project.) views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return HttpResponse("Hello, world!") urls.py from django.conf.urls import url from django.contrib import admin from my_app import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.home) ] settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'secret … -
Django SSL Site getting timed out when multiple users access
I have a Django site running in apache server. which is working fine using http. but using https and more that 7 users assesing the site, the site is getting down The main configured settings.py content is attached. Hope Someone can help to fix this issue. Also I have updated the firewall using sudo ufw allow https. CORS_REPLACE_HTTPS_REFERER = True HOST_SCHEME = "https://" SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True #SECURE_SSL_REDIRECT = False SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True X_FRAME_OPTIONS = 'ALLOW' SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_SECONDS = 31536000 SECURE_HSTS_PRELOAD = False SECURE_FRAME_DENY = True Thanks, Joseph -
User-Created Fields in Django Models
I'm creating a contact form which would allow users to create custom fields. I'm trying to pass request or a group object into the model.py. I would need this line contact_custom_char1 = ContactCustomCharField.objects.filter(group=group)[0] but don't know how to get the group or request there. How should I go about this? What is a way of letting users customize form fields? Let me know if I'm not being clear enough. class ContactCustomCharField(models.Model): editable = models.BooleanField(default=False) name = models.CharField(max_length=50, null=True) group = models.ForeignKey(Group, editable=False, blank=True, null=True, on_delete=models.SET_NULL) try: contact_custom_char1 = ContactCustomCharField.objects.get(pk=1) except: contact_custom_charl = ContactCustomCharField.objects.create(editable=False, name='None', group=group) try: contact_custom_char2 = ContactCustomCharField.objects.get(pk=2) except: contact_custom_char2 = ContactCustomCharField.objects.create(editable=False, name='None', group=group) try: contact_custom_char3 = ContactCustomCharField.objects.get(pk=3) except: contact_custom_char3 = ContactCustomCharField.objects.create(editable=False, name='None', group=group) class Contact(models.Model): company = models.ForeignKey(Company, null=True, blank=True, on_delete=models.SET_NULL) first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) title = models.CharField(max_length=50, blank=True) owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL) owner_group = models.ForeignKey(Group, editable=False, blank=True, null=True, on_delete=models.SET_NULL) custom_char1 = models.CharField(max_length=50, blank=True, null=True, editable=contact_custom_char1.editable, verbose_name=contact_custom_char1.name) custom_char2 = models.CharField(max_length=50, blank=True, null=True, editable=contact_custom_char2.editable, verbose_name=contact_custom_char2.name) custom_char3 = models.CharField(max_length=50, blank=True, null=True, editable=contact_custom_char3.editable, verbose_name=contact_custom_char3.name) -
Unable to log in with provided credentials - drf django
I have made a custom User Model and using that. Now, I want token auth in my app, so I generated a token for every user in my database. But that does not work for users other than superuser. This is the custom user, class User(AbstractBaseUser, PermissionsMixin): mobile = models.CharField(max_length=15,unique=True) email = models.EmailField(unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30,blank=True) date_joined = models.DateTimeField(auto_now_add=True) is_on_booking = models.BooleanField(default=False) is_acitve = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) bookings_count = models.IntegerField(default=0) GENDER_TYPES = (('male','m'),('female','f'),('other','o')) gender = models.CharField(max_length=15,choices=GENDER_TYPES,blank=True) objects = MyUserManager() USERNAME_FIELD = 'mobile' REQUIRED_FIELDS = ['email','first_name'] This is my custom usermanager, class MyUserManager(BaseUserManager): def _create_user(self, mobile, email, first_name, is_staff, is_superuser, password, **extra_fields): if not mobile: raise ValueError('User must give a mobile Number') email = self.normalize_email(email) user = self.model(mobile=mobile,email=email,first_name=first_name, is_staff=is_staff, is_superuser=is_superuser, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, mobile, password=None, email=None, first_name=None, **extra_fields): return self._create_user(mobile, email, first_name, False, False, password, **extra_fields) def create_superuser(self, mobile, email, first_name, password, **extra_fields): return self._create_user(mobile, email, first_name, True, True, password, **extra_fields) The superuser for which it returns the token was made using the default django User Model. So, I get that the problem is somewhere in my custom model OR custom manager. When I try to get token for user … -
django dynamically update ModelForm's Meta Class widgets
I want to dynamically generate ModelForm's Meta Class widgets according to exercise_type field from Exercise class. How can I get the value? class ExerciseAdminForm(ModelForm): class Meta: model = Exercise fields = '__all__' widgets = { 'starter_code': _make_language_mode(exercise_type=Exercise.exercise_type) } -
Django pagination + filter
have a problem with using pagination and filtering. I'm using filtering django-filter and paginator in CBV(ListView). Everything is working. The paginator wraps the box after filtering, the problem is in the buttons of the paginator in the template. When you press NEXT or PREV the filter is reset. I found a solution: <span><a href="?page={{ page_obj.previous_page_number }} {% for key,value in request.GET.items %} {% ifnotequal key 'page' %}&{{ key }}={{ value }}{% endifnotequal %} {% endfor %}">Previous</a> </span> But this does not solve the problem completely, so I can send a request from my filter: ?item_title=&description=&ordering=&popular=&min_price=&max_price=&category_brands=11&category_brands=13 And since i have two category_brands= in url and this solution don't work becouse I can not have two identical keys. Please help me. -
related_query_name's default / fallback behaviour has changed in Django 1.10
I am updating a project from Django 1.8 to Django 1.11. It's a somewhat mature / complex project with a lot of models and queries. It seems that a backwards incompatible change was made in Django 1.10, namely the default behaviour of ForeignKey.related_query_name. In Django 1.10, related_query_name falls back to the model's default_related_name - in Django 1.8 this was not the case. This change is apparent in the docs: Django 1.9: https://docs.djangoproject.com/en/1.9/ref/models/fields/#django.db.models.ForeignKey.related_query_name Django 1.10: https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.ForeignKey.related_query_name Almost all of my models have default_related_name defined, yet no ForeignKeys have related_query_name set. This means that essentially all of my database queries that traverse relationships are invalid! Am I doomed to rewrite all my queries, or add related_query_name to everything? Or is there some way to retain the old functionality? -
Use multiple database connections based on user role
In my Django project, I would like to restrict the DB access for users based on their respective roles. For example, a user with admin role will have a DB connection with which he can read and write and a normal user will have a read-only database connection. I already tried the 'DATABASE-ROUTERS'.I am using PostgreSQL. -
How to enable function to render templates based on try, except blocks from within another view in Django?
I am creating an application in Django that would allow my users to order items from my site based on information already stored in the database. Not all my users should be able to order certain items, for this purpose I have written a pipeline with comparison statements and try, except blocks. A small, reproduce-able piece of code looks like this: vendor.py def guest_constraint(request) # Ensure user in request is a house-guest by checking if it has an active token. try: guest = GuestProfile.objects.get(user=request.user.id) except ObjectDoesNotExist: return render(request, 'extGuest/appGuestError/not_hotel_login.html') # Check for Hotel Room Information linked to Guest Token try: room_information = RoomInformation.objects.get(guest_token=guest.token) except ObjectDoesNotExist: return render(request, 'extGuest/appGuestError/constraint_error.html') views.py from .vendor import guest_constraint @login_required def index(request): user = request.user # Grab user defined in request. name = user.get_short_name() # Grab first name of user. return render(request, 'extGuest/appGuestFlow/choose_order_type.html') Challenge: I can successfully import this small script into my view and I can see its content is run except for the return render(request, template) part. To explain myself better, the try/except block successfully catch the exception, however it does not returns the template specified in the block but instead it goes back to the view and renders the template I have in … -
Returning related fields of a model instance
I am creating an app with a rest API that should return values for instances of objects based on the url given. Right now I have the API working using ModelViewSets of my objects for the API. For example I have three objects, user, transactions, and goals. As it stands I can go to /mysite/api/users and return a list of all users I can also go to /mysite/api/users/1 to return just the user with the id '1'. I can do something similar with transactions and goals. What I'm looking to do is go to url /mysite/api/users/1/transaction/1/goal to find the goal associated with the transaction for that user. I've been scouring tutorials and am not sure what the right question is to ask in order to find something useful to learn how to do this. What is the correct way to go about setting up my rest api like this? -
Use the generate_files_directory method to change the FielField upload_to param do not work
I write a generate_files_directory method to generate the upload path: def generate_files_directory(self,filepath): url = "images/%s" % (filepath) return url The model is bellow: class Upload(models.Model): filepath = models.CharField(max_length=64, default="imgs/test/") pic = models.FileField(upload_to=generate_files_directory) upload_date=models.DateTimeField(auto_now_add =True) The form code is bellow: class UploadForm(ModelForm): class Meta: model = Upload fields = ('pic', 'filepath') my views.py: def home(request): if request.method=="POST": img = UploadForm(request.POST, request.FILES) if img.is_valid(): img.save() return HttpResponseRedirect(reverse('imageupload')) else: img=UploadForm() images=Upload.objects.all() return render(request,'home.html',{'form':img,'images':images}) and I write a home.html to upload the files: <div style="padding:40px;margin:40px;border:1px solid #ccc"> <h1>picture</h1> <form action="#" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form}} <input type="submit" value="Upload" /> </form> {% for img in images %} {{forloop.counter}}.<a href="{{ img.pic.url }}">{{ img.pic.name }}</a> ({{img.upload_date}})<hr /> {% endfor %} </div> But seem it did not upload to the generated path, it still upload to the /images/ directory: all in there: -
Could any body plz help about how I can read this error? I am sure I typed import unittest truly and I am not sure why my code does not work?
When I run my code which is about testing my class code, I get the error below Traceback (most recent call last): File "my_servy_test.py", line 1, in <module> import unittest File "C:\python34\lib\unittest\__init__.py", line 59, in <module> from .case import (TestCase, FunctionTestCase, SkipTest, skip, skipIf, File "C:\python34\lib\unittest\case.py", line 6, in <module> import logging File "C:\python34\lib\logging\__init__.py", line 28, in <module> from string import Template File "C:\Users\flower\Documents\python_work\string.py", line 2 ^ SyntaxError: unexpected EOF while parsing ------------------ (program exited with code: 1) Press any key to continue . . . -
Making code for user in django
I'm creating database in django app. How can I make auto-generation of 8 character for every new registered user? For example, user creates his login and password and system assign him 8 character number, so I can lately use this number in app to search that user instead of using his login -
I get `AnonymousUser` Error when I access my api using axios, but I have really login the account
I get AnonymousUser Error when I request the api, but I have really login the account: File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Users/luowensheng/Desktop/QIYUN/Project/Qiyun02/用户管理后台/产品管理/user_admin_productmanage_cloudserver/api/views.py", line 153, in dispatch result = super(CloudServerListAPIView2, self).dispatch(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/Users/luowensheng/Desktop/QIYUN/Project/Qiyun02/用户管理后台/产品管理/user_admin_productmanage_cloudserver/api/views.py", line 159, in get openstackclouduserid = self.request.user.openstackcloud_userid File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/utils/functional.py", line 239, in inner return func(self._wrapped, *args) AttributeError: 'AnonymousUser' object has no attribute 'openstackcloud_userid' The bellow logs can prove me have login my developing website: [28/Nov/2017 11:40:59] "OPTIONS /rest-auth/login/ HTTP/1.1" 200 0 [28/Nov/2017 11:41:00] "POST /rest-auth/login/ HTTP/1.1" 200 50 [28/Nov/2017 11:41:07] "POST /api/user_productmanage/cloudserver/logincloudaccount/ HTTP/1.1" 200 23 My frontend code is bellow: The structure of my Axios method: import qs from 'qs' import Vue from 'vue' import ApiSetting from './config' import Cookies from 'js-cookie'; const Axios = axios.create( ApiSetting.AxiosConfig ); Axios.interceptors.request.use( config => { // 在发送请求之前做某件事 if ( config.method === "post" || config.method === "put" || config.method === "delete"|| config.method === "get" ) { // 序列化 config.data = qs.stringify(config.data); } // 若是有做鉴权token , 就给头部带上token if (Cookies.get('tokens')!==undefined) { config.headers['Authorization']= 'Token '+Cookies.get('tokens'); } return config; }, error => { //出错 return Promise.reject(error.data.error.message); } ); //拦截器 Axios.interceptors.response.use(function (response) { // 相应成功 return response; }, function …