Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Aligning Text boxes Django
This is my registration form: Registration Form I am trying to align all of the text boxes. This is my form code; Forms.py class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True, label = "Email:") username = forms.CharField(required=True, label = "Username:") first_name = forms.CharField(required=True, label = "First Name:") last_name = forms.CharField(required=True, label = "Last Name:") password1 = forms.CharField(widget=forms.PasswordInput, required=True, label = "Password:") password2 = forms.CharField(widget=forms.PasswordInput, required=True, label = "Confirm Password:") class Meta: model = User fields = { 'password2', 'username', 'first_name', 'last_name', 'email', 'password1' } Any help is greatly appreciated. -
Handling multiple query params
I have a create user view and here I first register a normal user and then create a player object for that user which has a fk relation with the user. In my case, I have three different types of users, Player, Coach, and Academy. I created a view to handle register all three different types of users, but my player user has a lot of extra model fields and storing all query params in variables will make it messy. Is there a better way to handle this, including validation? TLDR; I created a view to handle register all three different types of users, but my player user has a lot of extra model fields and storing all query params in variables will make it messy. Is there a better way to handle this, including validation? This is my view. class CreateUser(APIView): """ Creates the User. """ def post(self, request): email = request.data.get('email', None).strip() password = request.data.get('password', None).strip() name = request.data.get('name', None).strip() phone = request.data.get('phone', None) kind = request.query_params.get('kind', None).strip() print(kind) serializer = UserSerializer(data={'email': email, 'password':password}) serializer.is_valid(raise_exception=True) try: User.objects.create_user(email=email, password=password) user_obj = User.objects.get(email=email) except: raise ValidationError('User already exists') if kind == 'academy': Academy.objects.create(email=email, name=name, phone=phone, user=user_obj) if kind == 'coach': … -
POST request not working in Ajax jQuery
I have a Django application where I am trying to open index2.html from index.html on button click event. Basically, I am using 2 procedures in order to fulfil this simple task Form with submit button (Button 1) Ajax (Button 2) First one seems to work fine but Ajax is not working. On clicking, Button 2 nothing seems to happen. Can anybody tell me whats going on, any help would be appreciated. index.html <!DOCTYPE html> <html lang="en"> <head> <title>Index</title> </head> <body> <h2>Index</h2> <form method="post" action="/index2/"> <button type="submit" >Button 1</button> <input type="button" id="btn" name="btn" value="Button 2" /> </form> <script src="https://code.jquery.com/jquery-2.2.3.min.js"></script> <script> $("#btn").click(function() { $.ajax({ type: 'POST', url: '/index2/', data: {} }); }); </script> </body> </html> index2.html <!DOCTYPE html> <html lang="en"> <head> <title>Index 2</title> </head> <body> <h2>Index 2</h2> </body> </html> views.py from django.views.decorators.csrf import csrf_exempt from django.shortcuts import render @csrf_exempt def index(request): return render(request, "index.html") @csrf_exempt def index2(request): return render(request, "index2.html") urls.py from django.urls import path from . import views urlpatterns = [ path('index/', views.index, name='index'), path('index2/', views.index2, name='index2'), ] -
How to call a function from models.py with class based views in Django?
I would like to convert a user uploaded .docx file to .html using a function/method I have in models.py. I can do it with function based view with this kind of approach: models.py: class Article(models.Model): main_file = models.FileField(upload_to="files") slug = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) @classmethod def convert_word(self, slug): import pypandoc pypandoc.convert_file('media/files/%s.docx' %slug, 'html', outputfile="media/files/%s.html" %slug) And then I call the convert_word function like this in views.py: def submission_conf_view(request, slug): Article.convert_word(slug) return redirect('submission:article_list') What I would like to do is to call the same function/method but using Djangos Class-based views, but I am having trouble figuring that out... -
How to retry all celery tasks when OperationalErrors occur?
Occasionally when postgres is restarted I get a flood of errors from Celery because of OperationalErrors. Things like: File "/var/www/.virtualenvs/xxx/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) OperationalError: terminating connection due to administrator command SSL connection has been closed unexpectedly Is there a way to just automatically restart any celery tasks that end this way, perhaps with a 30s delay or something? I'm using redis as my broker. I could catch this kind of error in my task, but it'd mean wrapping every database command in a try/except, which would be kind of horrific. -
Can anyone help my find find error in django?
I am new to Django. I have a project which has 2 child apps: "visit" and "main". The error is in base.html file in href for the navigation bar. I am facing No reverse match found error. main/base.html: {%load staticfiles%} <link href="{%static "main/vendor/bootstrap/css/bootstrap.min.css"%}" rel="stylesheet"> <link href="{%static "main/css/small-business.css"%}" rel="stylesheet"> </head> <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top"> <div class="container"> <a class="navbar-brand" href="/home.html">Ekyam</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href='{%url 'main:home'%}'>Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href='{%url 'main: incubators'%}'>Incubators</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Services</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Contact</a> </li> </ul> </div> </div> </nav> {%block content%} {%endblock%} This is the error that I am facing NoReverseMatch at /home.html Reverse for ' incubators' not found. ' incubators' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/home.html Django Version: 1.11.3 Exception Type: NoReverseMatch Exception Value: Reverse for ' incubators' not found. ' incubators' is not a valid view function or pattern name. Exception Location: C:\Users\my dell\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 497 Python Executable: C:\Users\my dell\AppData\Local\Programs\Python\Python36-32\python.exe Python Version: 3.6.1 Python Path: ['C:\\Users\\my … -
Django Query Best Practice
Wondering about some Django querying performance/best practices. It is my understanding that QuerySets are "lazy" as the documentation states and that the three queries below do not run until they are actually evaluated at some point. Is that a correct understanding and is the below snippet a reasonable way to query against the same table for three different filter values against the same field? # General Education general_education_assignments = FTEAssignment.objects.filter( group_name='General Education' ) # Specials specials_assignments = FTEAssignment.objects.filter( group_name='Specials' ) # Dual dual_assignments = FTEAssignment.objects.filter( group_name='Dual Language' ) Even more so what I am wondering about besides if my understanding of the above is correct is if the below is in anyway more efficient (I don't think it will be)? Also, if either the above or below is better stylistically for Django or more 'pythonic'? # Get all assignments then filter fte_assignments = FTEAssignment.objects.all() # General Education general_education_assignments = fte_assignments.filter( group_name='General Education') # Specials specials_assignments = fte_assignments.filter(group_name='Specials') # Dual dual_assignments = fte_assignments.filter(group_name='Dual Language') Thank you! -
Django: null value in column "created_at" violates not-null constraint
I'm trying to add records via the code below: Post.objects.update_or_create( user=user, defaults={ "title": external_post.get('title'), "body": external_post.get('body'), "seo": external_post.get('seo') } ) I've successfully migrated the model but I'm getting the error " null value in column "created_at" violates not-null constraint". created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) -
UnicodeDecodeError relating to Unicode symbols in Django HTML templates
I don't understand why an HTML template containing Unicode symbols provokes the error: Environment: Request Method: GET Request URL: http://localhost:51389/ Django Version: 1.11.10 Python Version: 3.6.3 Installed Applications: ['app', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response 249. response = self._get_response(request) File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\app\views.py" in home 28. 'future_date':datetime(2018, 3, 16).strftime('%d %B %Y'), File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\shortcuts.py" in render 30. content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\template\loader.py" in render_to_string 67. template = get_template(template_name, using=using) File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\template\loader.py" in get_template 21. return engine.get_template(template_name) File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\template\backends\django.py" in get_template 39. return Template(self.engine.get_template(template_name), self) File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\template\engine.py" in get_template 162. template, origin = self.find_template(template_name) File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\template\engine.py" in find_template 136. name, template_dirs=dirs, skip=skip, File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\template\loaders\base.py" in get_template 38. contents = self.get_contents(origin) File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\template\loaders\filesystem.py" in get_contents 29. return fp.read() File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\codecs.py" in decode 321. (result, consumed) = self._buffer_decode(data, self.errors, final) Exception Type: UnicodeDecodeError at / Exception Value: 'utf-8' codec can't decode byte 0xc0 in position 91: invalid start byte The HTML template index.html {% extends "app/layout.html" %} … -
user login not working with django, admin can login fine
I'm creating a django app. I have set up the basic structure and admin creation and management. What I am trying to achieve is that the admin creates the accounts for the users. Then the users login using those credentials and create tickets for issues they're facing. Following are the pieces of code from different files: settings.py INSTALLED_APPS = [ 'ticketsapp.apps.TicketsappConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'appsgenii.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'ticketsapp/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', ], }, }, ] WSGI_APPLICATION = 'appsgenii.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'appsgenii', 'USER': 'root', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '3306', } } # Authentication Backend # AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',) # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] Project urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('auth/', include('django.contrib.auth.urls')), path('tickets/', include('ticketsapp.urls')), ] App urls.py urlpatterns = [ path('success/', views.ticket_created, name='ticket created'), path('create/', views.create_ticket, name='create ticket'), ] views.py from django.contrib.auth import authenticate, login as django_login, … -
Django ProgrammingError [42S02] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server] Invalid object name
I am using Django version 2.0.2. My Django application is connected to MS SQL (connection below). DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'projectcreation', 'HOST': 'Host_name', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', 'dns': 'projectcreation' }, } } So, I am getting the following error when trying to access my Django application: django.db.utils.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid object name 'projectcreation_partner'. (208) (SQLExecDirectW)") I believe that the problem is following: When I created tables (makemigrations+migrate) instead of creating tables that look like this: [projectcreation].[dbo].[projectcreation_partner] it created tables like this [projectcreation].[username].[projectcreation_partner]. So instead putting dbo which I actually expected to see it put my username.. I suppose that when the app tries to connect to db it cannot find it because it is looking for one containing dbo not username.. Of course, I could be wrong.. If you need more information please let me know, any help is greatly appreciated. Note: both db and application are called "projectcreation", "partner" is name of one of the models. -
Angular 5 deployment in Django app with hashing
I have a Django app that has an Angular 5 frontend connected by Django REST. Currently deployment only works with hashing disabled (--output-hashing none), because in uls.py I can only access a copy of index.html ("ang_home.html") in the template folder. ng build --prod --output-path .../backend/src/static/ --watch --output-hashing none --aot=false --env=prod I would now like to change my urls.py so that the newly created index. html in the django static folder is accessed directly. url(r'^.*', TemplateView.as_view(template_name="ang_home.html"), name='home'), The previous current solution is annoying because I would have to copy the index.html code into ang_home.html manually with every change. -
Django Cassandra engine timeout when creating data using models
I have a Django app running in a docker swarm. I'm trying to connect it with cassandra using django-cassandra-engine. Following the guides, I've configured installed apps and connection settings, and running the first step works great (manage.py sync_cassandra). It created the keyspace and my models. However, whenever I try to create data using the models or a raw query, there's simply a timeout while connecting without any other errors. Swarm is running on AWS with a custom VPC. Docker flow proxy is used as reverse proxy for the setup (not that it should affect the connection in any way) I've tried deploying cassandra both as a standalone and as a docker image. I am also able to ping the servers both ways. I am even able to manually connect to the django app container, install cassandra and connect to the cassandra cluster using cqlsh I've been banging my head off for the past few days around this... Has anyone encountered something similar? Any ideas as to where I can start digging Feel free to ask for any information you think may be relevant. -
Django do not validate select multiple
I am trying to disable validation on one manually created form field as per the below. The reason being I am using jquery to move a select option from one select multiple list to another. When the option is moved from available to assigned list and I submit the form I get an error stating that the id of the moved option is not a valid. which I can understand why. however I need for this to be ignored. I've searched and believed I could use clean_XX() but it doesn't seem to work. I still get the validation errors. error: 267 is the value of one of the subnets I moved across from the available list This is my form: class DeviceForm(forms.ModelForm): class Meta: model = DeviceData fields = ['site_data', 'switches', 'hostname', 'template', 'model', 'install_date','ospf_area','snmp_data'] def __init__(self, *args, **kwargs): site_id = kwargs.pop('site_id', None) device_id = kwargs.pop('device_id', None) self.is_add = kwargs.pop("is_add", False) super(DeviceForm, self).__init__(*args, **kwargs) def clean_assigned_subnets(self): assigned_subnets = self.cleaned_data['assigned_subnets'] return assigned_subnets devicesubnet = Subnets.objects.filter(devicesubnets__device_id=device_id) sitesubnet = Subnets.objects.filter(sitesubnets__site_id=site_id) common_subnets = list(set(devicesubnet) & set(sitesubnet)) subnet_id_list = [] for s in common_subnets: subnet_id_list.append(s.id) available_subnet_data = sitesubnet.exclude(id__in=subnet_id_list) assigned_choices = [] devicesubnet_data = DeviceSubnets.objects.filter(device_id=device_id) for choice in devicesubnet_data: assigned_choices.append((choice.subnet.id,choice.subnet.subnet)) self.fields['available_subnets'] = forms.ModelMultipleChoiceField( label='Available Subnets', queryset=available_subnet_data, … -
Annotating a Django queryset through two relations
I have models that represent People and Books, which are joined via a through-model that can indicate their role (e.g. 'Author' or 'Editor'): from django.db import models class Person(models.Model): name = models.CharField() class Book(models.Model): title = models.ChartField() people = models.ManyToManyField('Person', through='BookRole', related_name='books') class BookRole(models.Model): person = models.ForeignKey('Person', related_name='book_roles') book = models.ForeignKey('Book', related_name='roles') role_name = models.CharField() And I have a Reading model that represents an occasion a Book was read: class Reading(models.Model): book = models.ForeignKey('Book') start_date = models.DateField() end_date = models.DateField() I know how to get a list of Persons ordered by the quantity Books associated with them: from django.db.models import Count from .models import Person Person.objects.annotate(num_books=Count('books')) \ .order_by('-num_books') But how can I get a list of Persons ordered by the number of times their Books have been read (i.e. the number of Readings related to their Books)? -
Django channels 2, accessing db in tests
I recently updated my project to Django 2 and channels 2. Right now I am trying to rewrite my tests for chat app. I am facing a problem with tests that depend on django db mark from pytest-django. I tried to create objects in fixtures, setup methods, in test function itself, using async_to_sync on WebsocketCommunicator. However, none of those worked. If I create a user in a fixture and save it correctly gets an id. However, in my consumer Django does not see that User in the database. And treat it like an anonymous user. I have a temporary token which I use to authenticate a user on websocket.connect. @pytest.fixture def room(): room = generate_room() room.save() return room @pytest.fixture def room_with_user(room, normal_user): room.users.add(normal_user) yield room room.users.remove(normal_user) @pytest.fixture def normal_user(): user = generate_user() user.save() return user @pytest.mark.django_db class TestConnect: @pytest.mark.asyncio async def test_get_connected_client(self, path, room_with_user, temp_token): assert get_path(room_with_user.id) == path communicator = QSWebsocketCommunicator(application, path, query_string=get_query_string(temp_token)) connected, subprotocol = await communicator.connect() assert connected await communicator.disconnect() Consumer: class ChatConsumer(JsonWebsocketConsumer): def connect(self): # Called on connection. Either call self.user = self.scope['user'] self.room_id = self.scope['url_route']['kwargs']['room_id'] group = f'room_{self.room_id}' users = list(User.objects.all()) # no users here self.group_name = group if not (self.user is not None and … -
heroku django timestamps not converting to UTC
I've got a Django app (running on Heroku) with a simple form that contains a DateTimeField(): class Response(models.Model): ''' Model serves to record a users response to a given question on a given questionnaire. ''' user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, default=None, db_index=True, ) date = models.DateTimeField( blank=False, auto_now_add=True, db_index=True, help_text=( "Date on which question was answered." ) ) From what I understand, my date field should get populated automatically with the current datetime For DateTimeField: default=timezone.now - from django.utils.timezone.now() -- ref Furthermore, it should be a UTC timestamp If USE_TZ is True, this will be an aware datetime representing the current time in UTC. -- ref My settings.py has TIME_ZONE = 'UTC' USE_TZ = True And I've got some middleware that sets current time zone to CST: from django.utils import timezone import pytz class TimezoneMiddleware(object): def process_request(self, request): if request.user.is_authenticated(): timezone.activate(pytz.timezone('America/Chicago')) else: timezone.deactivate() I have some debugging print statements used right before the form submit [print(now(), localtime(now()), get_current_timezone())] to validate that now() is actually UTC. When I submit my form I'm seeing: 2018-03-06T16:56:23.569311+00:00 app[web.1]: 2018-03-06 16:56:23.569131+00:00 2018-03-06 10:56:23.569145-06:00 America/Chicago however the database stores 2018-03-06 10:56:23 How can I ensure that my submitted timestamps properly get converted to UTC? -
Double nested inputs in django request
So there's this question and it's answered but for PHP. Is it possible to make double nested inputs in html and parse it with Django? I managed to make it work only with one level and request.POST.getlist works fine if you just supply similar names. But if I follow that answer I get empty list. -
Django: Images inside conditional template tags
I'm trying to display an image based on certain conditions in a Django template, but Django doesn't seem to like use of the static tag within a condition. Code as follows: <td> {% if result.threshold == "normal" %} <img src="{% static "face-green-small.jpg" %}" alt="Green"/> {% endif %} {% if result.threshold == "high" or result.threshold == "low" %} <img src="{% static "face-amber-small.jpg" %}" alt="Amber"/> {% endif %} {% if result.thresdholf == "vhigh" or result.threshold == "vlow" %} <img src="{% static "face-red-small.jpg" %}" alt="Red"/> {% endif %}"> </td> The error I'm getting is: Invalid block tag on line 32: 'static', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? I'm sure static is registered, because it's being used earlier in the template. Any guidance on what I'm doing wrong would be appreciated. -
Creating docker secrets with user variables within django
I have django application that uses docker to create sessions using some user inputs. The spec for the services look something like this: { "Name": "dummy_service", "TaskTemplate": { "ContainerSpec": { "Image": REGISTRY_HOST + '/' + DEFAULT_IMAGE + ':latest', "Command": ["start-notebook.sh"], "Env": [LIST OF ENV VARS], "User": "root" }, "RestartPolicy": { "Condition": "on-failure", "Delay": 10000000000, "MaxAttempts": 10 }, }, "Mode": { "Replicated": { "Replicas": 1 } }, "EndpointSpec": { "Ports": [ { "Protocol": "tcp", "TargetPort": 8888 } ] } } I would like to create a secret for any variables that the user wants so that if somebody gets hold of my docker credentials they cannot view a users secrets by simply looking at the environment variables of their session. The user would give these to us through a POST request using a password form input. Their secret would be in a variable contained in something like this requests.POST['some_private_name'] in the back end of the application. Is this possible? -
Editing fields in Django admin when "Save as New"
I'm trying to blank some fields when a user in the Django admin clicks "Save as New", but it doesn't seem to be working. Ar first I was just calling obj.save(), but it complained their was no request object, so I passed in the request object. Now the new item saves as expected, but if I don't click "Save as New", and just click "Save", I get an IntegrityError: "duplicate key value violates unique constraint". Leading me to believe it's trying to save the existing object with the same pk? Here is the relevant code that lives in my admin.py: def save_model(self, request, obj, form, change): if '_saveasnew' in request.POST: original_pk = resolve(request.path).args[0] original_obj = obj._meta.concrete_model.objects.get(id=original_pk) for prop, value in vars(original_obj).items(): print(prop) if prop == 'submitter_email_address': setattr(obj, prop, None) if prop == 'submitted_by_id': setattr(obj, prop, None) if isinstance(getattr(original_obj, prop), FieldFile): setattr(obj, prop, getattr(original_obj, prop)) obj.save(request) I got the relevant code from this question and edited it to what I need: Django "Save as new" and keep Image fields -
django-s3-storage: Use protected and public files in one project (AWS_S3_BUCKET_AUTH)
I`m using django-s3-storage. I want to use files with and without authentication in one project. So I created two storage classes and set AWS_S3_BUCKET_AUTH to True or false after initial setup from django_s3_storage.storage import S3Storage class S3StoragePublic(S3Storage): def _setup(self): super()._setup() self.settings.AWS_S3_BUCKET_AUTH = False class S3StorageProtected(S3Storage): def _setup(self): super()._setup() self.settings.AWS_S3_BUCKET_AUTH = True Is there a better way of doing this? Or is this how it should be done? -
Django: Make user email required
For my application the email field of a User should be required. That's not the case for the default User model. So I thought it would make sense to create a custom user model as described in the docs: If you’re starting a new project, it’s highly recommended to set up a custom user model, even if the default User model is sufficient for you. This model behaves identically to the default user model, but you’ll be able to customize it in the future if the need arises: from django.contrib.auth.models import AbstractUser class User(AbstractUser): email = models.EmailField(_('email address'), blank=False) However, I am not sure if that's the correct way to achieve this. The reason is that here the Django docs say: Abstract base classes are useful when you want to put some common information into a number of other models. You write your base class and put abstract=True in the Meta class. This model will then not be used to create any database table. Instead, when it is used as a base class for other models, its fields will be added to those of the child class. It is an error to have fields in the abstract base class with … -
Django: Automatically selecting related UseRProfile when retrieving User model
When showing {{ user }} in a Django template, the default behavior is to show the username, i.e. user.username. I'm changing this to show the user's initials instead, which are stored in a separate (OneToOneField) UserProfile model. So in customsignup/models.py I've overridden the __unicode__ function successfully, with the desired result: # __unicode__-function overridden. def show_userprofile_initials(self): return self.userprofile.initials User.__unicode__ = show_userprofile_initials But of course, the database is hit again because it needs to independently select the UserProfile model every time a user object is asked to show itself as a string. So even though this works, it escalates the number of database hits quite a bit. What I'm trying to do is modify the manager of the User model after it has been defined by the Django library. So I'm in no control over the User model definition itself. I'm attempting to override an existing model manager. So I've tried overriding the objects member of the User model in the same way that I overrode the __unicode__ function, like so: # A model manager for automatically selecting the related userprofile-table # when selecting from user-table. class UserManager(models.Manager): def get_queryset(self): # Testing indicates that code here will NOT run. return super(UserManager, self).get_queryset().select_related('userprofile') … -
Add Properties To Class At Runtime
Is it possible to add a property to an instance of a class at runtime? This is for Django and it'd model objects but it'd be a great tool to have if this would work on any python class outside of Django. e.g. class person(models.Model) firstname=models.CharField(max_length=100) lastname=models.CharField(max_length=100) def main(): p = person() p.fisrtsname="Firsty" p.lastname="Lasty" p.addnewproperty(newtemporaryproperty) p.newtemporaryproperty="This is a new temporary property" when i use person.newtemporaryproperty=property("") i get a "Can't set attribute error" when trying to add a value to it. I may be using it wrong.