Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No MyUser matches the given query
I am having an error No MyUser matches the given query, and I am not sure why there is no a match since the URL is properly set. In my app I have two kind of users: Employees and candidates that are both part of the model MyUser and are differentiated by a boolean is_candidate or is_employee. My issue is when creating the user detail view. I started with the EmployeeDetailView : class EmployeeDetailView(LoginRequiredMixin, generic.DetailView): #import pdb; pdb.set_trace() model = MyUser template_name = 'employee_details.html' def get_object(self, queryset=None): return get_object_or_404(MyUser, pk=self.kwargs['pk2'], members__project=self.kwargs['pk1']) def get_context_data(self, **kwargs): context = super(EmployeeDetailView, self).get_context_data(**kwargs) employee_name = MyUser.objects.get(id=self.kwargs['pk2']) team_list = Project.objects.get(id=self.kwargs['pk1']).team_id.members.all() team_list_pop = Project.objects.get(id=self.kwargs['pk1']).team_id.members.all().exclude(id=self.kwargs['pk2']) context={ 'employee_name' : employee_name, 'team_list' : team_list, 'team_list_pop' : team_list_pop, } return context on URL : url(r'^project/(?P<pk1>[0-9]+)/(?P<pk2>[0-9]+)/$',views.EmployeeDetailView.as_view(), name='EmployeDetails'), That work properly and I am able to access my user detail So I wanted to do the same for CandidateDetailView with the code : class CandidateDetailView(LoginRequiredMixin, generic.DetailView): #import pdb; pdb.set_trace() model = MyUser template_name = 'employee_details.html' def get_object(self, queryset=None): print(self.kwargs['pk2']) return get_object_or_404(MyUser, pk=self.kwargs['pk2'], applicant__project=self.kwargs['pk1']) def get_context_data(self, **kwargs): context = super(CandidateDetailView, self).get_context_data(**kwargs) context={ } return context On URL : url(r'^project/(?P<pk1>[0-9]+)/(?P<pk2>[0-9]+)/$',views.CandidateDetailView.as_view(), name='CandidateDetails'), But this time I get the error that there is no matching Raised by: … -
Easy Django REST Framework Websocket Usage
I have a an application that uses Angular for the frontend and communicates with an API running Django RF. Now, let me try and outline what I'm trying to achieve in hopes of finding an easy solution. When a user runs a report, a worker version of the API generates the report to prevent the main API from bogging down. The report runs for a couple seconds/minutes. The user refreshes the page and voila, their report is there. What I'm trying to achieve is the elimination of the whole "user refreshes the page" portion of this process. My goal is to do this via websockets. I literally want something as simple as: WEB: "Hey API, I want this report. I'll wait." API: "Yo dog, you're reports done." WEB: "Cool, let me refresh my report list. Thanks bud." Now, we start to venture into an area I'm unfamiliar with. Websockets can do this, right? I just need to create a connection and wait for the all-clear to be sent by the worker. Now, here's where it gets hairy. I've spent the better part of the day going through libraries and just can't find what I need. The closest I've come is … -
django form ManyToMany Initial queryset value
This has oficially driven me crazy. I have a very basic form with 1 many to many field: models.py class ProtectionProfile(models.Model): Optional_SFR = models.ManyToManyField(SFR, related_name='Optional') Then my forms.py class OptForm(forms.Form): selecopt_sfr = forms.ModelMultipleChoiceField(queryset=MYProtectionProfile.Optional_SFR.all()) During my page render I get a number of protectionprofiles for a given user. for each protectionprofile I need to generate a form with those various Optional_SFR field. So how can I pass the relevant ProtectionProfile to the form for the correct query set? I feel like this should be really easy but I can't find it any where! Any help is greatly appreciated. -
adding a custom method to Meta class in django
I have an AbstractBase model class that gets inherited by several models in their respective apps. I want the user to be able to set a name that will be used in the verbose_name field in the Meta class. If a user provides a name in one of the fields in the AbstractBase model, then that field will be used as the verbose name this is what I have tried so far class AbstractBase(models.Model): ...... custom_name = models.CharField(blank=True) class Meta(object): abstract = True def update_verbose_name(self, custom_name): if self.project_setting is not None: return verbose_name == self.custom_name when I run this it gives me TypeError: 'class Meta' got invalid attribute(s): update_verbose_name is there another way that I solve this? -
Struggling with trans in a input placeholder
Here is the HTML part <div class="col-md-4 col-sm-4"> <input type="text" class="form-control" placeholder={% trans "First Name" %} id="cf-fn" name="cf-fn" required=""> </div> Instead of getting 'First Name', I got just 'First'. Here is a photo How could I fix it? -
Django ORM - a model object from using .get or indexing a QuerySet
my_model = MyModel.objects.get(pk=5) So 'my_model' is not a queryset object, neither would it be if I indexed it from a queryset. Is there something special about a QuerySet other than it is a list of objects from the table(s)? Also I was wondering, I know that simply creating a QuerySet does not involve a database lookup, but what about getting just one object like in 'my_model'? -
Django docker error table not exist
I had a existing Django Rest project with an existing MySQL database (named libraries) which I wanted to Dockerize. My dockerfile: FROM python:2.7 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . /code/ RUN pip install -r requirements.txt My docker-compose: version: '3' services: db: image: mysql environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: libraries MYSQL_USER: root MYSQL_PASSWORD: root web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" Steps: I ran: docker-compose build - build was successful I ran: docker-compose up - had to run this command twice and then I could access my API by hitting localhost:8000 However, whenever I hit any API endpoint I get an error Table "XYZ" does not exist. All the tables are already present. Why this happens? -
How to pull other serialized data from different Serializer classes?
I'm trying to pull the permissions data into my UserSerializer. I have a Many To Many relationship with User to Group with a through table called GroupUser. I'm able to pull the group_id and the group_name, but I can't seem to populate the data for permissions into my User Serializer. So far I've tried using permission = serializers.ReadOnlyField(source='group.permissions') but that doesn't work. Any suggestions? Here's my code: class GroupSerializer(serializers.ModelSerializer): users = GroupUserSerializer(source='groupuser_set', many=True) permissions = PermissionSerializer(source='permission_set', many=True) class Meta: model = Group fields = ('id', 'name', 'users', 'permissions', 'role', ) class GroupUserSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField(source='group.id') name = serializers.ReadOnlyField(source='group.name') class Meta: model = GroupUser fields = ( 'id', 'name', ) class UserSerializer(serializers.ModelSerializer): tests = TestSerializer(source='test_set', many=True) groups = GroupUserSerializer(source='groupuser_set', many=True) class Meta: model = User fields = ( 'id', 'username', 'groups', 'tests', ) I want my data to look like this: { "id": 1, "username": "user", "groups": [ { "id": 2, "name": "employee" "permission": "Access-Denied" } ], "tests": [] }, but I have it without "permissions" -
Dynamically updating db_table to use one model for several database tables
I thought I ran into a roadblock with Django that would require writing raw SQL to resolve instead of using Django's ORM. I asked about it on SO and was informed it is possible to create dynamic classes or to assign db_table dynamically to the model. The issue is that I have several dozen tables that are similar. They do all have about five fields that are in them all. The remaining hundred, or so columns, are unique. (Basically each table represents industry data and a year; even within the same industry the data can vary from year to year). I was informed that Django models are pretty "loose" in that you could only identify these common columns and the model doesn't care about the rest of the columns, so you could do a Table.objects.all() and get everything in the table. My concern was I was going to need to build several dozen mostly redundant models, and have to add new ones annually which is really inefficient. I was leaning towards writing the query in raw SQL so I could dynamically specify the table name until I was informed of these things. Came across these SO questions, but I am … -
Running two databases on heroku with django
I have two databases that my Django application needs access. One is a shared database owned by a separate app with the Django app only having read access. The second is entirely owned by the Django app. For local development I am ok but I'm not sure how to configure things so that Heroku uses the second database. Currently I have the shared database promoted to DATABASE_URL and the secondary database is at HEROKU_POSTGRESQL_BLUE_URL. In my settings I have: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'main_database_name', 'USER': 'username', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '5432', }, 'secondary': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'secondary_database_name', 'USER': 'username', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '5432', } } Please ask any more questions if you need me to clarify. Thanks! -
How to get objct information from Ajax response in JSON
I'm working on a site that needs to parse an Ajax response which looks something like this: {"comments": "[{\"model\": \"modelhandler.comment\", \"pk\": 4, \"fields\": {\"user\": 2, \"description\": \"hello this is a comment but I don't know if it's working yet.......\", \"replyto\": null, \"uploaded\": \"2018-01-10T20:35:40.856Z\", \"updated\": \"2018-01-10T20:35:40.856Z\"}}]"} I tried getting data from this response like this: success: function (data) { var json = JSON.parse(JSON.stringify(data)); $.each(json, function(key,value) { alert(value.comments); }); } This however alerts me undefined Here the comments field has 1 comment in it but I might have more than 1. How would I go about retrieving data from a Json response like this? EDIT: I logged data object and I got this: Object comments : "[{"model": "modelhandler.comment", "pk": 4, "fields": {"user": 2, "description": "hello this is a comment but I din't know if it's working yet.......", "replyto": null, "uploaded": "2018-01-10T20:35:40.856Z", "updated": "2018-01-10T20:35:40.856Z"}}]" __proto__ : Object in Google Chrome using console.log() also the json is generated by a django view like this: def obtain_comments(request, *args, **kwargs): begin = int(request.GET['begin']) end = int(request.GET['end']) n_comments = end - begin all_split = Comment.objects.order_by('-uploaded')[:end] data = { 'comments': serializers.serialize('json',all_split), } return JsonResponse(data) -
Django - Filter GTE LTE for alphanumeric IDs
I am trying to serve up our APIs to allow filtering capabilities using LTE and GTE on our ID look ups. However, the IDs we have are alphanumeric like AB:12345, AB:98765 and so on. I am trying to do the following on the viewset using the Django-Filter: class MyFilter(django_filters.FilterSet): item_id = AllLookupsFilter() class Meta: model = MyModel fields = { 'item_id': ['lte', 'gte'] } But the issue is, if I query as: http://123.1.1.1:7000/my-entities/?item_id__gte=AB:1999 or even http://123.1.1.1:7000/my-entities/?item_id__lte=AB:100 it won't exactly return items with ID's greater than 1999 or less than 100 since the filter will take ID as a string and tries to filter by every character. Any idea how to achieve so I can filter on IDs so I get items exactly greater / less than the numeric ID (ignoring the initial characters) ? -
Backend not Found for Facebook
I cant seem to get it to work guys, after reading similar questions my issue is not due to not specifying key and secret nor is it because i forgot to add '-oauth2' after facebook. please help?? All i see on the browser is Backend not Found. Maybe it is just because my django or python versions are too new?? I use python 3.6 and django 2.0... here is my project's settings.py SECRET_KEY = '<my_secret_key>' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main_app', 'django_filters', 'cuentas', 'social_django', ] 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', 'social_django.middleware.SocialAuthExceptionMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] # python social auth settings SOCIAL_AUTH_FACEBOOK_KEY = '<facebook_app_id>' SOCIAL_AUTH_FACEBOOK_SECRET = '<facebook_app_secret>' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_API_VERSION = '2.11' AUTHENTICATION_BACKENDS = [ 'social_core.backends.facebook.FacebookAppOAuth2', 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ] SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'social_core.pipeline.social_auth.associate_by_email', ) -
PK2 as a context for a User Detail View
In my app I have two kind of users, Employees and candidates that are both part of MyUser model, with different attribute is_candidate, is_employee (True, False) My view EmployeeDetailView ( I need to change the name) is supposed to serve both, and while for employee users I am ok, for candidate user I am having an issue acceding to the User detail view because of pk2 that is not found, the PK1 is found. I In general I am having trouble to understand how to deal with multiple key arguments like Pk1 and pk2 I do not know how to define PK2 in my context my model is : class Project(models.Model): name = models.CharField(max_length=250) team_id = models.ForeignKey(Team, blank=True, null=True) project_hr_admin = models.ForeignKey('registration.MyUser', blank=True, null=True) candidat_answers = models.ManyToManyField('survey.response') applicant = models.ManyToManyField(MyUser, related_name="applicant") def get_absolute_url(self): return reverse('website:ProjectDetails', kwargs = {'pk1' : self.pk}) the view of my page with the link: class RecruitmentPage(generic.ListView): #import pdb; pdb.set_trace() model = Project template_name = "recruitment_index.html" def get_object(self, queryset=None): return get_object_or_404(Project, id=self.kwargs['pk1']) def get_context_data(self, **kwargs): context = super(RecruitmentPage, self).get_context_data(**kwargs) current_project_id = self.kwargs['pk1'] applicant_list = Project.objects.get(id = current_project_id).applicant.all() app_with_resp = [] app_without_resp = [] for i in applicant_list: if len(i.response_set.all())>0: app_with_resp.append(i) else: app_without_resp.append(i) context['current_project_id'] = current_project_id context['applicant_list'] = … -
Django authentication view SetPasswordForm
I'm trying to modify password reset confirmation default template by adding styling to forms. My scripts: forms.py from django.contrib.auth.forms import SetPasswordForm class PasswordResetConfirmForm(SetPasswordForm): new_password1 = forms.CharField( label="New password", strip=False, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'New password', }), ) new_password2 = forms.CharField( label="New password confirmation", strip=False, widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Confirm New Password', }), ) views.py from django.contrib.auth import views as auth_views class ConfirmPasswordResetView(auth_views.PasswordResetConfirmView): form_class = PasswordResetConfirmForm template_name = 'registration/password_reset_confirm.html' password_reset_confirm.html {% extends 'base.html' %} {% block content %} {% if validlink %} <div class="mx-auto" style="width: 400px;"> <form method="post" style="background-color: #f0ebbe; padding: 20px;">{% csrf_token %} <h1>Change password</h1> <div class="form-group"> {{ form.new_password1 }} </div> <div class="form-group"> {{ form.new_password2 }} </div> <button type="submit" class="btn btn-primary">Change password</button> </form> </div> {% else %} <p> The password reset link was invalid, possibly because it has already been used. Please request a new password reset. </p> {% endif %} {% endblock %} Problem is that, class and placeholder attributes are not passed to inputs in the template. What can be the problem? -
Why does Python Request's JSON decoder return the concatenation of top-level keys
I am using the Requests library to decode a JSON response as follows: Payload Being Decoded: { "objectOne": { "desc": "one" }, "objectTwo": { "desc": "two" } } Code: from django.http import HttpResponse import requests class ApiService: @staticmethod def say_something(self): resp = requests.get('http://127.0.0.1:9501/polls/test/') return HttpResponse(resp.json()) Output: objectOneobjectTwo I followed the simple example from the official documentation: JSON Response Content In addition I wrapped the response in [] brackets to see if the response must be in a JSON array but it just returns an array with 'objectOneobjectTwo' as the 1st and only element. -
how to use integer variable as subscript in Django template
I have a for loop in a Django template: {% for i in no_of_lift_series_range %} {{ workout.lifts.series.i.activity_name }} {% endfor %} where this fails to output anything. The problem lies in the use of i. I know this, because this: {% for i in no_of_lift_series_range %} {{ workout.lifts.series.0.activity_name }} {% endfor %} outputs what it is supposed to output. Why can't I use i in the way I want and how do I make this work? -
django-filter access foreign keyed entries
The problem I'm using the django-filter package to filter through my results. Suppose my models look like the following: class Material(models.Model): id name class Test1(models.Model): id materialTested = models.ForeignKey(...) TestResult class Test2(models.Model): id materialTested = models.ForeignKey(...) TestResult I am trying to filter using the package using results from both Test1 and Test2. The reason the tests are their own models is because multiples of the same test (or none) can be run for the same materials Current Progress I currently have it set up to filter using a single test by defining the following filter: class Filter1(django_filters.FilterSet): class Meta: model = Test1 fields = {'TestResult':['gte','lte']} -
django create N number of forms in template
I was wondering if it was possible to write a more generic form to use as a template so that during the render it will create as many forms as necessary? If not how would one write code to create N number of forms, where the number is Dependant on the result of some query set? I know the code below doesn't work I am leaving it in as more sudo code forms.py: class OptionalSFRForm(forms.Form): selected_optional_sfr = forms.ModelMultipleChoiceField(queryset=sfrs_models.ProtectionProfile.objects.all()) def Custom(QueryPP): selected_optional_sfr = forms.ModelMultipleChoiceField(queryset=QueryPP.Optional_SFR.objects.all()) models.py class ST_Title(models.Model): Selected_SFR = models.ManyToManyField(sfrs_models.SFR, related_name='Selected_SFR') AttachedPPs = models.ManyToManyField(sfrs_models.ProtectionProfile, related_name='ST_PPs') sfrs.models.py class ProtectionProfile(models.Model): Optional_SFR = models.ManyToManyField(SFR, related_name='Optional') template: {% for AttachedPPs in ST_Title.AttachedPPs.all %} <form action="{% url 'SecurityTarget:stview' ST_Title.id %}" method="post" id="conformanceform"> {% csrf_token %} {{OPTSFRS.Custom(AttachedPPs)}} </form> -
What is the purpose of manage.py in Django startproject?
I come from a JS background, and decided to start a Python project to learn the basics of creating/deploying an app in Python, and I do not see any concise explanations of what the purpose of manage.py is, so I decided to give it an ask. -
Django form for hidden input fields
I have two models, Post and Attachment. Attachment has a foreign key to Post. I have a PostCreateView with PostForm. While writing a post, you may upload images using jquery-fileupload (AJAX). If files are uploaded the following lines are appended to <form>. <input type="hidden" name="attachments" value="1" /> <input type="hidden" name="attachments" value="2" /> <input type="hidden" name="attachments" value="3" /> The values(1, 2 and 3) are PK for Attachment model in order to make a relationship between Post and Attachment when I save a post. I was able to get a list in view: def form_valid(self, form): attachments = self.request.POST.getlist('attachments') However, I'd like to declare the form field in PostForm for the following validations: PKs must be integers. Attachment's foreign key must be null with those PKs. A post may have NO attachment, so the attachment hidden input tag does not exist at first. That's why it could be hard to have a form field. These are appended by AJAX/jQuery. If it is diffcult, I'd like to know the best practice which method shoud be overridden in CreateView. Thank you. -
Django Rest Framework admin extend model
I am trying to extend Django Rest Framework admin model. This is the code that I have: from django.contrib import admin from .models import * from markdownx.admin import MarkdownxModelAdmin def process_topics(_, __, queryset): from person.tasks import calculate_factors for object in queryset: calculate_factors(object) process_topics.short_description = "Process topics manually" class ObjectAdmin(admin.ModelAdmin): list_display = ('pk', 'sender', 'note',) actions = [process_topics, ] # admin.site.register(Object, ObjectAdmin) admin.site.register(Object, MarkdownxModelAdmin) I would like to use ObjectAdmin to extend MarkdownxModelAdmin class. -
GeoDjango GDAL error in terminal
I have an application which I wrote some months ago which included geodjango but I now visited the project today and ran the project in my terminal and got this error django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal2.1.0", "gdal2.0.0", "gdal1.11.0", "gdal1.10.0", "gdal1.9.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. . I since dont know how to figure it out. any help will be appritiated and further codes would be supplied on request -
django many to many modelform view
I'm newbie with django. I want to show all models in view. For example if this code is launched, it doesn't show the Author model. from django.db import models from django import forms #Models class Author(models.Model): name = models.CharField(max_length=100) birth_date = models.DateField(blank=True, null=True) def __str__(self): return self.name class Book(models.Model): name = models.CharField(max_length=100) authors = models.ManyToManyField(Author) class Peoples(models.Model): name = models.CharField(max_length=30) book = models.ManyToManyField(Book, blank=True) def __str__(self): return self.name #ModelForm class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ['name', 'birth_date'] class BookForm(forms.ModelForm): class Meta: model = Book fields = ['name', 'authors'] class PeoplesForm(forms.ModelForm): class Meta: model = Peoples fields = '__all__' #View def test(request): if request.method == 'POST': form = PeoplesForm(request.POST) else: form = PeoplesForm() return render(request, 'test/form.html', {'form': form} ) How diplay all models wich have servals manytomany relations ? Thanks a lot. -
Which technologies can I authorize users of my Django app to call an API Gateway endpoint?
so I'm developing a Django-based webapp and hosting it on AWS Elastic Beanstalk. Right now, users log in and are authenticated by Django's default Session based auth system. I also have a Chrome Extension, and an AWS Lambda function as part of the same system. The Chrome Extension, when installed, will periodically send requests to the AWS Lambda function via AWS API Gateway. When a request reaches API Gateway, I want to only allow Django-authenticated (authorized?) requests to pass. In the Lambda function, I would like to find out which user sent the request and process the data as required. My understanding is that I'll need to move away from session-based authentication to a public/private key encryption of some sort. I have seen AWS Cognito mentioned, OAuth2, OpenID, and JWT. I am struggling to compare these technologies as they seem to serve slightly different purposes in some cases. I see words like "authentication" and "authorization" being used and I don't fully understand the different meanings. Can anybody help me understand which technologies I can use and in what ways in order to achieve my use-case?