Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am trying to inser dictionary in database from django how to do this task at onclick event
I need code example to insert data from data dictionary in data base from django please help. I am stuck in this -
Django Admin formfield_for_foreignkey generic owner filter
I want to use formfield_for_foreignkey method to filter owned objects in selection list. There are many so i wanted to use a generic way. Also show all if super user. This is what i found in the documentation. class OwnerFilteredAdmin(admin.ModelAdmin): def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "company": kwargs["queryset"] = Company.objects.all() if request.user.is_superuser is not True: kwargs["queryset"] = kwargs["queryset"].filter(client=request.user.userprofile.client) return super().formfield_for_manytomany(db_field, request, **kwargs) return super().formfield_for_manytomany(db_field, request, **kwargs) class FooAdmin(OwnerFilteredAdmin): # configs In this case, only work for Company model. ¿Any ideas? -
ListView without queryset
I am trying to increase performance in a view that has to render a list of events. Currently, I populate a database table on the fly and with a generic list view I show it. However, since it has to do a dababase bulk insert it takes few seconds. I wonder if there is a way -since I have the information in a list in memory- to use the ListView not having to create the database table and the respective queryset. I mean to render the LisView directly from the list structure that I have in memory. Is it possible ? I would appreciate if anyone can give me a hand with this since I have not found any information in google regarding this issue. Best regards. -
Django makemigrations check generates same migration
I created a new model that has two foreign keys to existing models, nothing complex, ran makemigrations, and did a git push. After pushing, my Jenkins build failed immediately on account of a check migrations detecting more were needed. I ran makemigrations --check and sure enough a new migration appeared altering a field to my new model that did nothing but set it to what was already in the model. Running the command multiple times results in the same migration being generated every single time. At a loss as to what is triggering this behavior. I tried renaming the field and the same issue persists. Models: class CustomReference(BaseModelHardDelete): reference = models.CharField(max_length=constants.CHARFIELD_SIZE_256, null=False, blank=False) company_preferences = models.ForeignKey(CompanyPreferences, null=False, on_delete=models.CASCADE, related_name='custom_references') class Meta: ordering = ('created_at',) unique_together = ('reference', 'company_preferences',) class CustomReferenceValue(BaseModelHardDelete): custom_reference = models.ForeignKey('companies.CustomReference', null=False, on_delete=models.CASCADE) shipment = models.ForeignKey(Shipment, null=False, on_delete=models.CASCADE, related_name='custom_reference_values') value = models.TextField(blank=True, null=True) class Meta: ordering = ('created_at',) unique_together = ('custom_reference', 'shipment',) Migrations 1: class Migration(migrations.Migration): dependencies = [ ('companies', '0113_auto_20190730_1544'), ('shipments', '0191_merge_20190729_2140'), ] operations = [ migrations.CreateModel( name='CustomReferenceValue', fields=[ ('created_at', common.fields.CreatedField(default=django.utils.timezone.now, editable=False)), ('updated_at', common.fields.LastModifiedField(default=django.utils.timezone.now, editable=False)), ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='ID')), ('value', models.TextField(blank=True, null=True)), ('custom_reference', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='companies.CustomReference')), ('shipment', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='custom_reference_values', to='shipments.Shipment')), ], options={ 'ordering': ('created_at',), }, ), … -
Can django.forms.DateInput be customized to accept a range produced by daterangepicker?
I am using django-filter and django-tables2 to generate a report built from the Django framework. I have a filter that filters dates, and I'm trying to add the daterangepicker widget to the view. It provides dates in a range format 'MM/DD/YYYY - MM/DD/YYYY'. I am using forms.DateInput in my filter and it is complaining about format being invalid. How can I customize the Filter to accept the date range and perform the filtering based on the range? I've tried looking through the FilterView source code to see if I can tell how to make this work. I've been looking around for ways to integrate daterangepicker into this django-filter framework, but I'm having a hard time. I've tried using django_filters.DateFilter() but it only expects one date. Here is the view: from django_tables2.views import SingleTableMixin from django_filters.views import FilterView from .models import WorkHours from .tables import WorkHoursTable from .filters import WorkHoursFilter class FilteredWorkHoursView(SingleTableMixin, FilterView): table_class = WorkHoursTable model = WorkHours template_name = 'hub/multi_day_report.html' filterset_class = WorkHoursFilter the filter: import django_filters from django import forms from .models import WorkHours class WorkHoursFilter(django_filters.FilterSet): date_worked = django_filters.DateFromToRangeFilter( widget=forms.DateInput( attrs={ 'id': 'datepicker' } ) ) class Meta: model = WorkHours fields = [ 'date_worked', 'employee', 'job_number', ] … -
How to properly authenticate with both username and email with oauth2 toolkit
I would like to be able to login either with username or email using oauth2 toolkit - when I log with an email, I want to pass email parameter, not username to distinguish them. This is what I came up with from django.contrib.auth import get_user_model from oauth2_provider import views class TokenView(views.TokenView): def create_token_response(self, request): try: email = request.GET.copy().pop('email')[0] self.set_username_from_email(request, email) except (KeyError, get_user_model().DoesNotExist): pass return super().create_token_response(request) @staticmethod def set_username_from_email(request, email): """ Parameters used for request are for some reason stored in request.META['QUERY_STRING'] which is just url query string, we need to parse it, and replace email with username """ a = [] for pair in request.META['QUERY_STRING'].split("&"): username = get_user_model().objects.get(email=email).username items = pair.split('=') if items[0] == 'email': items[1] = username items[0] = "username" a.append('='.join(items)) request.META['QUERY_STRING'] = "&".join(a) This works, but it feels really ugly to alter the parameters like this. Is there a better way how to do it? Perhaps extend something else then TokenView? I was inspired by https://stackoverflow.com/a/44226177/4710968 but the request.POST attribute is empty and adding something to it changed nothing. I am using Django 2.1.7 and oauth2_toolkit 1.2.0 -
Paginating without model in django
this is my first post ever related to programming therefore please forgive if it is a bit silly. I'm making a website that will aggregate real estate data from some classified ads websites. I've already managed to write simple scrapers that update the website's database and now I wanted to make the actual web app using Django. The website would take data from users that can search the real estate database according to their criteria (already set up a django form and provisionary interface for that.) I'm a newbie and don't know a lot about django therefore I've been trying to use a simple function-based-view to process queries and display results based on user's choices. I've got completely stuck on pagination - as some queries might have thousands of results it's absolutely essential to implement it but django paginator seems to only be working with a predefined django model. I've tried using django paginator to no avail as it appears to require defined models. I've tried the paginate library but there is no real documentation or examples so I couldn't make it work https://pypi.org/project/paginate/ I'm thinking of writing the pagination script by myself but it will take me a very … -
updating web site witout deleting database
I am using docker for my django project with ubuntu server. When I was chaning something always I am removing my docker images and building it again and my database also removed and I have to be populate my database again. I am trying these steps: pulling new code from git docker stop $(docker ps -aq) docker rm $(docker ps -aq) docker-compose up --build -d and as I mentioned my database also removed. I have tried without stopping and removing. Only docker-compose up --build -d but it did not worked. Also I tried docker-compose restart it also not worked. What I have to be tried. Please note that I am new in docker and django. Its my first project. -
How to add section titles/headers in between form fields in django?
I'm trying to get my form to look like this: except with empty checkboxes (could't find icons without a check) Drive and Woods ☑ Driver ☑ 3-Wood ☑ 5-Wood Irons ☑ 1-Iron ☑ 2-Iron ☑ 3-Iron ☑ 4-Iron ☑ 5-Iron Wedges ☑ SW ☑ PW I'm using Crispy Forms by the way. I can only get the checkboxes going down without the headers and without spaces they look like this right now: ☑ Driver ☑ 3-Wood ☑ 5-Wood ☑ 1-Iron ☑ 2-Iron ☑ 3-Iron ☑ 4-Iron ☑ 5-Iron etc... my forms.py looks like this right now class inputForms(forms.Form): Driver = forms.BooleanField(required=False) _3_wood = forms.BooleanField(required=False) _5_wood = forms.BooleanField(required=False) Hybrid = forms.BooleanField(required=False) _1_iron = forms.BooleanField(required=False) _2_iron = forms.BooleanField(required=False) _3_iron = forms.BooleanField(required=False) _4_iron = forms.BooleanField(required=False) _5_iron = forms.BooleanField(required=False) _6_iron = forms.BooleanField(required=False) _7_iron = forms.BooleanField(required=False) _8_iron = forms.BooleanField(required=False) _9_iron = forms.BooleanField(required=False) SW = forms.BooleanField(required=False) PW = forms.BooleanField(required=False) my views.py looksl like this: def inputsuser(request): forms = inputForms() return render(request, 'users/inputsuser.html', {'form': forms}) my template form looks like this: <form method="POST" style="margin-top:50px;" > {% csrf_token %} {{ form|crispy }} <div class="row"> <button class="btn green white-text">Submit</button> </div> </form> Trying to get each group of checkboxes separated by a title or header -
Is there any way I can relate multiple users(different type) from my custom user model to my other models?
I am trying to make to take advantage of django's authentication system, but having difficult time with user models I tried to extend my user model using these tutorial: https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html. It was easy to follow and understandable until I got stuck while relating my newly extended user model to my existing models. My model has fields that relate to two types of my users at the same time, and I am using tuple within the field to differentiate my users. I searched for answers but the solutions are generic and I keep getting clash error messages when I tried to migrate. class User(AbstractUser): USER_TYPE_CHOICES = ( (1, 'Registral'), (2, 'Teacher'), (3, 'Parent'), (4, 'Admin'),) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES) telephone = models.CharField(max_length = 50, null=True) is_active = models.BooleanField(default=False) class Registral(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,primary_key=True) Admin_created=models.ForeignKey(get_user_model(), on_delete=models.CASCADE) class Parent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) parent_of = models.ForeignKey('Student',on_delete=models.CASCADE) class Student(models.Model): first_name = models.CharField(max_length = 50, null=True) last_name = models.CharField(max_length = 50, null=True) grade = models.IntegerField() member_of = models.ForeignKey('communicate.Class', on_delete=models.CASCADE) contact_parent = models.ForeignKey('Parent', on_delete=models.CASCADE) registered_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) How to migrate without error -
LDAP connect failed: socket connection error while opening: [Errno 111]
I recently deployed my Django project on a Linux Ubuntu server using LDAP backend for user authentication. Everything was working fine, but now I am receiving the error: LDAP connect failed: socket connection error while opening: [Errno 111] Connection refused when I attempt to login. The only real change I have made since the last working version was that I switched to using Google DNS (8.8.8.8). Would this cause any issues? Additionally, the LDAP backend works fine on the localhost. -
Multiple nested inheritance in templates
I have 4 models that need to be presented by chain inheritance each other. I'll show first two models to show what problem is - Parent and Child: I've tried to extend a parent template from base.html - it's works. But next, when i extend a child.html template from parent.html it outputs nothing. models.py: class Parent(models.Model): title = models.CharField( max_length=150, ) class Child(models.Model): title = models.CharField( max_length=150, ) parents = models.ManyToManyField( Parent, blank=True ) views.py: class ParentListView(ListView): model = Parent template_name = 'parent_list.html' context_object_name = 'parent_objects_list' class ChildListView(ListView): model = Child template_name = 'child_list.html' context_object_name = 'child_objects_list' parent_list.html: {% extends '_base.html' %} {% block title %}Parents_list{% endblock title %} {% block content %} {% for parent in parent_objects_list %} <div class="card"> <div class="card-header"> <span class="font-weight-bold">{{ parent.title }}</span> </div> </div> {% endfor %} {% endblock content %} shows parent list right. child_list.html {% extends 'parent_list.html' %} {% block title %}Childs_list{% endblock title %} {% block childs_block %} {% for child in child_objects_list %} <div class="card"> <div class="card-header"> <span class="font-weight-bold">{{ child.title }}</span> </div> </div> {% endfor %} {% endblock childs_block %} that returns empty. I think i need to pass an argument with key into childs block to filter childs of certain … -
"Authentication credentials were not provided." and terminal says Unauthorized: /api/auth/login/ django-rest-framework
I am using postman. when i do a post request to api/auth/login/, I get a 401 response "Authentication credentials were not provided.". In terminal, I do not get my print statement inside of the login serializer, I get Unauthorized: /api/auth/login/. This is my code: settings.py #just including the rest framework one here REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_AUTHENTICATION_CLASSES': ( 'knox.auth.TokenAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',) } views.py #just everything user related class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username') class LoginUserSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) print(user) if user:# and user.is_active: return user print("failed") raise serializers.ValidationError("No no to log in with provided credentials.") #Views class RegistrationAPI(generics.GenericAPIView): serializer_class = CreateUserSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) class LoginAPI(generics.GenericAPIView): serializer_class = LoginUserSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user) }) urls.py router = routers.DefaultRouter() router.register('api/games', GameViewset, 'games-name') urlpatterns = [ re_path(r"^", include(router.urls)), re_path(r'^api/auth/', include('knox.urls')), re_path(r"^api/auth/register/$", RegistrationAPI.as_view()), re_path(r"^api/auth/login/$", LoginAPI.as_view()) ] -
How to generate ping-pong api using Django Rest Framework?
I want to build a simple Ping-Pong using Django Rest Framework, so I don't need Model. I watch the api's status via swagger(drf_yasg), but I cannot find any parameters of it. I want to create Serializer, View and some code for routing. And I got some error lines from terminal. Serializer from rest_framework import serializers class PingPongSerializer(serializers.Serializer): ping = serializers.CharField(allow_blank=True, default="ping", max_length=20, help_text="please input 'ping'") # example_ping = PingPongSerializer({"ping": "hoge"}) # => {'ping' : 'hoge'} # example_ping = PingPongSerializer({}) # print(example_ping.data) # => {'ping' : 'hoge'} View from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from ping_pong.serializers import PingPongSerializer # Create your views here. class PingPongView(APIView): def get(self, request, format=None): serializer = PingPongSerializer(data=request) print(request) if serializer.is_valid(): print(request.data) return Response(serializer.data) else: print(serializer) print(serializer.errors) return Response({'result': "I don't know anything"}) Urls from django.contrib import admin from django.urls import path from django.conf.urls import url from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi from rest_framework import routers from ping_pong import views from django.conf.urls import include # router = routers.SimpleRouter() # router.register(r'ping', views.PingPongView, base_name='ping') schema_view = get_schema_view( openapi.Info( title="Restful API Lists", default_version='v1', description="Ping Pong", license=openapi.License(name="MIT"), ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path('admin/', admin.site.urls), # url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), … -
"Manager isn't accessible via model instances" when add data on ForgeinKey from ManyToManyField data
In models: class MyTeam(models.Model): captain_first_team = models.ForeignKey(FirstTeamPlayer, on_delete=models.SET_NULL, null=True, blank=True, related_name="captain_first_team_set") team_player_first_team = models.ManyToManyField(FirstTeamPlayer, blank=True, related_name="team_player_first_team_set") In views: amar_team = get_object_or_404(MyTeam, pk=team_id) first_team_player = get_object_or_404(amar_team.team_player_first_team, pk=player_id) amar_team.objects.create(captain_first_team=first_team_player) Here, In MyTeam model I have a ManyToManyField field and a ForeignKey field. I want to add data in a ForeignKey field from ManyToManyField field data. I also try: amar_team.captain_first_team.add(first_team_player) amar_team.captain_first_team.save(first_team_player) But it's not working. How can I do this?? -
Model translation in Django Rest Framework
I'm developing an API with Django Rest Framework, and I'd need some models with a few fields that should support translation in multiple languages then, of course, serializers should have to retrieve the field with the expected language. I've thought about two options: adding extra fields to the model (one field for language) or creating another model with all texts in every language. On the other hand, I've seen that there are some libraries such as django-modeltranslation that are intended to solve that issue, however, I'd like to know some opinions about them. What do you think? What would you recommend to me? Thank you very much -
Why my_task.delay() works only within tasks module, not in models or views modules?
I have created tasks.py in my app. Celery tasks I have created can be called in cmd or inside tasks.py itself. But it is not possible to call them in views.py or models.py. -
'django.contrib.messages.context_processors.messages' must be enabled in DjangoTemplates
When I try to migrate or createsuperuser in my project I get this error. I shouldn't be getting error since it's a starter project and I'm not even using templates. SystemCheckError: System check identified some issues: ERRORS: ?: (admin.E404) 'django.contrib.messages.context_processors.messages' must be enabled in DjangoTemplates (TEMPLATES) in order to use the admin application. -
Is there a way i can add the swagger integration to django project after adding i dont see all the endpoints on swagger api
I'm trying to integrate the swagger in Django project with DRF, but when i try to access the endpoint i dnt see all the endpoints https://django-rest-swagger.readthedocs.io/en/latest/ REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', # 'rest_framework.permissions.IsAdminUser', ], 'DEFAULT_PAGINATION_CLASS': 'finishline.pagination.Paginator', 'PAGE_SIZE': 100, 'PAGINATE_BY_PARAM': 'page_size' } these are my settings -
How to show the correct name object in Django admin instead 'XXX object'
I've two apps in my Django Project and I created an ManytoManyField relationship between then. However, when I check it on my admin site, the references appears showing the model name plus object inside the Many to Many box. I already tried write a str in my model as you can see below: def __str__(self): return str(self.course.name) Below there is my models code. from django.db import models from cursos.models import Course class Person(models.Model): name = models.CharField(max_length=50) course = models.ManyToManyField(Course, blank=True) def __str__(self): return str(self.course.name) -
Parallel stored procedure execution in MySQL
I have a web application with following setup: Django 2.1.7 web application. I'm using gunicorn as my web server. Script to startup gunicorn server: gunicorn project_config.wsgi:application --worker-class=gevent --worker-connections=1000 --workers=8 I have concurrent API requests (It does some heavy processing, but mostly it is stored procedure calls - most time spent in doing IO). So when serving multiple API calls, I'm running multiple stored procedure calls parallely. Since I'm starting up my gunicorn server using gevent worker class, it creates 8 worker processes (not green-threads). Which means there is no context switching happening between each API requests. But my stored procedure call execution time doubles with number of API calls. So essentially a API request which gets completed is 10 minutes takes 20 minutes if there is another API call getting served parallely. Similarly if there are 3 requests being served parallely, each request is taking 30mins. Initially I thought this is something to do with multi-threading and GIL lock, as python threads do not actually run parallely. But when I print the PID (using os.getpid()), each requests prints unique PID (pid of the gevent worker process). My stored procedure is a complex select statement. It does not perform any DELETE/UPDATE … -
Django: Reference to an outer query may only be used in a subquery
I use the following queries: def get_queryset(self): posts = Post.objects.filter(topic_id=OuterRef('pk')) unread_posts = posts.exclude(read_by=self.request.user) return Topic.objects.all().annotate(is_unread=Exists(unread_posts), number_of_replies=Subquery(posts.count())).order_by('-latest_post') Unfortunately, I get the following error message: This queryset contains a reference to an outer query and may only be used in a subquery. I'm confused because I explicitly set Subquery(posts.count()). Can someone give me a hint? -
Django - What is the most pythonic way to update my page via AJAX?
I want someone with "manager" access to be able to view all user activity, and the page should continuously update after every couple of minutes via AJAX. Should I have both users and AJAX requests get sent to the same URL? Or should I have two separate URLs (one that renders a template and another one that only returns JSON)? Here is how I imagine this should be structured: def index(request): context = get_user_activity() if request.is_ajax(): # Process the data and only return updates they don't already have on their screen return JsonResponse(updated_data, status = 200) return render(request, 'activity.html', context) domain.com/activity/ <-- Users and AJAX requests are sent to this url OR domain.com/activity/ <-- Users get sent to this page domain.com/api/update-activity <-- AJAX requests are made to this URL -
ValueError: Cannot use object with type list for a spatial lookup parameter. Geodjango Model
In trying to build a Geodjango app, I encounter a ValueError. I have not done any spatial queries but I get stuck with ValueError: Cannot use object with type list for a spatial lookup parameter. I made the Point object as a GEOS Point Object, How can I solve this? from __future__ import unicode_literals from django.contrib.gis.db import models as geomodels from django.utils.crypto import get_random_string from django.contrib.gis.geos import GEOSGeometry,Point # Create your models here. geos_pnt=Point(4314498.56, 1003834.600) #pnt=GEOSGeometry('POINT(4314498.56, 1003834.600)').wkt class Apartment(geomodels.Model): apt_id = get_random_string(length=8) location = geomodels.PointField(default=pnt,extent=(4282586.10,996190.90,4346411.02,1011478.31), blank=True, null=True, srid=3857, help_text="Point(longitude latitude)") apt_cost = geomodels.FloatField(default=0.0) apt_area = geomodels.FloatField(default=0.0) SUBCITY_CHOICES = (('ADK','Addis Ketema'),('AKLTY','Akaki-Kality'),('ARD','Arada'), ('BL','Bole'), ('GL','Gulele'), ('KLF', 'Kolfe-Keranio'), ('LDTA','Ledeta'), ('NFS','Nefas Silk'), ('YK','Yeka')) apt_subcity = geomodels.CharField(default='NFS',max_length=100, choices=SUBCITY_CHOICES) register_date = geomodels.DateTimeField('Register Date',auto_now_add=True,null=True) def save(self, *args, **kwargs): #self.Latitude = self..y #self.Longitude = self.location.x super(Apartment, self).save(*args, **kwargs) class Meta: # order of drop-down list items ordering = ('apt_cost',) # plural form in admin view verbose_name_plural = 'apartments' def __unicode__(self): return self.apt_id -
Cannot assign "(<User: jack>, True)" "Profile.user" must be a "User" instance
i Use One-To-One Link With a User Model (Profile) and i got this error when i try to make user registration Cannot assign "(, True)": "Profile.user" must be a "User" instance. and this is user_registration uses in my project thanks for help def user_registration(request): form = UserRegistrationForm() if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] structure= form.cleaned_data['structure'].id user = User.objects.get_or_create (username=username, password=password) profile=Profile.objects.create (structure_id=structure,user=user) profile.save() messages.success(request, 'Enregistrement avec succés {}'.format(user.username)) return HttpResponseRedirect(reverse('compte:login')) else: form = UserRegistrationForm() return render(request,'compte/register.html',{'form':form})