Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django QuerySet for ManytoMany relation using Bridging Table
I am new to Django and was looking for an efficient way to retrieve and post to a ManytoMany relation using an intemrediary table. models: from django.db import models # Create your models here. class Actor(models.Model): name = models.CharField(max_length = 50, primary_key = True) bio = models.CharField(max_length=150) class Movie(models.Model): name = models.CharField(max_length=100) release = models.CharField(max_length=100) class NormActors(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE) actor = models.ForeignKey(Actor, on_delete=models.CASCADE) I have checked the documentation and it got confusing, so any reference would be helpful as well. If on request, I want to send - for /movies: get list of all movies + details with the actor names in the respective movies for /actors: get list of all actors + details with the movies they have been in Should the ORM query look something like this? actor = Actor.objects.get(name="XYZ") movies = actor.movie_set.all() How should I go about fr the first one? -
Dynamically change point for OSMWidget in js
I am using OSMWidget field (docs) to show a PointField, the problem is I need to manually change the point in page. so I want to run something like this in js when user clicks on some other button in page: point.setCoordination(lat, lng) After some source code reading I found out django is using MapWidget to to draw a map. (link to django template) var geodjango_my_point = new MapWidget(options); and MapWidget is defined here which uses open layers (I think so) but other than that I don't have any other idea about solving this problem. -
How to show the path structure of navigated pages in templates[Home>Category>Products>Shoes]
How is it possible to show the Page's path inside a page. My idea is to implement the path using a link just like the directory structure in the OS. How can I implement something like. You are Here: Home>Category>Products>Shoes>Sports Shoes > Basketball > Nike And these must be links so that when a user clicks on these, it opens the following page. -
DRF: values() does not return groupby object
Suppose I have: # models.py class Project(models.Model): project = models.CharField(max_length=200) subproject = models.CharField(max_length=200) physical_pct = models.FloatField() cost = models.FloatField() # serializers.py class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = '__all__' In my viewset, I want to display a grouped by object by name that will later be annotated. # views.py class ProjectsViewSet(viewsets.ModelViewSet): serializer_class = ProjectSerializer def get_queryset(self): queryset = Project.objects.values('project') print(queryset) return queryset When I print queryset it displays a list of all project without the other fields in the terminal. However it raises an error: "Got KeyError when attempting to get a value for field `subproject` on serializer `ProjectSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'subproject'." -
Unable to display our details in profile page?
I'm new to django i created a project login and registration all are fine but i unable to display model user data on profile page, i tried so many ways but not displaying only adminUser related data displaying .... views.py -------- def maas(request,maas_username_slug): context_dict = {} try: maas = Maas.objects.get(slug=maas_username_slug) context_dict['maas_username'] = maas.username context_dict['maas_username_slug'] = maas_username_slug context_dict['maas_phone'] = maas.phone context_dict['maas_firstname'] = maas.firstname context_dict['maas_lastname'] = maas.lastname context_dict['maas_location'] = maas.location context_dict['date_of_birth'] = maas.date_of_birth context_dict['comments'] = maas.comments context_dict['maas_gender'] = maas.gender context_dict['photo'] = maas.photo context_dict['maas'] = maas except Maas.DoesNotExist: pass print(context_dict) return render(request, 'testapp/profile.html', {'context_dict': context_dict}) urls.py ------ url(r'(?P<maas_username_slug>\w+)/$', views.maas, name='profile'), -
Catching Server Error 500 using logging in Django (Server gunicorn)
I have an application deployed on Heroku and sometimes it throws the server error 500 randomly. I am trying to implement logging in my project. I am reading the docs but I am missing some critical piece of information. The docs say, Once you have configured your loggers, handlers, filters and formatters, you need to place logging calls into your code. My question is where exactly to put the logging code because I have already used try-except for all the parts, as far as I know, that may throw an error? I have done a tutorial on the topic and reading the docs but that doesn't seem to convey the message to me. -
Django infinity redirect in IIS behind a proxy server turned on SSL
I have a problem with Python Django when deploying on Windows Server. Let's summary my situation: End user <---> Proxy Server will SSL <--> Django on Win Server The communication between End-User with Proxy server is HTTPS, the commnunication between Proxy Server with Django is HTTP. So, when the user browse the web site, proxy server tried to redirect to https and passing to Django, Django processed the request and return http to proxy, proxy server tried to redirect its to https => that's caused the CSRF failed => loop infinity here. I have read the django doc here https://docs.djangoproject.com/en/2.2/ref/settings/#secure-proxy-ssl-header Warning Modifying this setting can compromise your site’s security. Ensure you fully understand your setup before changing it. Make sure ALL of the following are true before setting this (assuming the values from the example above): - Your Django app is behind a proxy. - Your proxy strips the X-Forwarded-Proto header from all incoming requests. In other words, if end users include that header in their requests, the proxy will discard it. - Your proxy sets the X-Forwarded-Proto header and sends it to Django, but only for requests that originally come in via HTTPS. If any of those are not … -
Django admin list_filter return ''str' object has no attribute 'days' for DurationField
I am using DurationField in on my model's field. The issue arises when I try to use this DurationField in list_filter in Django admin. Filtering based on this DurationField results in ''str' object has no attribute 'days'. I am using sqlite3 and Django 2.2.4. How can I overcome this problem? I need to be able to use DurationField in my Django admin filter. I have checked the Debug page result and it shows that the value is returned as a string. Why is being returned as a string and not in timedelta format? Below is the snippet of the DEBUG page. The value is in string and thus it fails. connection prepared True self value '1:22:22' Below is how my model is: class VideoSeries(models.Model): average_length = models.DurationField() I just want to be able to filter based on average_length which is a duration field. Is there any customization to be done for DurationField? Any help is highly appreciated. Thanks in advance -
Receiving 'invalid form: crispy' error when trying to use crispy forms filter on a form in Django, but only in one django app and not the other?
When trying to use the crispy filter I receive an error: django.template.exceptions.TemplateSyntaxError: Invalid filter: 'crispy' I believe this is because Django can for some reason not locate the crispy filter, since when I put in the name of a filter that did not exist I received the same error. I have used {% load crispy_forms_tags %} at the top of the html document and use {{ form|crispy }} to apply the filter. I have also added the 'crispy forms' app to the settings.py file, and installed the django-crispy-forms package with pip, which I can clearly see using pip freeze. PLEASE NOTE that the crispy forms filter does work in a different django app for my website, even though I don't think I altered anything in that app's directory (but I could be wrong it's been awhile since I worked in that directory). I can't figure out what's different. I read something about filters attaching to the first app directory it can and that's it, but that info was vague, and when I removed the ```{% load crispy_forms_tags %}''' line from the template that used it, the crispy filter still wouldn't work in the new app. The next two chunks of … -
How to modifying url.py to run in latest django version?
urls.py from django.conf.urls import patterns, include, url from django.conf.urls.i18n import i18n_patterns from django.utils.translation import ugettext_lazy as _ from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^i18n/', include('django.conf.urls.i18n')), ) urlpatterns += i18n_patterns('', (_(r'^dual-lang/'), include('duallang.urls')), (r'^', include('home.urls')), ) from django.conf import settings if 'rosetta' in settings.INSTALLED_APPS: urlpatterns += patterns('', url(r'^rosetta/', include('rosetta.urls')), ) Getting ImportError: cannot import name 'patterns' from 'django.conf.urls' -
raise errorclass(errno, errval) django.db.utils.InternalError: (1698, "Access denied for user 'root'@'localhost'")
'ENGINE': 'django.db.backends.mysql', 'NAME': 'tutorial', 'USER': 'root', 'PASSWORD': 'qweasd45678', 'HOST': 'localhost', 'PORT': '3306', when i makemigrations .... raise errorclass(errno, errval) django.db.utils.InternalError: (1698, "Access denied for user 'root'@'localhost'") -
Two fields unique
I have two fields in my model, number and series, What I want is that these fields are not repeated among the other records, example R1: Series: A and number: 1, which does not allow these two records to be repeated in the future if it already exists -
How to optimise querying facebook graph API
So we are building a web application that fetches data from FACEBOOK-WORKPLACE. On top of that, we are also building a machine learning algorithm to help in predicting employees that are at risk of employee churn. We're using a predictor called "Reactions Given" in order to get this, we have to Get the user email upon login. Get all the groups associated with the user. Get all the post in each group. Check weather a post was liked by a user. It is working, but it takes around 2 minutes to run. Any idea how we can optimize this? This is not a problem for analysis purposes but note that we are displaying a summary statistic to the web application, and this can probably result in bad UX. def get_user_groups(self): group_list = [] group = graph.request('%s?fields=groups&limit=999999999999' %self.email_address) group = group['groups']['data'] for i in group: group_list.append(i['id']) print('User has no groups') return group_list def get_group_feed(self,group_id): group_post = graph.request('%s/feed?limit=9999999999' %group_id) try: group_post = group_post['data'] except: print('Group has no posts') return group_post def get_group_post_list(self): group_post_list = [] for i in (self.get_user_groups()): for j in (self.get_group_feed(i)): try: group_post_list.append(j['id']) except: print('No id') return group_post_list def get_reaction_given(self): for i in self.get_group_post_list(): print(self.get_reaction_received(i)) -
How to inherit the source field validators on a serializer field?
Say I have the following model: class MyModel(models.Model): my_field = models.CharField(max_length=5, unique=True) When I create a ModelSerializer and define the model fields on the Meta class, it automagically defines the serializer fields like this: from rest_framework import serializers class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ('my_field',) >>> MySerializer() MySerializer(): my_field = CharField(max_length=5, validators=[<UniqueValidator(queryset=MyModel.objects.all())>] However, if I redefine this field on the serializer - e.g. say I want to rename this field to comply with the API spec - it defines it like this (as expected): from rest_framework import serializers class MySerializer(serializers.ModelSerializer): my_other_field = serializers.CharField(source="my_field") class Meta: model = MyModel fields = ('my_other_field',) >>> MyOtherSerializer() MyOtherSerializer(): my_other_field = CharField(source='my_field') How could I inherit the max_length and the validators from the model field specified by source, on the serializer field? Is there a way? I know I can redefine them by specifying max_length and the validators on the serializer field, but I wish to avoid this duplication of code. -
Error smpt sender refused in password reset
i want to send an email using gmail smpt but give me some errors, here the settings in django EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') is there anything wrong with the configuration? -
How to restrict the login google api with specific domain name only?
I'm creating a web application which I'm using Google API for authentication. Also, the library that I've applied was social-auth-app-django. Then, my goal is to allow only specific domain name like user@example.com with a domain of example.com. Upon reading its documentation this line of code should be added to settings.py SOCIAL_AUTH__WHITELISTED_DOMAINS = ['foo.com', 'bar.com'] however, it is not working to me. settings.py configuration AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_DOMAINS = ['example.com.hk'] How can I restrict the google api to only allow the specified whitelisted domains? -
How can I get all descendent of a tree except one leaf using django-mptt?
I have a tree: Art (root) |__> Visual art | |___> Painting | |___> Photography | |__> Performance art |___> music |___> dance How do I use Django-mptt and .get_descendants() to get everyone, except excluding one node (say in this case dance)? -
I get an mysqlclient error when run migration in Django
I install Django and try to connect to MySQL and run migrations, i get error "Did you install mysqlclient?". What should I do? I'm using venv, and my python version is 3.7.4, and mysql is Ver 8.0.17 for osx10.14 on x86_64 (Homebrew). And this is pip list Package Version beautifulsoup4 4.6.0 certifi 2019.6.16 chardet 3.0.4 Django 2.2.5 django-modelcluster 4.4 django-taggit 0.24.0 django-treebeard 4.3 djangorestframework 3.10.2 draftjs-exporter 2.1.6 entrypoints 0.3 flake8 3.7.4 html5lib 1.0.1 idna 2.8 mccabe 0.6.1 mysqlclient 1.4.2.post1 Pillow 6.1.0 pip 19.0.3 pycodestyle 2.5.0 pyflakes 2.1.1 pytz 2019.2 requests 2.22.0 setuptools 40.8.0 six 1.12.0 sqlparse 0.3.0 Unidecode 1.1.1 urllib3 1.25.3 wagtail 2.6.1 wagtailcodeblock 1.15.0.0 webencodings 0.5.1 Willow 1.1 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'local_test', 'USER': 'root', 'PASSWORD': 'root', 'HOST': '', 'PORT': '', 'OPTIONS': { 'charset': 'utf8mb4', } } } Traceback (most recent call last): File "/Users/bicepper/PycharmProjects/test-project/venv/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/bicepper/PycharmProjects/test-project/venv/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/bicepper/PycharmProjects/test-project/venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 2): Library not loaded: @rpath/libssl.1.0.0.dylib Referenced from: /Users/bicepper/PycharmProjects/test-project/venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so Reason: image not found The above exception was the direct cause of the following exception: Traceback (most recent call last): File "../manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/bicepper/PycharmProjects/test-project/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in … -
if i request axios.post, i recieve response null
if i request axios.post, i recieve response null. How do I correct this error? I've tried to changing multipart/form-data into x-www-form-urlencoded and multipart/x-www-form-urlencoded async submitUser() { this.memberObj = { id: this.memberObjLocal.id, name: this.memberObjLocal.name, password: this.memberObjLocal.password, email: this.memberObjLocal.email, password: this.memberObjLocal.password, gender: this.memberObjLocal.gender, experience: this.memberObjLocal.experience, birth: this.memberObjLocal.birth, phoneNum: this.memberObjLocal.phoneNum, address: this.address, introduce: this.introduce, pic: this.pic }; const config = { headers: { "Content-Type": "multipart/form-data" } }; var formData = new FormData(); for (let data in this.memberObj) { console.log(data); formData.append(data, this.memberObj[data]); console.log(this.memberObj[data]); } for (var key of formData.entries()) { console.log(key[0] + ", " + key[1]); } try { let response = await this.$axios.$post("/users/", formData, config); this.$router.push("/"); console.log(response) // null } catch (e) { console.log(e.response); } } -
Apply sort using python(not QuerySet) to models using ListView pagination
Apply sort using python(not QuerySet) to models using ListView pagination I use Django ListView with pagination feature to display models. Since I need to sort list of models using method field(need to send param to method thus it must be a method) return value, I cannot complete sorting using get_query_set method. Since get_context_data is called for each page, I cannot add sort to there. class SpotRankingView(ListView): model = Spot template_name = 'places/spot_list.html' paginate_by = 5 def get_context_data(self, **kwargs): context = super(SpotRankingView, self).get_context_data(**kwargs) # This is called for every page # So I cannot add sort here return context def get_queryset(self): # I need method return value to sort models # # ex. I need something like blow to sort models # spot.category(category_name = 'Relaxing').points # # Those cannot be done by QuerySet so I caanot add that # sorting here return Spot.objects.all() How can I sort models using python list sorting & make them paginate? -
Im building a crud in Django why is my Update function not working?
Im working on a CRUD in python Django, for CR D no problem, but for Updating it is a mess ! :) For now I have this first error : RuntimeError at /updateUser/36 You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. I dont understand because I have this in my urls.py : url(r'^removeUser/(\d+)/$', app.views.removeUser, name='removeUser'), url(r'^updateUser/(\d+)/$', app.views.updateUser, name='updateUser'), And for removing user there is no problem ! So okay lets add manually this slash at the end of my url and now I get this error : NOT NULL constraint failed: app_employee.name I really don't see what this means my views.py def addUser(request): """Add new employee""" if request.method == 'POST': form = CreationUserForm(request.POST) newEmployee = Employee() newEmployee.name = form['employeeName'].value() newEmployee.email = form['employeeEmail'].value() newEmployee.save() return HttpResponseRedirect(reverse('app:home')) def removeUser(request, id_user): """Fire an employee""" employeeFired = Employee.objects.get(id=id_user) employeeFired.delete() return HttpResponseRedirect(reverse('app:home')) def updateUser(request, id_user): """Make a change on an employee""" employee = Employee.objects.get(id=id_user) form = UpdateUserForm(request.POST) employee.name = form['changeEmployeeName'].value() employee.email = form['changeEmployeeEmail'].value() employee.save() return HttpResponseRedirect(reverse('app:home')) I built update as addUser which works so I dont get the point Thanks for helping !! … -
Linking of homePage view to other views
I am trying to link my home page view to other views but it's not working I also tried to take only a single view but it still not working I also don't know how to connect multiple views into a single URL app/views.py from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import redirect from django.shortcuts import render from homePage.forms import SignInForm,DropUsaMessage # Create your views here. def homePage(request): sign_in_detail=SignIn message_detail=DropUsaMessage return render(request, "index.html",{"form":sign_in_detail,"forms":message_detail}) def SignIn(request): sign_in_detail=SignInForm() if request.method == 'POST': sign_in_detail = SignInForm(request.POST) if sign_in_detail.is_valid(): return render(request, "index2.html",{"form":sign_in_detail}) else: sign_in_detail = SignInForm() # "form":sign_in_detail return render(request, "index.html",{}) def Contact(request): message_detail=DropUsaMessage() if request.method == 'POST': message_detail = DropUsaMessage(request.POST) if message_detail.is_valid(): return homePage(request) else: message_detail = DropUsaMessage() # "forms":message_detail return render(request, "index.html",{"forms":message_detail}) app/urls.py from django.urls import path from . import views urlpatterns=[ path('', views.homePage), ] app/forms.py from django import forms from django.core import validators class SignInForm(forms.Form): email=forms.EmailField(widget=forms.EmailInput(attrs={"class": 'form-control',"placeholder":'Enter E-mail',"id": 'exampleInputEmail1'})) password=forms.CharField(widget=forms.PasswordInput(attrs={"class":'form-control',"placeholder":'Enter Password',"id":'exampleInputPassword1'})) class DropUsaMessage(forms.Form): name = forms.CharField(widget=forms.TextInput(attrs={"class":'form-control',"placeholder":'Your Name'})) email = forms.EmailField(widget=forms.EmailInput(attrs={"class": 'form-control',"placeholder":'Your E-mail',"id": 'exampleInputEmail1'})) phone = forms.IntegerField(widget=forms.NumberInput(attrs={"class":'form-control',"placeholder":'Your Phone Number'})) message = forms.CharField(widget=forms.Textarea(attrs={"class":'form-control',"placeholder":'Type Your Message',"style":'width:100%; height: 150px'})) index.html <div class="container-fluid"> <div class="row"> <div class="col-md-8"> <img src="{% static 'img/sampleImage.jpg' %}" width="100%" height="100%" class="d-inline-block align-top" alt=""> </div> <div class="col-md-4"> <form method="POST"> {% csrf_token %} {{ … -
How to Solve KeyError in View Django
When I attempt to render a view, I am getting an error message 'KeyError at /manifest'. I am working with sessions for the first time so I'm not sure how to troubleshoot this issue. I'm trying to achieve passing a field 'reference' from the edit_manifest_frombrowse view to the manifest view using sessions. Could someone explain to me what is prompting this error and why I might fix it? Code and full traceback below: views.py def edit_manifest_frombrowse(request, pk): item = get_object_or_404(Manifests, pk=pk) if request.method == "POST": form = CreateManifestForm(request.POST, instance=item) if form.is_valid(): request.session["reference"] = form.cleaned_data["reference"] return redirect('manifest') else: form = CreateManifestForm(instance=item) return render(request, 'edit_manifest_frombrowse.html', {'form': form}) def manifest(request): form = CreateManifestForm(request.POST) if request.method == "POST": ... reference_id = request.session.pop('reference') ... return render(request, 'manifest_readonly.html', context) forms.py class CreateManifestForm(forms.ModelForm): class Meta: model = Manifests fields = ('reference', 'cases', 'product_name', 'count', 'CNF', 'FOB') FULL TRACEBACK Request Method: GET Request URL: http://127.0.0.1:8000/manifest Django Version: 1.11 Python Version: 2.7.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'bootstrap_modal_forms', 'smart_selects', 'unit'] 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.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, … -
Loping via Bootstrap in Django
I want to loop via a div with class="table_cell", whenever the loop reaches 3, I will like to have another div with class="table_cell", which means, I need new div with class="table_cell" for every 3 every products in my loop. I want to loop via a div with class="table_cell", whenever the loop reaches 3, I will like to have another div with class="table_cell", which means, I need new div with class="table_cell" for every 3 every products in my loop. <div class="table_row"> <!-- - - - - - - - - - - - - - Product - - - - - - - - - - - - - - - - --> {% for product in featured %} <div class="table_cell"> <div class="product_item"> <!-- - - - - - - - - - - - - - Thumbmnail - - - - - - - - - - - - - - - - --> <div class="image_wrap"> <img src="{% if product.image %}{{ product.image.url }}{% else %}{% static "img/no_image.png" %}{% endif %}" alt="{{ product.name }}"> <!-- - - - - - - - - - - - - - Product actions - - - - - - - - - - - … -
Django http://127.0.0.0:8000 not displaying results from new Prod/App View
I'm learning Django. I created the following Projects/Apps first_project first_app (Hello World - in view) ProTwo AppTwo (My Second App - in view) The apps just display text at the moment from the views. Both are set up exact same way. In the first_project I ran python manage.py runserver and when I go to http://127.0.0.1:8000 I see the hello world. In the AppTwo I ran python manage.py runserver also but when I go to http://127.0.0.1:8000 I still get hello world. How do I resolve this so I display "My Second App" in the browser instead of "Hello World"?. I've followed the steps in the course including information here https://www.tutorialspoint.com/django/django_creating_project.htm It is showing results from first Proj/App -> Hello World and NOT "My Second App"