Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make username field to accept email in django?
I have a Django application that accepts username to login to the application. I want to change it from username to email, without using a custom user model. Here i am using the Django's in built user model and now i don't want to change it. How can i do that? -
django - Unsupported lookup for JSONField or join on the field not permitted
I am having a Json field in my models as - class Product(models.Model): ... detailed_stock = JSONField(load_kwargs={'object_pairs_hook': collections.OrderedDict},default=dict) I am having values in my database like - { "total":0, "5[1]":0 } I am trying to filter objects with total = 0, for that I tried - Product.objects.filter(detailed_stock__total = 0) but it throws error - Unsupported lookup 'total' for JSONField or join on the field not permitted. as per the documentation the following code is permitted. this is full traceback- Traceback (most recent call last): File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\core\handlers\exception.py", line 35, in inner response = get_response(request) File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\views\generic\base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\braces\views\_access.py", line 102, in dispatch request, *args, **kwargs) File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\views\generic\base.py", line 89, in dispatch return handler(request, *args, **kwargs) File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\views\generic\list.py", line 142, in get self.object_list = self.get_queryset() File "c:\Users\lenovo\Desktop\My_Django_Stuff\bekaim\accounts\views.py", line 142, in get_queryset queryset = Product.objects.filter(detailed_stock__total = 0) File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\db\models\query.py", line 836, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\db\models\query.py", line 854, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\db\models\sql\query.py", line 1253, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\lenovo\AppData\Local\conda\conda\envs\myDjangoEnv\lib\site-packages\django\db\models\sql\query.py", line 1271, in _add_q current_negated, allow_joins, … -
static file are not loading in templates django
i am very new to django . m adding static files but they are not being shown in m templates when i runserver. if i add an static image the image does not load but only shows a img icon. #settings.py STATIC_DIR=os.path.join(BASE_DIR,"static") STATIC_URL = '/static/' STATICFILES_DIR=( STATIC_DIR, ) #INDEX.HTML <!DOCTYPE html> {% load staticfiles %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <h1>hey eeyone</h1> <img src="{% static "images/hotel.jpg" %}"> </body> </html> -
javascript code not working for external file
i have javascript code that send data to backend which when i place inline then work fine but when i place in external file it does not work.meanwhile other javascripts is working in external file. <script> $('#submit-ajax').click(function(event) { console.log('working or not') $.post( '/order/detail/', { 'test': 'hi i am here', }, function() { alert( "Data Loaded: " ); } ) }); </script> in external file code is: $(document).ready(function(){ $('#submit-ajax').click(function(event) { console.log('working or not') $.post( '/order/detail/', { 'test': 'hi i am here', }, function() { alert( "Data Loaded: " ); } ) }); } -
How to call 'set password' in Django using a fetch request - issue with csrfmiddlewaretoken?
I'm trying to create a 'reset password' function in my Django / React app. I'm using django-contrib-auth for the back end and most of this is working OK. However I can't get the POST request right in order to actually update the password. Here's the workflow. The user clicks a "forgot password" link and is shown a form where they enter their email address. They receive an email containing a link to click. They click the link and visit a page where they enter their new password twice and click "Submit". This is where the problem lies. If I use the built-in form generated by django-contrib-auth, the password is reset correctly. But I want to use a form generated by React, and in that page I'm sending a fetch request to the same endpoint. Here's a fetch request generated by the form which works: curl 'http://localhost:8000/api/v1/reset/Mw/set-password/' -H 'Cookie: meteor_login_token=OG2fh2iVTkn5AOujhdaBXCsetV-CQ1lS6ZLdtrtzFYC; csrftoken=uSEF8NQB0lUpimwfQcOWLt118igo0bQq2gbpTaGq7zvgQMeF4oM2cu3ZwfgmuDOa; sessionid=39awyoab3wouvxmacbzbxez2hrfoa498' -H 'Origin: http://localhost:8000' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: en-GB,en-US;q=0.9,en;q=0.8' -H 'Upgrade-Insecure-Requests: 1' -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36' -H 'Content-Type: application/x-www-form-urlencoded' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8' -H 'Cache-Control: max-age=0' -H 'Referer: http://localhost:8000/api/v1/reset/Mw/set-password/' -H 'Connection: keep-alive' --data 'csrfmiddlewaretoken=ASbYGmwXWOTKagND1hWHK0DQt5Qo9MPq8gIIrJmM32uBIGv3ftUNb1FOR2QmDeNa&new_password1=sometext&new_password2=sometext' --compressed Here's my fetch request that … -
Accessing django template's dictionaries given a variable?
My question is if there's a way to obtain a value of a dictionary given a key. For example, imagine that my_dictionary is {1:'a', 2:'b', 3:'c'}and I have an attribute which is key which equals 1. How can I obtain 'a'? I tried with {{my_dictionary.key}}and {{my_dictionary.{{key}} }}but none of them worked. My idea is to do the same as with python, which is my_dictionary[key] but in a Django Template. Thank you -
Exclude And Operations Conditions Django
i want to AND and put all exclude query in one exclude function. User.objects.exclude(role_title='Super Admin').exclude(user_is_deleted = False) Above i have two exclude instead i want one User.objects.exclude(role_title='Super Admin', user_is_deleted = False) But it is not working in my view -
submit selected fields in many-to-many relation
I created a node and scheduled action models with manyTomany relation: class Node(models.Model): name = models.CharField(default='node', max_length=32) nb_solenoid = models.DecimalField(max_digits=19, decimal_places=10, null=True, blank=True) connexion = models.CharField(max_length=255) class ScheduledAction(models.Model): date = models.DateTimeField(default=datetime.now, blank=True) firm = models.ForeignKey('firme.Firme', on_delete=models.CASCADE, null=True, blank=True) node_ids = models.ManyToManyField(Node) In forms.py: class ScheduledActionForm(forms.ModelForm): date = forms.DateTimeField() firm = forms.ModelChoiceField(queryset=Firme.objects.all()) node_ids = forms.ModelMultipleChoiceField(queryset=Node.objects.filter(), widget=forms.CheckboxSelectMultiple) class Meta: model = ScheduledAction fields = [ 'date', 'firm', 'node_ids' ] in views.py: def planification_view(request): scheduledAction = ScheduledActionForm(request.POST or None) nodes = Node.objects.all() if scheduledAction.is_valid(): scheduledAction.save() print('formulaire enregistre') scheduledAction = ScheduledActionForm() context = { 'form': scheduledAction, 'nodes': nodes } return render(request, "node/planification.html", context) The view works fine but how many nodes I check it always saves all the nodes in the many-to-many field. How can I make it only submit selected fields? -
AttributeError at /accounts/signup/ 'str' object has no attribute 'add'
Am new using django so i used practical example on this tutorial on extending user model using User Profile, am having trouble on form.py it gives that error, on removing this line; supervisor.su_mobile_number.add(*self.cleaned_data.get('su_mobile_number')) it works smoothly but no data for su_mobile_number was inserted o the database view.py class SupervisorSignUpView(CreateView): model = User form_class = SupervisorSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'supervisor' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('home') model.py class User(AbstractUser): is_supervisor = models.BooleanField(default=False) is_student = models.BooleanField(default=False) class Supervisor(models.Model): user = models.OneToOneField('User', on_delete=models.CASCADE, primary_key=True, related_name='supervisor') su_mobile_number = models.CharField(max_length=200) forms.py class SupervisorSignUpForm(UserCreationForm): su_mobile_number = forms.CharField() class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_supervisor = True user.save() supervisor = Supervisor.objects.create(user=user) supervisor.su_mobile_number.add(*self.cleaned_data.get('su_mobile_number')) return user -
Models.py Issue (Keys)
I'm trying to make a basic web application for as a small project and I'm facing an issue where whenever I use any type of relationship between 2 attributes. Like when I try to pull some data from another table, it gets displayed as "Person object(1)" or "project object(1)". How do I ensure that this doesn't happen and the name of the person and the name of the project shows up? Im also willing to accept any sort of help with improving my database codes.. Thank you in advance. Attached below is the source code. When I try to pull some data from another table, it gets displayed as "Person object(1)" or "project object(1)". How do I ensure that this doesn't happen and the name of the person and the name of the project shows up? from django.db import models from django.db import models from django.contrib.auth.models import User, Group from django.db import models from django.core.mail import EmailMessage from django.contrib import admin class Project(models.Model): STATUS_CHOICE = ( ('Work Assigned', 'Work Assigned'), ('Work in Progress', 'Work in Progress'), ('Testing', 'Testing'), ) project_name = models.CharField(max_length=100) project_description = models.CharField(max_length=100) status_of_the_project = models.CharField(max_length=18, choices=STATUS_CHOICE) created = models.DateTimeField(auto_now_add=True, null=True, blank=True) finish_date = models.DateTimeField(null=True, blank=True) supporting_documents = … -
enumeration and capping items within either inlineformset_factory or modelformset_factory in Django
I have something that looks like this: https://imgur.com/gallery/9pnbBmJ and aside from adding a bit of "CSS/HTML makeup" I'm stuck here at the very last step of the very last leg of the project before I need to start looking into production settings and the like. Now, according to https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#inline-formsets (quite at the bottom; "Using an inline formset in a view") it should be possible to mass produce class objects, and it is, it would appear. I believe I'm on the right track, but I'm no expert in neither Python nor Django, unfortunately. What I'm trying to do is to: 1) limit/cap the objects to 9 items per user each of which may be edited later if the user should wish to do so, and 2) enumerate those items, ie. "(1), (2) ... (9)" so that I may avoid receiving the embarrasing MultipleObjectsReturned at /user/vulpes/ - get() returned more than one Gallery -- it returned 2! error. I've commented out some things: Firstly there's the matter of the modelformset_factory VS inlineformset_factory. I don't really know which to chose as the former returns one image per user whilst respecting the cap, while the latter returns many an image not respecting the cap … -
celery task status showing pending
I am working with celery and i am getting tasks status is pending, may be it is implementation problem. please check my code. I am trying to save task info like id, name, status in my mongodb database, for this i am using a function which my task will call to save data in mongodb. Am i getting my task pending because my function call is happening before return statement of task? settings.py CELERY_BROKER_URL = 'mongodb://localhost:27017/jobs' CELERY_RESULT_BACKEND = "mongodb" CELERY_IGNORE_RESULT = False CELERY_TRACK_STARTED = True CELERY_MONGODB_BACKEND_SETTINGS = { "host": "127.0.0.1", "port": 27017, "database": "jobs", "taskmeta_collection": "my_taskmeta_collection", } CELERY_BEAT_SCHEDULE = { 'add-every-minute-contrab': { 'task': 'username_length_periodically', 'schedule': crontab(minute='*/1'), #'args' : (2,3), }, } CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE celery.py from __future__ import absolute_import, unicode_literals import os, logging from celery import Celery from celery.schedules import crontab # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'RestUserAPI.settings') app = Celery('UserAPI') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app … -
How does AUTH_LDAP_REQUIRE_GROUP work in django?
I am using following block of code , I copied from web : AUTH_LDAP_REQUIRE_GROUP = "cn=GALAXY_login,ou=AppRoles,ou=GALAXY_TEAM,ou=Applications,o=IAM" AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active":"cn=GALAXY_login,ou=AppRoles,ou=GALAXY_TEAM,ou=Applications,o=IAM", "is_staff": "cn=GALAXY_login,ou=AppRoles,ou=GALAXY_TEAM,ou=Applications,o=IAM", "is_superuser":"cn=GALAXY_superuser,ou=AppRoles,ou=GALAXY_TEAM,ou=Applications,o=IAM" } If i am only allowing GALAXY_login to login into application how will "is_superuser":"cn=GALAXY_superuser,ou=AppRoles,ou=GALAXY_TEAM,ou=Applications,o=IAM" ever return true? My understanding is , I am only permitting the user which is in group GALAXY_login. Then how will "is_superuser" be true for any user? -
'User' object has no attribute 'soft_delete' - Django Soft Deletion
i have created soft delete in my project and it is working fine. But the problem is that i am using User in-built model and OneToOneField with UserProfile. Now soft_delete function is in UserProfile Model where im using generic.DeleteView to delete user. The problem is that i could not pass object of User to UserProfile to set user_is_deleted to True. Here is my Code. Views.py class UserDeleteView(LoginRequiredMixin, generic.DeleteView): model = User template_name = 'users/user_confirm_delete.html' success_url = '/users/' def delete(self, request, *args, **kwargs): self.object = self.get_object() self.object.soft_delete() return HttpResponseRedirect(self.get_success_url()) Models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_company = models.ForeignKey(Company, on_delete=models.CASCADE) user_role = models.ForeignKey(Roles, on_delete=models.CASCADE) user_is_deleted = models.BooleanField(default=False) user_deleted_at = models.DateTimeField(blank=True, null=True) def soft_delete(self): self.user_is_deleted = True self.user_deleted_at = timezone.now() - tdelta(days=-1) self.save() -
You have 1 unapplied migration(s)
I cannot able to search and migrate the 1 unapplied ...help me out -
Get HTML and CSS from grapes.js newsletter editor in Javascript
How to get output HTML and CSS of grapes.js in Javascript ? I am writing a Django app for newsletter, in which i need a newsletter editor for which i used "grapes.js" newsletter. Everything is fine but i am stuck in part where i need to get the HTML and CSS of the template created with it. I have: <script type="text/javascript"> var editor = grapesjs.init({ container : '#gjs', plugins: ['gjs-preset-newsletter'], pluginsOpts: { 'gjs-preset-newsletter': { modalTitleImport: 'Import template', 'grapesjs-plugin-export': { /* options */ } // ... other options } } }); function returnHtml(){ console.log('test') const mjml = editor.getHtml; preview = editor.getHtml $("#myiframe").contents().find("body").html(mjml) } returnHtml(); This code gives me the html of the template but without the css ! i have tried https://github.com/artf/grapesjs-mjml/issues/2. Can someone please suggest me what i am missing ? Thanks. -
What are the difference between django structure in different project scale
How we implement Django on different scale project: fro single app, Medium size app, large apps and enterprise app? -
Django - 'User' object is not iterable
When i am passing instance1 in context it giving error 'User' object is not iterable. I want to display Name in Template of pk. Example http://localhost:8000/users/15/profile-update/ pk=15 def userProfileUpdate(request, pk): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=User.objects.get(id=pk)) p_form = UserProfileForm(request.POST, request.FILES, instance=UserProfile.objects.get(user_id=pk)) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, 'Profile Updated!!!') return redirect('users') else: instance1 = User.objects.get(id=pk) u_form = UserUpdateForm(instance=User.objects.get(id=pk)) p_form = UserProfileForm(instance=UserProfile.objects.get(user_id=pk)) context ={ 'object': instance1, # This is giving the error 'u_form': u_form, 'p_form': p_form } return render(request, 'users/userprofile.html', context) -
Changing error messages in django-rest-auth
Whenever I make a POST request with an empty username value, I get the following error message: "username": [ "This field may not be blank." ], I'd like to change this error message to my own custom error message. However, in my User model I try to create a blank error message like so: class User(AbstractBaseUser): username = models.CharField(max_length=15, unique=True, error_messages={ 'blank': 'You have to have a username!', 'unique': "Username has already been taken.", }) However, this error message does not show, instead the default error message shows. How can I show my own custom error message? The unique error message shows up fine, it's just the blank one doesn't show up. -
sshtunnel.BaseSSHTunnelForwarder Could not establish session to SSH gateway
I am using django with mysql database to develop apis. Now I got a new requirement to connect mongodb database with django. I have used following solution from sshtunnel import SSHTunnelForwarder import pymongo import pprint MONGO_HOST = "REMOTE_IP_ADDRESS" MONGO_DB = "DATABASE_NAME" MONGO_USER = "LOGIN" MONGO_PASS = "PASSWORD" server = SSHTunnelForwarder( MONGO_HOST, ssh_username=MONGO_USER, ssh_password=MONGO_PASS, remote_bind_address=('127.0.0.1', 27017) ) server.start() client = pymongo.MongoClient('127.0.0.1', server.local_bind_port) # server.local_bind_port is assigned local port db = client[MONGO_DB] And now I am getting following sshtunnel.BaseSSHTunnelForwarderError: Could not establish session to SSH gateway Is it good way to connect mongodb in django poject? -
Push notification in django rest
I am working on a attendance registration system where a user of an office can make a leave request. When any user makes a leave request, it must be notified to admin. How do I implement it ? I had seen django-fcm for push notification. But I am using django rest framework . Can I implement django-fcm with django rest ? If any tutorials link would be more helpful -
Unable to view content in DetailView Django
I am trying to view the content in my blog posts using django DetailView class but when I run the local server and click on the headline link in my blog post, while the url bar changes to read the correct post, the actual page stays the same, and so I can't view individual blog posts. Here is the section of code were the problem lies. #view.py class PostListView(ListView): model = Post template_name = 'post_list.html' class PostDetailView(ListView): model = Post template = 'post_detail.html' #urls.py urlpatterns = [ path('post/<int:pk>', PostDetailView.as_view(), name='post_detail'), path('', PostListView.as_view(), name='post_list'),] #post_list.html {% for post in post_list %} <h2><a href="{% url 'post_detail' post.pk %}">{{ post.title }}</a></h2> <p> {{ post.tagline }} </p> -
id(number) path in urls
I am new to django In urls.py, I set path like this. I tried to create a page with urls: localhost:8000/topics/1/ urlpatterns = [ path('topics/(?P<topic_id>\d+)/', views.topic, name='topic'), ] In views.py. Code is this: def topic(request, topic_id): """Show a single topic and all its entries""" topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('date_added') context = {'topic': topic, "entries": entries} return render(request, 'learning_logs/topic.html', context) I got error 404 when enter localhost:8000/topics/1/. topics/(?P\d+)/ [name='topic'] The current path, topics/1/, didn't match any of these. But the correct urls turns out to be: localhost:8000/topics/(%3FP1%5Cd+)/ Is there something wrong with the path in urls or what's the problem? -
How to limit fields returned in django queryset per field
I have rows of products, that tend to share some information, such as the same images (an image may show multiple products), descriptions, manufacturer, etc. I would like to choose some fields to only show the information once. I can't use distinct for this (I don't think) as the information is not always identicle, such as with the description, but may be only subtly different enough that I don't want to repeat it. At the moment, I am using a for loop to display fields from each result, which ends up with something like this: This is the code I am using in my view: def collection_detail(request, name=None): template = loader.get_template('/webapps/mywebapp/furniture/main_page/templates/main_page/detail.html') products = product.objects.filter(id=name) cart_product_form = CartAddProductForm() context={'products': products, 'cart_product_form': cart_product_form} return HttpResponse(template.render(context)) What would be the appropriate way to do this in a view, ignoring subsequent rows for some fields? -
AttributeError: 'CloudWatchLogHandler' object has no attribute 'shutting_down' while deploying django-rest-api into aws
i have deployed my django-rest-api application into aws using zappa. its working fine but sometimes i'm getting error like AttributeError: 'CloudWatchLogHandler' object has no attribute 'shutting_down'(im using watchtower for logging in aws).please help me out in settings.py for logs : from boto3.session import Session import logging boto3_session = Session(aws_access_key_id=S3_ACCESS_KEY_ID, aws_secret_access_key=S3_SECRET_ACCESS_KEY, region_name=S3_REGION) LOGGING = { 'version': 1, 'disable_existing_loggers': False, # 'root': { # 'level': logging.ERROR, # 'handlers': ['console'], # }, 'formatters': { 'simple': { 'format': u"%(asctime)s [%(levelname)-8s] %(message)s", 'datefmt': "%Y-%m-%d %H:%M:%S" }, 'aws': { # you can add specific format for aws here 'format': u"%(asctime)s [%(levelname)-8s] %(message)s", 'datefmt': "%Y-%m-%d %H:%M:%S" }, }, 'handlers': { 'watchtower': { 'level': 'INFO', 'class': 'watchtower.CloudWatchLogHandler', 'boto3_session': boto3_session, 'log_group': 'test_logs_group', 'stream_name': 'test_stream_name', 'formatter': 'aws', }, }, 'loggers': { 'django': { 'level': 'INFO', 'handlers': ['watchtower'], 'propagate': False, }, # add your other loggers here... }, } i kept that code in settings.py for logging using watchtower in cloudwatch