Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ModelAdmin: how to ask password using two secret fields?
This is my custom user model: class CustomUser(AbstractUser): created = models.DateTimeField(auto_now_add=True) username = models.CharField(max_length=100, unique=True) email = models.EmailField(max_length=200, unique=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='%(class)s_company') Since there is a foreign key field, I have created a custom ModelAdmin: class CustomUserAdmin(admin.ModelAdmin): exclude = ('groups', 'user_permissions', 'date_joined') list_display = ('username', 'email', 'company') Otherwise it works fine, but there is only one, clear-text password field shown. How can I modify it so that Django Admin would ask the password using the default two field approach? -
Djongo issue with "id" field and existing mongo db
I'm trying to use django+djongo and an already existing mondo database. The collection I need to read is like this: { "_id" : ObjectId("5dde69143f664504b7149fed"), "name" : "example_123456", "hash" : { "md5" : "d9feb4e791077aeba4e946696a2fbf8a", "sha256" : "72f7a877db57e43580495d0ac05615138a73e3f8507781188d4469b1bf09389b", "sha1" : "38e600408e141389d0bb0baaf6a2e0594411a34d" }, } So in my models.py I've created these two models: class Hash(models.Model): md5 = models.TextField() sha256 = models.TextField() sha1 = models.TextField() class Meta: db_table = "hash" abstract = True class ExampleCollection(models.Model): name = models.TextField() hash = models.EmbeddedModelField( model_container=Hash ) class Meta: db_table = "example_collection" Now the problem is that when I try to read something from this collection (for example even a ExampleCollection.objects.all()), I get a MigrationError: Exception Type: MigrationError Exception Value: id I've noticed (by creating a "test" model) that django/djongo automatically add an "id" field in my models (that acts as a primary key), but since it doesn't exist in this collection, I get this exception. -
How to run two django apps in same server with different dynamic DJANGO_SETTINGS_MODULE env variables
I'm running two django application in same server, server setup and multi settings file are created. But i have DJANGO_SETTINGS_MODULE env variable as dynamic, i need to set two different values. If i change DJANGO_SETTINGS_MODULE variable name to something else, i'm getting error. Can anyone suggest some solution for this problem. -
Python - Create multiple user types and email as the username field in Django 2
I'm working on a project using Python(3.7) and Django(2.2) in which I have to implement multiple types of users as: Personal Account - below 18 Personal Account - above 18 Parent Account Coach Account Admin along with that, I also need to use email as the username field for login/authentication. The strategy I'm trying to use is to build a custom base model as User inherited from AbstractBaseUser and also created a custom User Manager to make the email as username but it's not working. Here's my complete model code: class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email=None, password=None, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): user = self._create_user(email, password, True, True, **extra_fields) user.save(using=self._db) return user def generate_cid(): customer_number = "".join([random.choice(string.digits) for i in range(10)]) return customer_number class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) is_personal_above_18 = models.BooleanField(default=False) is_personal_below_18 = models.BooleanField(default=False) is_parent = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD … -
How to stop User Agent Stylesheet from overriding my CSS
I have the following CSS .imagetable{ border-collapse:collapse; width:100%; height:100%; } and HTML: <table class="imagetable"> <tr> <th><img src="{% static "images/myimage1" %}"></th> <th><img src="{% static "images/myimage2" %}"></th> </tr> <tr> <td><a href='myurl'><button>button1</button></a></td> <td><a href='myurl'><button>button2</button></a></td> </tr> </table> But whenever I run this and look in Google Chrome F12 I see not my own CSS but this: table { user agent stylesheet display: table; border-collapse: separate; border-spacing: 2px; border-color: grey; Annoyingly my CSS works everywhere else other than this table. Any ideas? -
How to Install Pillow on Openshift
I'm trying to deploy my django web application on OpenShift. When I try to deploy it I get this error: I have no idea how I can access the terminal in the openshift to install pip. -
Start 'python manage.py runserver' of django within jupyter notebook
I would like to create small application in Django. However, main requirement for this application is to be started within jupyter notebook, as every user will have such application locally. Plotly dash (from which I would like to rewrite this app) allows app.runserver() inside jupyter cell, which afterwards starts the app. However this is not available for django in the jupyter notebook. I could do !python manage.py runserver This spawns server correctly. But this server is not 'killable' using the interrupt button inside jupyter notebook - which is important feature of this approach. Same applies for os.system or subprocess.Popen. I tried also approach from this question: Django runserver from Python script Which does not work in the jupyter notebook unfortunately. This raises zmq.error.ZMQError: Address in use Is there any other approach which I could try? -
Run specific function before executing any code in the view
I haven't worked too much with Django. Let's say I have three views. The url patterns that these views are mapped to all start with string Y. Suppose I want to run specific function X before running code that the views contain. Is there a way to run function X by adding it somewhere only once instead of adding the function call to to the beginning of each of these views separately? Would middleware be the recommended way to do this? -
What is proper way to store data in DateTimeField field
I have a model Fixture Class Fixture(models.Model): event_timestamp = models.DateTimeField(null=True) I have piece of json data for item in piece_json: event_timestamp = item["event_date"] Where in item["event_timestamp"] the following data 1572567600 While i am trying to create object from this model fixture = Fixture.objects.create(event_timestamp= event_timestamp) I got the following error match = datetime_re.match(value) TypeError: expected string or bytes-like object After this error i tried to wrap event_timestamp variable in built-in str() function fixture = Fixture.objects.create(event_timestamp= str(event_timestamp)) After it i got error django.core.exceptions.ValidationError: ["'1572651000' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."] -
Loggedin pages after authintification
I am learning django and make mini project for learning pupose and as example took kidgarden. I have a directorry gun and with two apps inside it accounts and equity apps. I want only registered users to be able to see equity app which requires to get information and after clicking ok button brings a user to another page that bring users info. In accounts i have templates with login signup htmls like following.This section works fine without any problem. Then i created equity app. where i have forms.py: from django import forms from .models import Child class ChildForm(forms.ModelForm): name = forms.CharField(max_length=150, label='',widget= forms.TextInput (attrs={'placeholder':'Ticker'})) class Meta: model = Child fields = ('name',) models.py : from django.db import models from django.contrib import auth class Child(models.Model): name = models.CharField(max_length=150, blank=True) and views.py : from django.shortcuts import render from .forms import ChildForm def home(request): stock = ChildForm() if request.method == "POST": stock = ChildForm(request.POST) if stock.is_valid(): data = stock.save(commit=True) name = data.name context={ 'name':name, } else: stock = ChildForm() return render(request,'equity/search.html',{'stock':stock}) return render(request,'equity/analysis.html',context) return render(request,'equity/search.html',{'stock':stock) in gun /setting.py i inserted this info LOGIN_REDIRECT_URL = 'kids' so if a user is logged in it bring them to kid.html page in main directiory (gun) … -
How to pass class-based view data to django formset
I have a formset that is rendered using a class-based view. I get a 404 error when project_id = kwargs.pop('project_id',None) in the def get_context_data function below. The formset doesn't render at all when project_id = kwargs.pop('project_id',None) in the def __init__(self,*args,**kwargs) function below. project_id is the auto-generated id in the ProjectDetails model. How can get project_id to be passed to the formset? models.py class ProjectDetails(models.Model): project_name = models.CharField(max_length = 50,blank = False) client = models.CharField(max_length = 200,blank = False) class ProjectFinance(models.Model): project_name = models.ForeignKey(ProjectDetails,on_delete = models.CASCADE, null = True,blank=False) finance_item = models.CharField(max_length = 50,null=True,blank=False) forms.py class FianceForm(forms.ModelForm): def __init__(self,*args,**kwargs): project_id = kwargs.pop('project_id',None) super(FianceForm,self).__init__(*args,**kwargs) class Meta: model = ProjectFinance fields = '__all__' FinanceFormSet= inlineformset_factory(ProjectDetails, ProjectFinance, form=FianceForm, fields='__all__',extra=2) views.py class FinanceView(CreateView): template_name = "project.html" model = ProjectFinance form_class = FianceForm def get_form_kwargs(self,*args, **kwargs): form_kwargs = super(FinanceView, self).get_form_kwargs(*args, **kwargs) form_kwargs['project_id'] = self.kwargs.get('project_id') return form_kwargs def get_context_data(self,**kwargs): project_id = kwargs.pop('project_id',None) project = get_object_or_404(ProjectDetails,id=project_id) formset = FinanceFormSet(instance=project) context = super(FinanceView, self).get_context_data(**kwargs) context['project'] = project return context Thanks. -
Django - 'bool' object is not callable
I have a UserProfile Model that looks like this: class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile',on_delete=models.CASCADE) needhelp = models.BooleanField(default=True) def __str__(self): return self.user.username def get_absolute_url(self): return ('user:help', (), {'id': self.id}) Im working on a visual guide for a website and for a start I made a modal that asks the user if he needs help when he logs in. If he clicks "no" I want to change the needhelp bool to False and hide the modal. If he clicks "yes" I want to change the needhelp bool to True and start the guide. This is how far I got: class HelpToggle(RedirectView): def get_redirect_url(self, pk, *args, **kwargs): obj = get_object_or_404(UserProfile, pk=pk) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated(): if user in obj.needhelp.all(): user.needhelp = False else: user.needhelp = True return url_ url(r'^help/(?P<pk>\d+)/$', HelpToggle.as_view(),name="help") But when I go to the url, I get 'bool' object is not callable Thank you for any help -
API's of vCenter
We are using API's in our product to talk at vCenter. We are a quit new development team and want to update vCenter 6.5 to 6.7. I tried to find if this will have consequences for our code base in the form of deprecation or something. But I cant find anything regarding to this. Now this seem to mean that it should have no consequences. But before updating production I want to be sure. Does anyone has experience with this? -
Is there a way to programatically find which account has been locked out in django-axes?
I would like to check which accounts have been locked out in django-axes. I know this can be done in admin site, but can I get this in a view.py as well? -
How can i get the id of each record in ListApiView in DRF
I am facing an issue while getting the promary_ket(id) of record ListApiView in the Django rest framework. I am also implementing the Custom pagination. Here is my ListApiView Code: class TestList(ListAPIView): permission_classes = (IsAuthenticated, ) serializer_class = AllTestListSerializer pagination_class = CustomPagination def get_queryset(self): return TakeTestDetails.objects.filter(user=self.request.user).order_by('date', 'time').all() And here is my CustomPagination code: class CustomPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): response_data = { 'status': '200', 'message': 'Success', 'count': self.page.paginator.count, 'next': self.get_next_link(), 'previous': self.get_previous_link(), } if data: new_cycle_data = [] for row in data: row_dict = dict(row) print(row) cycle_id = row_dict['cycle_id'] cycle = TestCycle.objects.get(id=cycle_id) cycle_no = cycle.cycle_no cycle_start_date = cycle.cycle_start_date cycle_end_date = cycle.cycle_end_date cycle_start_date = change_date_format(cycle_start_date) cycle_end_date = change_date_format(cycle_end_date) test_date = change_date_format(row_dict['date']) row_dict['date'] = test_date row_dict['cycle_no'] = cycle_no row_dict['cycle_start_date'] = cycle_start_date row_dict['cycle_end_date'] = cycle_end_date new_cycle_data.append(row_dict) response_data['data'] = new_cycle_data else: return Response({ 'status': '404', 'message': "You haven't performed any test yet", 'count': self.page.paginator.count, 'next': self.get_next_link(), 'previous': self.get_previous_link(), 'data': data }) return Response(response_data) Now what i want is also to get the primary_key/id of each row/record. But it's not giving me the id in data. How can i get the id? Thanks in advance -
Django: How to keep non-PII from removed users under GDPR
I'm using Django to build a B2B SaaS hobby project, where each company (tenant) can have many users and, eventually, remove them. It's important to keep the reason why a user was removed. The straightfoward way for this to be solved would be to turn is_active to False and add a reason_for_removal field on the User model. Then make sure is_active is indexed (is it by default in Django?) and all querysets are appropriately filtered. However, in a GDPR world, is this the right way to do it? Does it make sense to create a separate model called RemovedUser just with the user and reason_for_removal fields (and no other Personal Identifiable Information) and delete the original user instance? -
python requests taking 100% of cpu
One of our API servers has an issue with CPU usage. API is written in python and configured in ubuntu aws EC2 instance. This application uses Python 2.7 and Django 1. This can be accessed through port 80 by proxy passing. Sometimes we are getting 499 requests in our logs that time $htop value shows 100% cpu usage in the server. Only python requers are running in this server. But in aws cloudwatch monitoring it is not. only 40% to 50%. PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 23086 root 20 0 815776 96056 12792 S 100 4.7 2:43.12 python 24041 root 20 0 292756 92820 12696 S 8.0 4.5 0:33.73 python 24072 root 20 0 815656 95696 12792 S 5.3 4.7 0:28.27 python Please help TIA -
Django formtools how to store form data between logout/login cycles
I am using django-formtools to split a long form in parts. This is working fine. However, I want users to be able to start filling the form going until let's say step 5 out of 9, then logout and login again and continue filling the form from step 5 on. I can do this with cookies but, if user A starts filling the form then logs out and then user B logs in, user B can see the data of user A if user B chooses to continue filling the form. This happens if users A and B use the same computer and web browser. This, of course, cannot happens. If I use sessions instead of cookies then when a user logs out it is not possible to continue filling the form from step 5 on because the session is flushed and the data deleted. So I guess that sessions will not help me here. In order to continue filling the form from step 5 on I override the get method of django-formtools.WizardView: def get(self, request, *args, **kwargs): """ To allow resume editing of a session storaged submissions """ if self.continue_fill == True: try: return self.render(self.get_form()) except Exception as e: … -
How to create multiple users in Django without letting them access each other's data
I am not quite sure if the title I used for my question is the right one. And if this has previously been answered, someone should please point me to it as I have tried so much to find that out but its been futile. I am currently working on a basic HR system which can be used by different companies. In a much clearer way, how can I create an online system whereby multiple companies can manage their employees online without having access to each other's data? And without even knowing that they use the same system? A perfect example of this kind of system is "Zoho People". -
i want to try to implement activation hash in Django using python 3.x
import random import base64 import hmac import hashlib short_hash = hashlib.sha256(str(random.getrandbits(256)).encode('utf-8')).hexdigest() username='hp' activation_key = hashlib.sha256(short_hash + username).encode('utf-8').hexdigest() short_hash = hashlib.sha256(str(random.getrandbits(256)).encode('utf-8')).hexdigest()[:5] username="hp" activation_key = hashlib.sha256(short_hash + username).hexdigest() Traceback (most recent call last): File "", line 1, in TypeError: Unicode-objects must be encoded before hashing -
Django Rest API - custom layout for xml Render
Im having trouble formatting XML output for a specific render. I need to have the XML format outputted like the below sample: <mappings> <mapping> <subnet from="192.168.1.1" mask="255.255.255.0"/> <location country="United States" region="California" city="San Francisco"/> </mapping> <default country="United States" region="California" city="San Francisco"/> </mappings> Ive tried two methods thus far both have failed, how can I achieve this xml output? Thanks First I create json fields in serialiser and create the json dict manually for subnet and location like below Serializer class SerializerDataGeoMapping(serializers.Serializer): subnet = serializers.JSONField() location = serializers.JSONField() View class DataGeoMapping(generics.ListAPIView): permission_classes = (IsAuthenticated,) serializer_class = SerializerDataGeoMapping paginate_by = 20 def get_queryset(self): queryset = SiteSupernet.objects.filter(site__is_live=True, subnet_type__subnet_type__icontains='site aggregate' ).select_related( 'site', 'site_type', 'subnet', 'subnet__subnet_type' ).values( 'site_id', 'mask', 'subnet', location=F('site__location'), country=F('site__country'), region=F('site__region'), city=F('site__town'), location_type=F('site__site_type__site_type'), ) for supernet in queryset: supernet['subnet'] = {"from" : supernet['subnet'], "mask" : supernet['mask']} supernet['location'] = {"country" : supernet['country'], "region" : supernet['region'], "city" : supernet['city']} output <root> <list-item> <subnet> <from>10.1.1.0</from> <mask>/24</mask> </subnet> <location> <country/> <region/> <city>Aberdeen</city> </location> </list-item> <list-item> <subnet> <from>10.3.3.0</from> <mask>/24</mask> </subnet> <location> <country/> <region/> <city>Edinburgh</city> </location> </list-item> ... Second I tried creating a full dictionary and using that as json field serializer class SerializerDataGeoMapping(serializers.Serializer): mappings = serializers.JSONField() default = serializers.JSONField() view class DataGeoMapping(generics.ListAPIView): permission_classes = (IsAuthenticated,) serializer_class = SerializerDataGeoMapping paginate_by … -
Dynamic select box in Django template without using JavaScript
I have a template page which displays a database table. The implementation I would like here is to have a set of select boxes to set filter parameters, then have a button to apply the selected filters. The problem here is some of my categories are a bit out of control with the amount of options available. So I would like to be able to select an option from selectbox1 and depending on the choice, the options in selectbox2 are filtered down by eliminating any null combinations. I reckon this is a fairly easily solved problem if I included some JavaScript in my solution but I want to know if there is a relatively tidy method of doing this purely within Django Views + Templates. -
Django - JupyterHub - OAuth2 - Jupyter Notebook Interaction
I have a rather complex requirement. Here is what I hope to achieve. A Django backend that shall host all kinds of information about the user of a service. User will log into Django backend and can send some instructions or query to the service. OR The user can access a Jupyter notebook from within the Django app and use an API to communicate the query to the service. This might be a preferred mode of accessing the service since the results are something that need further analysis using Python. Whether it is a query sent using a form within the Django service OR whether query is sent using a Python API from within a notebook, it is sent to the same web URL/endpoint so that the query can be logged etc. This URL is protected by authentication. Now, what I have managed to do so far is the following: Configure Django to provide OAuth based authentication. Configure JupyterHub to communicate with Django and start a user specific notebook server. I have even figured out how to use Jupyter Notebook Extensions to pre-populate any new notebook with the relevant code and comments that will help the user use our API. … -
Integrate sweatalert2 in django as python package
How to ingrate sweat-alert in a django application as a python package ( installing via pip) and pass it into views -
Unable to get the third-level dropdown list options using django modelform and ajax
I'm trying to create a chained dropdown-list for Indian administrative levels (State --> District --> City) My Model and ModelForm is like this: models.py: # I've pre-loaded using foreignkeys from models State, District and City in another app in the same project folder class LocationChainForIndia(Model): state = ForeignKey(State, on_delete=CASCADE) district = ForeignKey(District, on_delete=CASCADE) city = ForeignKey(City, on_delete=CASCADE) --------------------------- forms.py: class LocationChainIndiaForm(ModelForm): class Meta: model = LocationChainForIndia fields = ['state', 'district', 'city'] def __init__(self, *args, **kwargs): super(LocationChainIndiaForm, self).__init__(*args, **kwargs) self.fields['state'].queryset = State.objects.all().order_by('name') self.fields['district'].queryset = District.objects.none() self.fields['city'].queryset = City.objects.none() if 'state' in self.data: state_id = int(self.data.get('state')) self.fields['district'].queryset = District.objects.filter(state_id=state_id).order_by('name') elif self.instance.pk: self.fields['district'].queryset = self.instance.state.district_set.order_by('name') if 'district' in self.data: district_id = int(self.data.get('district')) self.fields['city'].queryset = City.objects.filter(district_id=district_id).order_by('name') elif self.instance.pk: self.fields['city'].queryset = self.instance.district.city_set.order_by('name') Views are written as: def request_india_data(request): if request.method == "POST": form = LocationChainIndiaForm(request.POST) if form.is_valid(): form.save(commit=False) state = form.cleaned_data.get('state') district = form.cleaned_data.get('district') city = form.cleaned_data.get('city') pprint({'state': state, 'district': district, 'city': city}) else: form = LocationChainIndiaForm() context = {'form': form} return render(request, 'india/request_india_data.html', context=context) def districts_for_state(request): state_id = request.GET.get('state') districts = District.objects.filter(state_id=state_id).order_by('name') context = {'districts': districts} return render(request, 'india/districts_for_state.html', context=context) def cities_for_district(request): district_id = request.GET.get('district') cities = City.objects.filter(district_id=district_id).order_by('name') context = {'cities': cities} return render(request, 'india/cities_for_district.html', context=context) HTML templates for districts_for_state, and cities_for_district are in …