Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, syntax for insering Javascript to template
I would like to embed Bokeh plot in Django template using Json output. http://bokeh.pydata.org/en/latest/docs/user_guide/embed.html#json-items Json output is ready for query in database. Plot should be rendered to div with specific ID. Documentation says to use Json output in template with following code function: item = JSON.parse(item_text); Bokeh.embed.embed_item(item); Please advise the correct syntax for use in template: <div id="title"></div> <script> function(response) { return item = JSON.parse( {{plot_json}} ); } function(item) { Bokeh.embed.embed_item(item); } </script> -
how to solve redirection in django auth is not working
here is my code everything is working fine but when i tried to login and hit on login button nothing happens. my login page didn't redirect me on any page. Login page coding. {% extends 'authenticate/base.html' %} {% block content%} <h1 class="text-center">Login </h1> <div class="col-md-6 offset-md-3" <form method="POST"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control" placeholder="Enter UserName" name="username"> </div> <div class="form-group"> <input type="password" class="form-control" placeholder="Password" name="password"> </div> <button type="submit" class="btn btn-secondary">Login</button> </form> </div> {% endblock %}` Views.py page coding. from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout def home(request): return render(request, 'authenticate/home.html',{}) def login_user(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: return redirect('login') else: return render(request, 'authenticate/login.html', {}) Base.py page coding. <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link" href="{%url 'login'%}">Login</a> </li> </ul> </div> -
Django - show to user an object corresponding to the current url
apologies for the misleading title; let's say I've got this kind of link: <div class="col-md-3"> <a class="btn btn-success" href="{% url 'rental-create' car.pk %}">Order this car!</a> </div> which leads to a view I use to process ordering my cars class RentalCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): form_class = RentalCreateForm template_name = 'rentals/rental_create.html' success_message = 'Created' context_object_name = 'order' def get_success_url(self): return reverse('rental-detail', kwargs={'pk': self.object.pk}) def form_valid(self, form): form.instance.profile = self.request.user.profile car = Car.objects.get(pk=self.kwargs['pk']) form.instance.car = car return super().form_valid(form) now I would like to simply use my object (car) pk in the template or directly in the form I've defined above. As you can see, I've managed to access this variable in my form_valid method: car = Car.objects.get(pk=self.kwargs['pk']) however, this mechanism only ensures that after saving an instance to the database, the car would be the same as in the requested url. My point is to use the car object (which corresponds to url like /rental/new/1/) in the template, or as the non-editable form field. in brief - I would like to show user the current car he is ordering. here is my forms.py class RentalCreateForm(ModelForm): class Meta: model = Rental fields = ('start_date', 'end_date', 'additional_info',) exclude = ('profile', 'paid') widgets = { 'start_date': DateInput(), … -
Django_filters Filtering Dates not working
I'm creating a filter using django_filters. I want to filter for a date range but it's not working. My filter ignores my start_date and my end_date. Here's my filters.py: class ArticleFilter(django_filters.FilterSet): date_range = django_filters.DateRangeFilter(field_name='pub_date') start_date = django_filters.DateTimeFilter(field_name="pub_date", lookup_expr="gt", widget=widgets.DateInput(attrs={"class": "datepicker"})) end_date = django_filters.DateTimeFilter(field_name="pub_date", lookup_expr="lt", widget=widgets.DateInput(attrs={"class": "datepicker"})) btw. pub_date is a DateTimeobject. -
Use URL to set model as true or false
I have a todo APP and I would like to have a link where the user can click and set the "todo" as complete without deleting it from my database. I use CBV but cannot figure out how do it : I tried views.py : class TodoDeleteView(LoginRequiredMixin, DeleteView): model = Todo success_url = '/' template_name = 'dashboard/dashboard_confirm_delete.html' def completeTodo(request, todo_id): todo = Todo.objects.get(pk=todo_id) todo.complete = True todo.save() But it delete it from my DB and it does not set it to true. My models.py class Todo(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name="Nom de l'utilisateur") text = models.CharField(max_length=150, verbose_name="Nom de la Todo") complete = models.BooleanField(default=False) -
Difference between overriding save() vs create() in Django Models
What is the difference between overriding Django's def save(self, *args, **kwargs): super(MyModel, self).save(*args, **kwargs) and def create(self, **kwargs): kwargs['field'] = processed_data(kwargs['other_field']) return super().create(**kwargs) method to save data in Django models? Pretext So, I have a model from which I am not only creating new values but also updating old values. I want to know why and when are these methods overridden because whenever an entry is updated I am keeping track of the old and the new value in another shadow table so that I can show any user when, how and by what medium the values of the table were changed. Thanks in advance :) -
Django QuerySet returns nothing
I have a list of countries, they all have there own url www.example.com/al/ for example. There is a list of cities for every country but the object_list is empty My View: class CityOverview(generic.ListView): template_name = 'shisha/pages/country_index.html' model = City def get_queryset(self, *args, **kwargs): country_id = self.kwargs.get('country_id') return City.objects.filter(country__name=country_id) My Model: class Country(models.Model): COUNTRY_CHOICES = ( ('al', 'Albania'), ('ad', 'Andorra'), #etc. etc. ) name = models.CharField(max_length=255, choices=COUNTRY_CHOICES, default='nl') def __str__(self): return self.name class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=250) def __str__(self): return self.name My Urls: path('<str:country_id>', views.CityOverview.as_view(), name='country'), My Template: {{ object_list }} It returns an empty QuerySet <QuerySet []> Does anyone know what the problem is? -
Crispy-Forms: Better control over checkbox css within a CheckboxSelectMultiple
I am using Cripsy forms and have a ModelMultipleChoiceField using a CheckboxSelectMultiple. However, the checkboxes render at standard checkboxes and I need to add some css to the checkbox field ('custom-control-input') to get it to render like the rest of my bootstrap checkboxes. Any ideas on where to start? class CustomPermissionMultipleChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return "%s" % obj.name class UserPersonalInfoEdit(forms.ModelForm): permission_codename_list = ( 'can_view_admin', 'change_retailer', 'change_website', 'change_rating', 'change_contract', 'view_contract', ) user_permissions = CustomPermissionMultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, queryset=Permission.objects.filter(codename__in=permission_codename_list)) class Meta: model = CustomUser fields = ['first_name', 'last_name', 'email', 'username', 'user_permissions'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'POST' self.fields['first_name'].required = True self.fields['last_name'].required = True self.fields['email'].required = True self.fields['username'].help_text = None self.fields['is_active'].help_text = None self.helper.layout = Layout( Row( Column('first_name', css_class='form-group col-md-4 mb-0'), Column('last_name', css_class='form-group col-md-4 mb-0'), Column('username', css_class='form-group col-md-4 mb-0'), ), Row( Column('email', css_class='form-group col-md-4 mb-0'), ), HTML('<hr>'), Row( Column('user_permissions', css_class='form-group col-md-4 mb-0'), ), HTML('<hr>'), Submit('submit', 'Save'), HTML('<a class="btn btn-primary" href="{% url "core:user_list" %}" role="button">Close</a>') ) -
How to add list data in choices in django forms?
I have list, l = [1,2,3,4,5,6]. Now I want to show this list in django admin form as a dropdown. list_data = forms.charField(choices = l) How to perform this? -
Overriding clean function not being called/
The documentation says (which I have done) The clean_() method is called on a form subclass – where is replaced with the name of the form field attribute. Next it is telling me that I should do (i believe i have done so) You will need to look up the value of the field in self.cleaned_data My Form class CreatePostForm(forms.ModelForm): class Meta: model = Post fields = ( 'title', 'text', ) def clean_text(self): data = self.cleaned_data['text'] print(data) #check if word count is <30 if len(data.split()) < 30: raise forms.ValidationError(('Please write at least 30 words,\ %(count)s words is not long enough'), params={'count':count}) return data My View @login_required def create_new_post(request): if request.method == 'POST': form = CreatePostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.created = timezone.now() post.save() return redirect('post-detail', pk=post.pk) else: form = CreatePostForm() return render(request, 'journal/create_post.html', {'form':form}) So I tried printing to see if the function is even being called, but nothing was being printed in the console. Can anyone explain what I am doing wrong? Why is this happening? -
How to add favicon to django app with React front end
I'm building a Django app with a React front end, built using react-create-app. I can't get the favicon to show up in production. I'm using Django 2.10.0. When I build the React app, the build output files are put in the assets/static/ folder. This includes image files used as backgrounds via css, and all works fine. These are included in the build because they are referenced in the stylesheets. The favicon is referenced from index.html and therefore isn't picked up by the build process. However I don't know how to get the server to serve up the favicons. If I put them in the frontend/public folder, the Django server doesn't find them. If I manually copy them into the static/ folder, they show up but that folder is managed by Webpack and the contents are removed when the app is built. Copying the favicons into the project root doesn't work. They are in the same folder as index.html, which is served up, but Django server won't serve those co-located image files. The only documentation I can find deals with either Django or create-react-app; I can't find anything that explains how to tie them together for favicons. In settings.py: STATIC_URL = … -
How do I set a ManyToMany field on post_save of a model?
I have a model, say, Ticket. The Ticket has Tag as ManyToMany field among the other fields. After somebody updates any field of Ticket (say Description), I want to set the Tag field value to one of the existing tags. How do I do this? -
Python (Django) Get Response API Not working
New to this forum, HI to all. Learning web development as well, so apologies in advance if this is a easy find. My code is unable to POST data to Get Response: Getting authentication errors on the headers (Response on terminal). Have spoken with GR and they can see the traffic but advising that the code is wrong. Here is the POST code: import requests from django.db import models from elissa.functions import get_async_web_response, get_async_web_response_no_decode def post_lead(self): data = '{ "name": "' + self.first_name + '", "email": "' + self.email + '", "campaign": { "campaignId": "xxxxx" }, "ipAddress": "' + self.ip + '", }' headers = {"X-Auth-Token": "api-key xxxxxxxxxxxx","Content-Type": "application/json"} get_async_web_response_no_decode("https://api.getresponse.com/v3/contacts", "POST", data=data, headers=headers) print "post lead data: " + data headers = requests.post('https://api.getresponse.com/v3/contacts') print headers.content response = requests.get('https://api.getresponse.com/v3/contacts') print response.content Hope you can help, and please do let me know if you need further information. Cheers -
Invoke AWS Lambda function that is Written in Django App
I have written some cronjobs in my django app and I want to schedule these jobs using AWS Lambda service. Can someone please recommend a good approach to get this done? -
is there a form validation like laravel in django?
Laravel has an easy option to do server-side validation using $validator object. Is there any similar approach in Django. -
django.core.exceptions.ImproperlyConfigured: WSGI application could not be loaded; Error importing module
I have tried every solution proposed to solve this error but nothing seems to work. I have copied the application from GitHub and installed it locally. WSGI.py: import os import sys from django.core.wsgi import get_wsgi_application ##from whitenoise.django import DjangoWhiteNoise sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(file), "../../"))) sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(file), "../"))) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myprogram.settings") application = get_wsgi_application() ##application = DjangoWhiteNoise(application) Settings.py: from django.utils.translation import ugettext_lazy as _ import os #from . import custom_storages # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ‘XXXX’ # SECURITY WARNING: don't run with debug turned on in production! ########## #Use True on your local PC, False on Heroku!! ######## #DEBUG = True DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'myprogram.service_development.apps.ServiceDevelopmentConfig', 'storages', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', #TODO: disabled csrf middleware, is this usable with voiceXML? #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'myprogram.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', ], }, }, ] WSGI_APPLICATION = 'myprogram.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': … -
How to add a function after a record inserted in database using django admin?
I want to execute a function after a record inserted to database using django-admin panel . I have a product table , i want to send notification to users when a record inserted in database by django admin panel . i know how to send notification to users , but i dont know where to put my code . any suggestion will be helpfull . How can i execute a function to notify user after my record inserted ? here is my code to execute after record inserted : from fcm_django.models import FCMDevice device = FCMDevice.objects.all() device.send_message(title="Title", body="Message", icon=..., data={"test": "test"}) i searched alot but not found anything usefull . thanks to this great communtiy . -
Django user account delete and then return redirect and render
I want to allow a user to delete his account and upon deletion, I want the user to be logged out and see a html page account_deleted.html for confirmation. students/views.py: def delete_account(request): user = User.objects.get(username=request.user) user.delete() context = { "deleted_msg": "Account has been deleted", } return render(request, "students/account_deleted.html", context) and redirect("students:logout") For logout, I'm using the built-in LogoutView function. The logout redirect URL in my settings.py is set to my home page. students/urls.py: path('logout/', LogoutView.as_view(), name='logout'), In case of an account deletion, how can I make the delete_account(request) function return a render and redirect at the same time? Is that even possible? Thanks! -
Cannot import ASGI_APPLICATION module 'myproject.routing'
I've followed the channels 2 tutorial, but I'm getting this error after running py manage.py runserver File "C:\Users\Mach2\AppData\Local\Programs\Python\Python37-32\lib\site-packages\channels\routing.py", line 35, in get_default_application raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'channels_test.routing' -
Create Django "Sub Admin" to access related to single company users
I am building a Django app which can be used by multiple companies. Now I have set up the common(super) admin, which can look every users and model. I am storing all the company details on the company table. Suppose we've 3 companies - A, B and C. I want to create 3 sub-admins for each company, where they can only see/edit all the data related to their company users only. What I've tried already: I created permissions based on the models but they're not solving the purpose of accessing data from the only single company. Can anyone explain to me how this can be achieved? Either programmatically or from the admin portal. Tech Specs: Django 2.1 Python 3.6.4 PS: If you need more information, then please let me know. I will provide as much information as I can. Thank you. -
Django connecting to SQL SERVER
I am tryng to connect my project to the sql server. i was folling this steps, and already do everything but right now i allways have this error and i dont know what to do. My connection DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'HOST': 'xxx', 'NAME': 'xxx', 'USER': 'xxx', 'PASSWORD': 'xxx', 'PORT': '', 'OPTIONS': { # 'DRIVER={SQL Server Native Client 11.0}', }, }, } -
Reverse url is not working in djnago 1.6 inside middleware
reverse('settings:force_update'), this one is working in other places. But while trying to use it in one of the middleware. It saying that settings namespace is not defined. And for this reverse('force_update') No reverse found. -
Error with paginating the exact number of records as json result in django
My problem is that my returning json is not the expecting one based on the limit that I have given to my paginator. For example, when I am giving the limit 11 to define the number of my returning results per page, after the request the paginator returns only 10. This happens when I am requesting records above 10. Below 10 the json result is right. my view class ProductSerialNumbersListJSon(LoginRequiredMixin,BaseDatatableView): # my model model = ProductSerialNumbers columns = ['snumber' , 'order_id','product','registration_date'] order_columns = ['snumber','order_id','product','registration_date'] paginate_by = 11 def get_initial_queryset(self): #fetch the query list from db query_list=ProductSerialNumbers.objects.filter(Q(snumber__isnull=True)|Q(order_id__isnull=True)|Q (order_id__finished=0)).order_by("id") #declare the Paginator paginator = Paginator(query_list,self.paginate_by) #getting the page number from the kwargs of the url page=int(self.kwargs['page']) try: result = paginator.page(page) except PageNotAnInteger: result = paginator.page(1) except EmptyPage: result = paginator.page(paginator.num_pages) product_serials = result.object_list.all().values_list('pk', flat=True) result=ProductSerialNumbers.objects.filter(pk__in=list(product_serials)) return ProductSerialNumbers.objects.filter(pk__in=list(product_serials)) my json result {"recordsTotal": 11, "recordsFiltered": 11, "draw": 0, "data": [["3", "", "test_proion", "2019-01-16"], ["55", "", "test_proion", "2019-01-16"], ["56", "", "test_proion", "2019-01-16"], ["57", "", "test_proion", "2019-01-16"], ["58", "", "test_proion", "2019-01-16"], ["59", "", "test_proion", "2019-01-16"], ["60", "", "test_proion", "2019-01-16"], ["61", "", "test_proion", "2019-01-16"], ["62", "", "test_proion", "2019-01-16"], ["63", "", "test_proion", "2019-01-16"]], "result": "ok"} Despite the fact that the recordsTotal and the recordsFiltered variable are returning both … -
Django: How to annotate M2M or OneToMany fields using a SubQuery?
I have Order objects and OrderOperation objects that represent an action on a Order (creation, modification, cancellation). Conceptually, an order has 1 to many order operations. Each time there is an operation on the order, the total is computed in this operation. Which means when I need to find an attribute of an order, I just get the last order operation attribute instead, using a Subquery. The simplified code class OrderOperation(models.Model): order = models.ForeignKey(Order) total = DecimalField(max_digits=9, decimal_places=2) class Order(models.Model) # ... class OrderQuerySet(query.Queryset): @staticmethod def _last_oo(field): return Subquery(OrderOperation.objects .filter(order_id=OuterRef("pk")) .order_by('-id') .values(field) [:1]) def annotated_total(self): return self.annotate(oo_total=self._last_oo('total')) This way, when I run my_order = Order.objects.annotated_total()[0].oo_total, I get the order total amount, works great. The issue Computing total is easy as it's a simple value. However, when there is a M2M or OneToMany field, this method does not work. For example, using the example above, let's add this field: class OrderOperation(models.Model): order = models.ForeignKey(Order) total = DecimalField(max_digits=9, decimal_places=2) ordered_articles = models.ManyToManyField(Article,through='orders.OrderedArticle') Writing something like the following does NOT work as it returns only 1 foreign key (not a list of all the FKs): def annotated_ordered_articles(self): return self.annotate(oo_ordered_articles=self._last_oo('ordered_articles')) My current idea Maybe something like ArrayAgg (I'm using pgSQL) could do the trick, … -
How to send firebase notifications using django-admin panel or Admin account?
I'm Developing an android app in client side and django admin panel in server side , what i need to do is sending firebase notifications to single or all users , i have already registered android app to firebase . i know i should use django-fcm . i need a recomendation or any suggestion to make it right . can i have a page to send notifications to users that only admin account can access to it ? any suggestions will be helpfull . i searched alot but not found anything .