Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python DES Encryption
I have a project where our provider has their own DES Encryption logic however I am using django as my backend. I can run the java using subprocess but I'm actually planning to convert that java code to python.. Here is my code: import java.io.*; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import sun.misc.BASE64Encoder; import sun.misc.BASE64Decoder; public class PHPDESEncrypt { String key; public PHPDESEncrypt() { } public PHPDESEncrypt(String key) { this.key = key; } public byte[] desEncrypt(byte[] plainText) throws Exception { SecureRandom sr = new SecureRandom(); DESKeySpec dks = new DESKeySpec(key.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(dks); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, key, sr); byte data[] = plainText; byte encryptedData[] = cipher.doFinal(data); return encryptedData; } public String encrypt(String input) throws Exception { return base64Encode(desEncrypt(input.getBytes())).replaceAll("\\s*", ""); } public String base64Encode(byte[] s) { if (s == null) return null; BASE64Encoder b = new BASE64Encoder(); return b.encode(s); } public static void main(String args[]) { try { PHPDESEncrypt d = new PHPDESEncrypt(args[0]); String p=d.encrypt(args[1]); System.out.println(p); } catch (Exception e) { e.printStackTrace(); } } public String getKey() { return key; } public void setKey(String key) { this.key = key; } } Any suggestions on how to convert this? Like a … -
How to force Generic Editing Views using set methods from Model
I'm trying to work with Generic Editing Views to do CRUD operations with my custom models. The problem is, one of these models is a custom User and my CreateView/UpdateView doesn't use the set_password method from model to save password, resulting on non-cryptographic data. I googled about how to force them to use set methods but I couldn't find anything. My custom User model: class User(AbstractBaseUser): name = models.CharField(max_length=MEDIUM_LENGTH, verbose_name='Nome') username = models.CharField(max_length=MEDIUM_LENGTH, unique=True, verbose_name='Nome de Usuário') email = models.CharField(max_length=MEDIUM_LENGTH, unique=True, verbose_name='Email') profile = models.ForeignKey('Profile', on_delete=models.CASCADE, related_name='users', verbose_name='Perfil') creation_date = models.DateTimeField(auto_now_add=True, verbose_name='Data de Criação') is_active = models.BooleanField(default=True, verbose_name='Ativo') is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['password','email'] class Meta: ordering = ['name'] My User Generic CreateView/UpdateView: class UsuarioView(ModelView): model = User def get_context_data(self, **kwargs): context = super(UsuarioView, self).get_context_data(**kwargs) context['profiles'] = Profile.objects.all() return context class UsuarioCriarView(UsuarioView, CreateView): pass class UsuarioEditarView(UsuarioView, UpdateView): context_object_name = 'user' -
Cannot get "_set" from model using "self" in foreign key
I'm trying to get the related objects using _set in Django. I want to get all objects which are referring to the parent object. My model: class MessageBoard(models.Model): title = models.CharField(max_length=40) message = models.TextField() person = models.ForeignKey(User) date = models.DateTimeField() parent = models.ForeignKey("self", default=None, null=True) But when I try to get the set of an object I get an error. >>> msg = MessageBoard.objects.get(pk=1) >>> msgs = msg.parent_set.all() Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'MessageBoard' object has no attribute 'parent_set' If I do >>> MessageBoard.objects.filter(parent=1) It return the objects as I want. I need the other way because I want to use inside django templates. -
Django Migration Error with MySQL: BLOB/TEXT column 'id' used in key specification without a key length"
We have Django Model, use Binary Field for ID. # Create your models here. class Company(models.Model): id = models.BinaryField(max_length=16, primary_key=True) name = models.CharField(max_length=12) class Meta: db_table = "company" We use MySQL Database and have error when migrate. File "/home/cuongtran/Downloads/sample/venv/lib/python3.5/site-packages/MySQLdb/connections.py", line 270, in query _mysql.connection.query(self, query) django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'id' used in key specification without a key length") Do you have any solution? We need to use MySQL and want to use the Binary Field for ID. Thank you! -
Django unable to find static files
I followed to tutorial and I still cannot get static files like .css files and images to load onto a template. Everything you see on the tutorial I did so don't ask me if i didn't because I did. Tutorial Errors: Not Found: /polls/about/simple.jpg Not Found: /polls/about/style.css Debug is set to True: Error from debug: [![Pics of error][2]][2] -
Error asking for secret key but secret key is already inserted
I keep getting an error when running my backend for Django. Here is the traceback: Traceback (most recent call last): File "/Users/lyndseearmstrong/dev/recipe_organizer/backend/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/core/management/__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/core/management/__init__.py", line 195, in fetch_command klass = load_command_class(app_name, subcommand) File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/core/management/__init__.py", line 39, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 16, in <module> from django.db.migrations.executor import MigrationExecutor File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/db/migrations/executor.py", line 7, in <module> from .loader import MigrationLoader File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/db/migrations/loader.py", line 10, in <module> from django.db.migrations.recorder import MigrationRecorder File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 12, in <module> class MigrationRecorder(object): File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 26, in MigrationRecorder class Migration(models.Model): File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 27, in Migration app = models.CharField(max_length=255) File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1072, in __init__ super(CharField, self).__init__(*args, **kwargs) File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 166, in __init__ self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/conf/__init__.py", line 55, in __getattr__ self._setup(name) File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/Users/lyndseearmstrong/.virtualenvs/recipe_organizer/lib/python2.7/site-packages/django/conf/__init__.py", line 120, in __init__ raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. Here are my urls: from django.conf.urls import include, url from django.contrib import admin from django.views.static import serve … -
Where to generate JSON schemas that change depending on model fields?
In Django, I need to represent payment details for a client. These payment details depend on which country the client is in. For example, US has a Routing Number and Account Number while Canada has Institution, Transit, Account Numbers and anything European has IBAN and BIC. I think data like this is exactly what JSON storage is made for so I used PostgreSQL's JSONField. class Client(models.Model): country = CountryField(blank=True) payment_details = JSONField() After some time, I figured the best place to populate the JSONField with a schema appropriate for the country is in the frontend, because in the backend, I would have to wait for the model to be saved first, which is silly from the user's perspective. If I am to populate it in the frontend, then I'd have to override Django's admin template, and somehow include Javascript that watches one of the model's fields in HTML and if it changes, look up the schema and populate the JSON field with the appropriate schema. Is this the right solution to my problem, and how can I do this? I'm unfamiliar with overriding Django admin templates. -
Python library authentication pop up is targeting server and not the client
I developed a library to authenticate users with google using httplib2.Http() the problem is that the dialog box pop up in the server or localhost browser not in the client browser. Also I am using Django to call this library. Any clue how can I target the client browser ?? def get_service(self): # Create an httplib2.Http object and authorize it with our credentials http = httplib2.Http() try: http = self.credentials.authorize(http) service = build('analytics', 'v3', http=http) return service except AttributeError, e: logger.exception('No credentials!') logger.exception(e) -
How to install packages in debian whitout sudo permission?
I want to up a django server on a shared-hosting domain (debian/jessie). I don't have root permission, so i can-t execute "apt-get install package". I success to run a virtualenv but i need to install some common package to run django successfully. -libssl-dev -openssl -build-essential -python-dev -libmysqlclient-dev I hope someone can help me -
Django request.DATA gets corrupt value
My problem My problem is that when sending a json document via post to a rest framework api, the document converts a key and adds an empty value. file.js function SaveFiles(task_id) { data = {'taskid': task_id,'file_list': file_list}; $.ajax({ url: '/tarjet/save.../', type: 'POST', data: JSON.stringify(data), async:false, success:function(data){ }, complete:function(){}, error:function (xhr, textStatus, thrownError){ } }); } api.py class SaveTaskFiles(APIView): authentication_classes = (TokenAuthentication,) def post(self, request): a = request.DATA javascript output {"taskid":"1198792","file_list":[{"id":0,"file_name":"image2.png","upload_date":"11/16/2016","file_description":"","download_link":"a6175ab4-ac58-11e6-8e10-00dbdfd54837.png","isdeactivate":"0","sft_f":"svt"}]} actual input request.DATA {u'{"taskid":"1198792","file_list":[{"id":0,"file_name":"image2.png","upload_date":"11/16/2016","file_description":"","download_link":"a6175ab4-ac58-11e6-8e10-00dbdfd54837.png","isdeactivate":"0","sft_f":"svt"}]}': [u'']} Is a Querydict type. I can not explain why my json file becomes a key,and this value is a empty list, i have solved it using request.body, but I know it's not the convention. I've tried dumps, loads, but it did not work, although I could get the key and use it, I do not think that's a good idea. Beforehand thank you very much ¡ -
Getting NoReverseMatch Error
I'm new to django, but I have gone through the tutorial (running 1.10.2). I have an app that is going to display some information about people in my group. I'm getting a NoReverseMatch error when trying to use the url tag in my index.html. If I do not use the url tag, but specify the root, I do not receive the error. The error says: NoReverseMatch at / Reverse for 'specialist' with arguments '(1,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['$(?P[0-9]+)/'] Here is are the urls.py files. From the main wi_tech urls.py: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^$', include('person.urls')), url(r'^tech/', include('person.urls')), url(r'^admin/', admin.site.urls), ] From the 'person' app urls.py: from django.conf.urls import url from . import views app_name = 'person' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='specialist'), ] My views.py file looks like this: from django.views import generic from .models import Specialist class IndexView(generic.ListView): template_name = 'person/index.html' context_object_name = 'person_list' def get_queryset(self): """Return all specialists""" return Specialist.objects.order_by('id') class DetailView(generic.DetailView): model = Specialist template_name = 'person/detail.html' And my index.html page looks like this: {% if person_list %} <ul> {% for specialist in person_list %} <li><a href="{% url 'person:specialist' specialist.id … -
How long should it take to integrate Stripe as a payment gateway for a fairly large Django application?
Here's the scenario. We have a Django application that works much like AirBnB but we need it to handle payments. Stripe is the only one we've been in contact with that can handle our needs for the platform. A development team quoted us 240 hours to integrate Stripe as a payment gateway into our Django based application. Can anyone who has experience with Stripe and/or Django take a look at the requirements below and help us gauge if this is reasonable or outrageous? I know this is a challenge without a link to the platform but we don't have a live link nor are we allowed to host the source code publicly. An attempt at a hot or cold answer here would really help us out a lot. Develop process to cancel booking if funds are not confirmed Develop process to deposit into site owner's account. Develop process to charge back on cancellations. Develop process for accounting > Site owner's fee Develop process for accounting > deposit into ACH payment Develop billing reports logic to pull transaction data via Stripe Develop process for coupons Develop process for accounting to reconcile if a space is rented, for how much, when, and … -
Missing field in a Django User custom model
After experimenting with classical serializers in Django REST, I am currently trying to work with custom models i.e. my model has a OneToOneField field. My model (in models.py) is a custom User: class Friend2(models.Model): user = models.OneToOneField(User) add_field = models.CharField(max_length=15) And I serialize it (in serializers.py) with (based on this SO topic): class Friend2Serializer(serializers.HyperlinkedModelSerializer): add_field = serializers.CharField(source='friend2.add_field') class Meta: model = User fields = ('id', 'username', 'password', 'email', 'add_field') def create(self, validated_data): profile_data = validated_data.pop('friend2', None) user = super(Friend2Serializer, self).create(validated_data) self.create_or_update_user(user, profile_data) return user def update(self, instance, validated_data): profile_data = validated_data.pop('friend2', None) self.create_or_update_profile(instance, profile_data) return super(Friend2Serializer, self).update(instance, validated_data) def create_or_update_user(self, user, profile_data): profile, created = Friend2.objects.get_or_create(user=user, defaults=profile_data) if not created and profile_data is not None: super(Friend2Serializer, self).update(profile, profile_data) To POST data to register a new user, I use the following code snippet: import requests import json json_data = {'username': 'mylogin12', 'password': 'mypassword', 'email': 'mymail12@wanadoo.fr', 'add_field' : 'myaddfield'} r = requests.post('http://127.0.0.1:8000/register_new_user', json=json_data) And in my views.py: @api_view(['POST']) def register_new_user(request): if request.method == 'POST': print('POST request !') print(request.data) serializer = Friend2Serializer(data=request.data) if serializer.is_valid(): serializer.save() print('save friend!') return HttpResponse(status.HTTP_201_CREATED) else: print(serializer.errors) return HttpResponse(status.HTTP_403_FORBIDDEN) So far, it works. However, when I try to retrieve all the registered users with: def get_all_users(request): all_friends = Friend2.objects.all() … -
Django runserver with DEBUG True serving the wrong static files
Trying to server staticfiles via runserver for development, with Django 1.10 I have 'django.contrib.staticfiles' in my INSTALLED_APPS and the following relevant settings: STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.AppDirectoriesFinder", "django.contrib.staticfiles.finders.FileSystemFinder", ) STATICFILES_DIRS = [ path('node_modules'), # resolves to `node_modules/` in the project root ] STATIC_URL = '/static/' STATIC_ROOT = path('static') # resolves to `path/` in the project root This works fine for collectstatic, and serves fine via NginX directly. However with runserver + DEBUG=True, I'm expecting Django webserver to serve from the static/ folder, but instead it is serving from node_modules/ folder. If I remove/rename node_modules/ then I get 404s for static files. The static files are collected by copy (not symlink). I'm using Django channels which could be hijacking everything as well? -
Django 1.7 AttributeError: 'WSGIRequest' object has no attribute 'user'
I have read some similar posts but none helped me plus I was recommended to create a new question. I try to reach to admin page of an inherited web-site and I created a user for that matter but I reach to the admin page I get the below stack trace. I have also added the settings.py in case it helps. Any input is much appreciate it. M 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.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'XXXXX' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # ALLOWED_HOSTS = ['0.0.0.0', 'localhost'] ALLOWED_HOSTS = ['192.168.1.36', 'localhost'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 'south', 'CordeliaHanelBackend', 'tastypie', 'StudioHanel', ] 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 = 'CordeliaHanelBackend.urls' PROJECT_ROOT = os.path.dirname(os.path.dirname(__file__)) TEMPLATE_DIRS = ( '/var/www/CordeliaHanelBackend-master/StudioHanel/templates2', ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # 'DIRS': ['/var/www/CordeliaHanelBackend-master/StudioHanel/templates2'], '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 = 'CordeliaHanelBackend.wsgi.application' # Database … -
Django ChoiceField not working insed {% for sub in subs %}
Inside my django project i have a template called formquestions.html. Inside the html template I am looping through all sub categories from my database (right now it is only 1 for testing purposes). My issue is that my ChoiceField is not dropping down so you may select other options. If I movie outside of the for loop it works just fine. form.py file contents - DATA_DISPLAY_TYPE = ( ('input', 'Input'), ('select', 'Select'), ('checkbox', 'CheckBox'), ) class EditSubInfo(forms.Form): help_text = forms.CharField(widget=forms.Textarea) data_display_type = forms.ChoiceField(choices=DATA_DISPLAY_TYPE) template file to update the type of data type the sub is - <html> <head> </head> <body> {% for sub in subs %} Name: sub.name Choices: {{form.data_display_type}} {% endfor %} </body> </html> The ChoiceField renders just fine. But when you try to click on it, nothing happens. If I move it outside of the for loop, it will work just fine. Any ideas of what is going wrong? -
Django Rest Framework - Unit test image file upload
I am trying to unit test my file uploading REST API. I found online some code generating the image with Pillow but it can't be serialized. This is my code for generating the image : image = Image.new('RGBA', size=(50, 50), color=(155, 0, 0)) file = BytesIO(image.tobytes()) file.name = 'test.png' file.seek(0) Then I try to upload this image fille : return self.client.post("/api/images/", data=json.dumps({ "image": file, "item": 1 }), content_type="application/json", format='multipart') And I get the following error: <ContentFile: Raw content> is not JSON serializable How can I transform the Pillow image so it's serializable? -
Need to generate alt text for Fancy Box images from Django gallery
I have images in a Django/Mezzanine gallery with a description and need to grab that description and insert it into the alt text of the image when it's displayed with Fancy Box. This is the fancybox template. I've added tags into the alt="" part but nothing. Any suggestions for getting that description entered in the Django/Mezzanine admin? // HTML templates tpl: { wrap : '<div class="fancybox-wrap" tabIndex="-1"><div class="fancybox-skin"><div class="fancybox-outer"><div class="fancybox-inner"></div></div></div></div>', image : '<img class="fancybox-image" src="{href}" alt="" />', iframe : '<iframe id="fancybox-frame{rnd}" name="fancybox-frame{rnd}" class="fancybox-iframe" frameborder="0" vspace="0" hspace="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen' + (IE ? ' allowtransparency="true"' : '') + '></iframe>', error : '<p class="fancybox-error">The requested content cannot be loaded.<br/>Please try again later.</p>', closeBtn : '<a title="Close" class="fancybox-item fancybox-close" href="javascript:;"></a>', next : '<a title="Next" class="fancybox-nav fancybox-next" href="javascript:;"><span></span></a>', prev : '<a title="Previous" class="fancybox-nav fancybox-prev" href="javascript:;"><span></span></a>' }, -
why should I use django rest framework instead of django's built in serializers?
I am building my first django app and not sure why should I use django rest framework, when I have json and xml serializers built into django.core module: https://docs.djangoproject.com/en/1.10/topics/serialization/ I anyone could clarify this to me, it would be great. Thanks! -
Django Form building in the Admin
I've been trying to get dynamic forms for my Django project, and I'm using an app I've found for that. The idea is for the admin user to be able to create a new form, by giving it a name, description, and then add 1 or more fields to that form, that might be of several types (each field may be text, numbers, urls, etc...) My issue here is that I want 1 Field to be 'pre-filled' (or 'default') as I know that this 1 field will be used in all of the forms (it's a field for representation of map coordinates). I've made some changes to this app, thanks to some help in another question, and tried to pre-fill fields in the admin.py code. I get this in the admin (the fields that will be in in the form that's being created): Every single field is filled with Map Coordinates, even when trying to edit already created forms where I've put other types of fields in there, which ends up making my solution worthless. I want 1, and only 1 of the fields, to be 'pre-filled', so I want the form creation to look like this (I've cleared the … -
How to change settings for email confirmation (text, activation_url, ...) django rest auth
I am using Django as back-end and React as front-end for my application. I want to implement user registration via rest. I came across django rest auth that has some out of the box features like JWT tokens support, login, registration and sending email for confirmation, change password etc.. And this is where I am stuck I still didn't figure it out how to change email text, activation url (and that react will know that user clicked on the activation link recieved via email). First if I understand correctly I should create a new router in React and then just make request back to REST Django API verify the UID, make mark in DB that user has verified email and return a Response. Next two things are customizing the send email. I know that I should change RegisterSerializer and it's save method, but after reading that code for two days I kinda got lost. I want to know how to do the job with a little effort as possible. Library rest auth also uses special tables for verified email and for email. I would like to migrate that to UserProfile table and just add additional field email_verified. Any advice would … -
Custom user permission based on User Profile Model Filed Role
i am creating a Todo list app using Django rest framework. in this app only manager can post task in the list. User Profile has a field named as a role. I have a User Profile Model with extended User Model. model.py class UserProfile(models.Model): user = models.OneToOneField(User,unique=False) department = models.CharField(max_length=50, choices=DEPARTMENT_CHOICES,default='technology') role = models.CharField(max_length=50, choices=ROLE_CHOICES,default='manager') User Profile have a role field. I want the only manager can post Task in my app. How can I write custom user permission in order to achieve this? restrict only POST request all another request can be permitted. -
Error when I try to migrate a custom user model
I have app named: custom_user. models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): facebook = models.CharField( max_length=100, blank=True, null=True, help_text='Url to facebook profile.', ) I put in settings.py: AUTH_USER_MODEL = 'custom_user.CustomUser' I make migrations with: python manage.py makemigrations Migrations for 'custom_user': custom_user\migrations\0001_initial.py: - Create model CustomUser After I try to migrate: python manage.py migrate C:\Users\Senciuc Serban\PycharmProjects\website_bancuri>python manage.py migrate custom_user Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\Senciuc Serban\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\Senciuc Serban\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Senciuc Serban\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Senciuc Serban\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 345, in execute output = self.handle(*args, **options) File "C:\Users\Senciuc Serban\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\commands\migrate.py", line 86, in handle executor.loader.check_consistent_history(connection) File "C:\Users\Senciuc Serban\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\loader.py", line 292, in check_consistent_history connection.alias, django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency custom_user.0001_initial on database 'default'. NOTE: When I migrate first: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying sessions.0001_initial... OK PS Long … -
How to Identify a variable in a table Python/Django
I want to know how I can identify a possible issue in my system. I manage a big data table (always around 2300-2600 lines). Every SOSS line can have duplicates some of them are unique. But for the duplicated SOSS lines I need to identify if they don't have the same BU and mark them as an issue (in a new column), another issue may be if an order has the same Part Number as shown in the image below: Is there a way to create a function to identify this issue? I have an idea but nothing clear. First to create a variable that makes a filter from every SOSS def soss_issues(): for item in Data.objects.all(): each_soss = Report.objects.filter(soss=item.soss) try: #HERE do a logic that verifies the BU if they have the same continue else mark as an issue and save except: #I have an idea to add an append from a list Let me know if you need more details, Thanks for your time, -
Django Queryset slice makes many queries to the database
Have an view code: posts = category.category_posts.filter( ~Q(pk=id), date_published__lte=timezone.now(), is_active=True).order_by('-date_published')[:19] right_now = posts[:5] actual = posts[5:10] old_1 = posts[10:12] old_2 = posts[12:14] old_3 = posts[14:19] When rendering in the template, Django performs a query to the database for each slice. Just 5. A Queryset is lazy. As to reduce to a one query?