Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter a list of displayed elements in django with a dropdown value
Right now I have a list of forms being displayed by Django: {% for form in forms %} <form method="post" class="{{ form.css_class }}"novalidate> {% csrf_token %} {% include 'bs4_form.html' with form=form %} <input type="hidden" name="selected_form" value="{{ forloop.counter0 }}"> <button type="submit" class="btn btn-primary">Submit</button> </form> {% endfor %} I also have a dropdown being rendered above the forms: <label>Choose a component to modify: <select class="rule-component" name="component"> <option value="">Select One …</option> <option value="0">Option 0</option> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> <option value="4">Option 4</option> </select> </label> My question is, how would I go about displaying no form when the page is entered, and a single form that corresponds with the dropdown value when that is selected? I've attempted something with JavaScript, but I'm not very familiar with it and I'm not sure how to get this to interact with the django templating language. The code below allows me to log the form element I want to display by linking it with the forloop.counter: <script type="text/javascript"> const formElement = document.querySelector(".rule-component") formElement.addEventListener('change', (event) => { const selectElement = document.querySelector("form input[value='" + formElement.value + "']").parentNode; console.log(selectElement) const result = document.querySelector('.result'); result.textContent = `You like ${selectElement.className}`; }); </script>``` -
How do I implement toast messages in Django?
I am trying to implement toastmessage in my django project. I followed this link https://pypi.org/project/django-toast-messages/ and made all the files and did everything mentioned but I cannot get a toastmessage no matter what. Please Help. -
Display single record from app to home page of the website in Django
I am trying to display record on the website home from the app. In the admin interface records are getting displayed but on the website home its not working. Site Structure Site structure website --MyWebsite ----templates --alert ----templates Code at alert/view.py def weather_single(request): weatheronly=Weatherreport.objects.last() return render(request, '../MyWebsite/templates/sidebar_left.html', {'weatheronly':weatheronly}) Code at MyWebsite/templates/sidebar_left.html {% for wresult in weatheronly %} {{ wresult.temp }} {{ wresult.forecast }} {% endfor %} Currently not getting any error message and no results at all. -
How to create a Django queryset from a list of values
I am given a list like so a = [1, 2, 3, 4] This list matches the id's stored in a django model we will call Books. I am trying to return a queryset of Books with the id's in the list. I am thinking of using Q objects and grab them by doing something like this Books.objects.filter(Q(id = 1) | Q(id=2) | Q(id=3) | Q(id=4)) Now i would just use the index like this: Books.objects.filter(Q(id = a[0]) | Q(id=a[1]) | Q(id=a[2]) | Q(id=a[3])) BUT, These list will be varying in length up to around 30 and hardcoding the index wont work, and hardcoding the query won't satisfy the varying length of lists. Is it possible to go this route? And if so, how can I accomplish returning the books with the id's that match the list? -
CSRF Token Problem with Dev Environment Django and React, Redux, Axios
I can't do a POST request via axios to my Django REST Framework API because I'm not able to get a CSRF Token. I can't render it with { % csrf_token % } because I'm developing the Front- and Backend in different Environments. Is there any way to get a CSRF Token, at least for the Dev-Environment, without rendering the page with Django? Or am I getting it right that this would make the whole idea of the CSRF Token Protection pointless? I'm using Webpack, Babel etc. for my Frontend Dev-Environment and a Docker Container for the Backend Django REST Framework Environment. I already tried to get the CSRF Token by simply sending a GET Request when the Frontend is loaded, but can't figure out to read it from the Response. I also tried disabling the CSRF Protection temporarily for the Dev-Environment but didn't find a way to disable it for the REST Frameworks Auth Views with csrf_exempt(). -
Do not display the list of the most viewed articles in the template
I want the article to appear first and then the article on the number of views. I make a list of the most popular articles on the site and so that the list of articles is displayed next to each other in order but for some reason they are not displayed in the template . I have a view model and articles should be sorted by it the more views views.py class ArticleIndex(ListView): model = Articles template_name = 'news/posts.html' paginate_by = 6 def article_tops(self): article_top = Articles.objects.all().order_by('-view') return {'article_top':article_top} posts.html {% for article in object_list %} <h1> {{ article_top }} </h1> {% endfor %} -
(Django) How to make the User FK register the User name instead of a Code (int)
In my models.py, I have the request_author field defined as: request_author = models.ForeignKey( User, on_delete = models.CASCADE ) This makes the request_author field to be registered with a user code (int) number in the API database. However, I would like to have it as the user name. How do I do that? -
Auth0 logs-in the incorrect user on custom django authentication backend
I'm using the Django Admin page to manage some basic CRUD operations of a large database. I've integrated Auth0 for login/authentication, which also bypasses the admin login page, and have written a custom authentication backend based on the Auth0 documentation for Django. Logins sometime work properly, redirecting to the Auth0 social auth sign in, requiring email and password. However, at other times, the login page is bypassed and redirects to the admin landing page, logged in as a user other than myself (I work with the user that's getting auto-logged, and he has never logged in on my local machine but is in the Auth0 and application database as a user). Auth0 logs for the application don't provide any insight to the problem. I have tried to enable the authentication portion using both the Auth0 provided guide (which uses the 'social_django' app and a custom authentication backend application) and the 'allauth' django application, both yielding the same results. I've also set the JWT token for the application to 60 seconds to ensure it expires before another login is attempted. I'm unsure if this is an issue with sessions data persisting. I have not set up a sessions backend but do … -
DjangoAdmin has_delete_permission executed from another Admin Class
I have two admin models, one is called Animal and another one is called Person. Each one have have their own has_delete_permission on their admin classes. In my logic, the instances of Animal can't be deleted if the animal is a dog. I am using has_delete_permssion for that. The code I am using is listed below. class Animal(models.Model): sound = models.CharField(max_length=25, blank=True, null=True) class Person(models.Model): sound = models.CharField(max_length=25, blank=True, null=True) class AnimalAdmin(admin.ModelAdmin): model = Animal def has_delete_permission(self, request, obj=None): if request.POST and request.POST.get('action') == 'delete_selected': animals = Animal.objects.filter( id__in = request.POST.getlist('_selected_action') ) print (animals) return True class PersonAdmin(admin.ModelAdmin): model = Person def has_delete_permission(self, request, obj=None): return True admin.site.register(Animal, AnimalAdmin) admin.site.register(Person, PersonAdmin) When I try to delete a Person instance that have the same ID of some Animals the instances of Animals are printed. This could be a serious problem if I was doing some logic like changing the database or showing a message to the user. The point is why has_delete_permission methods of different classes are also executed? -
Django reverse foreign key
I'm using python/django for 1 month now and I need help because I can't find any similar questions that has the answer I was looking for. I have Worker model and Job model. A Worker can have many jobs. I need to query the latest job that the Worker has. class Worker(models.Model): name = models.CharField(max_length=128) class Job(models.Model): worker = models.ForeignKey(Worker) type = models.CharField(max_length=64) position = models.CharField(max_length=64) location = models.CharField(max_length=128) start_date = models.DateField() I am currently using this sample code. The problem is that this returns similar Worker objects including its previous jobs. I just want to query the Worker with the latest job location and start date. for employee in Job.objects.all(): print(employee.worker, employee.location, employee.start_date) Sample Output (A, north, 2018-01-21) (A, south, 2018-09-13) (A, east, 2019-05-11) (B, west, 2019-01-01) Is there a way to use a for loop to a query like Worker.job_set.all() to have this expected output (A, east, 2019-05-11) (B, west, 2019-01-01) Hope you can help a newbie like me. Thank you in advance! :) -
How to pass a Django variable in HREF "mailto:" tag
I want to allow the user to click on a button in order to open his mailbox and send an email to the specific contact. I know in HTML I can use the tag <a href="mailto:example@gmail.com">, when the users clicks that tag, his mailbox will be open and the receiver will be "example@gmail.com". However I need a dynamic href which changes depending on project.user.email I would like to have something like that: <a href="mailto:{{project.user.email}}"></a> but naturally, this is not working. Is there a way to pass to a HREF mailto tag a Django variable? -
authenticate() is not running while adding new authentication backend
i' m trying to add a new authentication backend to my project with the following versions and code snippets: django: 2.2.1 python: 3.5.2 mysql-server: 5.7 settings.py ... AUTHENTICATION_BACKENDS = ['common.backends.MyOwnAuthenticationBackend'] common/backends.py from django.conf import settings from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User class MyOwnAuthenticationBackend(ModelBackend): print('MOAB') def authenticate(self, username=None, password=None): print('AUTH') ... def get_user(self, username): print('GETUSER') try: return User.objects.get(pk=username) except User.DoesNotExist: return None While trying to log in i get back the MOAB, but none of the AUTH or GETUSER strings. What can be the reason for it? The main urls.py contains the following for authentication: urls.py from common import views as common_views from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth import views from django.urls import path ... url(r'^accounts/login/$', views.LoginView, name='auth_login'), ... . What did i miss? I read many questions and posts about it on the Internet, but i can' t figure out why the authenticate() method is not called at all. -
Invisible field of AbstractUser - Django, models.py
I use the first time class AbstractUser in Django 3+. Therefore, I create my custom user model with an obligatory field test from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): test = models.CharField(max_length=100) def __str__(self): return self.email then it modifies my settings.py file ... AUTH_USER_MODEL = 'app.CustomUser' ... I create migrations, next I login in to django admin and my field is still not visible. How to add a test field to my user so that it is always required and visible in Django / admin. Any help will be appreciated. My admin.py class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username', 'test'] My forms.py class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ('username', 'email', 'test') class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('username', 'email', 'test') admin.site.register(CustomUser, CustomUserAdmin) -
ListAPIView is returning Page Not Found 404 as error instead of results
I have a django rest framework application and I am want to add a list view for a specific url. When I go to the url and expect a list of results, I get alist of the urls for my project and a 404 message with page not found. this is the list view i have in views: class UserHasPreferenceView(ListAPIView): serializer_class = PreferenceSerializer permission_classes = [IsAuthenticated] def get_queryset(self): namespace = self.kwargs.get('namespace', None) path = self.kwargs.get('path', None) filter_id = self.request.query_params.get('filter_id') if namespace and path and filter_id: queryset = Preference.objects.all().filter( person=filter_id, namespace=namespace, path=path) elif namespace and path and filter_id is None: queryset = Preference.objects.all().filter( person=self.request.user.id, namespace=namespace, path=path ) elif namespace and path is None and filter_id: queryset = Preference.objects.all().filter( person=filter_id, namespace=namespace ) elif namespace and path is None and filter_id is None: queryset = Preference.objects.all().filter( person=self.request.user.id, namespace=namespace ) elif namespace is None and path is None and filter_id: queryset = Preference.objects.all().filter( person=filter_id ) elif namespace is None and path is None and filter_id is None: queryset = Preference.objects.all().filter( person=self.request.user.id ) else: return None return queryset this is the urls user_has_preference = UserHasPreferenceView.as_view() path('person/has-preference/<str:namespace>/<str:path>/', user_has_preference, name='preferences-path'), this is the error i am getting: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/api/v2/person/has-preference/ -
How to import a function or a class outside django project to it?
I have a project with core module which contains my classes and function s and a rest API using django, I want to import core files inside django but I couldn't. the project structure is the following: app - core -manager - rest-api -api(django) Thanks -
Django Search Results Pop Up
The below code should return a user if the user exists. Can I use is_authenticated or is there a better way? <li class="dropdown-hover"> <form class="form-inline"> {% include "tweets/search_form.html" %} </form> {% if user in request.GET.q.is_authenticated %} <div class="dropdown-content x-card-4 x-bar-block" style="width:300px"> <a href='{{ request.GET.q }}'>{{ request.GET.q }}</a><br/> {% else %} <div class="dropdown-content x-card-4 x-bar-block" style="width:300px"> <a href='#'>No users found</a><br/> {% endif %} </li> Thank you for any help -
Why won't RadioSelect buttons appear in my browser when using the relevant widget in Django ModelForms?
I have been using Django ModelForms in an attempt to display a number of fields as radio buttons. However, after following the guidance in Django Docs regarding the RadioSelect widget, no radio buttons are displaying in the browser. Can anybody explain why? I have followed the instructions as set out in the Django Docs (https://docs.djangoproject.com/en/2.2/ref/forms/widgets/#radioselect). The relevant code is detailed below: class ReviewForm(forms.ModelForm): class Meta: model = Review fields = ['subject', 'feedback', 'mentorship', 'hiring', 'community'] class RawReviewForm(forms.Form): RATINGS = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ) subject = forms.CharField(label='') feedback = forms.CharField(widget=forms.Textarea) mentorship = forms.ChoiceField(widget=forms.RadioSelect(choices=RATINGS)) hiring = forms.ChoiceField(widget=forms.RadioSelect(choices=RATINGS)) community = forms.ChoiceField(widget=forms.RadioSelect(choices=RATINGS)) ``` My view def review_create(request): review_form = RawReviewForm() if request.method == 'POST': review_form = RawReviewForm(request.POST) if review_form.is_valid(): review_form.save() Review.objects.create(**review_form.cleaned_data) return redirect(reviews) context = { 'form': review_form } return render(request, 'reviews/review_form.html', context) ``` My form template <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend>Leave A Review</legend> {{ form.as_p }} {% for radio in form.mentorship %} <div class="myradio"> {{ radio }} </div> {% endfor %} {% for radio in form.hiring %} <div class="myradio"> {{ radio }} </div> {% endfor %} {% for radio in form.community %} <div class="myradio"> {{ radio }} </div> {% endfor %} </fieldset> … -
Django making a many post requests to a another webapp always cancelled
I creating a website (for practice only) that allows user to check the Name of their favorite artists and my website will show details about that artists I created a form with textarea and once the user Submit all their favorite artist ( POST Requests to other path of my webapp ), It cancelled and return a error on terminal This is the error Traceback (most recent call last): File "F:\Python\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "F:\Python\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "F:\Python\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "F:\Python\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "F:\Python\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "F:\Python\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "F:\Python\lib\socketserver.py", line 799, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine [24/Jul/2019 00:18:58] "POST /knowers/parser HTTP/1.1" 200 322 Traceback (most recent call last): File "F:\Python\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "F:\Python\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "F:\Python\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "F:\Python\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "F:\Python\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "F:\Python\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "F:\Python\lib\socketserver.py", line … -
Django - Filter related objects by through field
I have the following models class User(models.Model): ... following = models.ManyToManyField('self', blank=True, through='relationships.Relationship', symmetrical=False, related_name='followers') class Relationship(models.Model): from_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='from_user') to_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='to_user') status = models.CharField(max_length=255, default=RelationshipStatus.ACCEPTED.value, choices=[(state.value, state.name) for state in RelationshipStatus]) class RelationshipStatus(Enum): ACCEPTED = 'accepted' PENDING = 'pending' REJECTED = 'rejected' I would like to get the followers of a given user, but only the ones that have an approved relationship. This is easy with the following query. Relationship.objects.filter(to_user=a_user, status=RelationshipStatus.ACCEPTED.value) But my question is, how can I do it by using the followers attribute of my user? If I do a_user.followers.all() I get them all, but I only want the ones with an accepted relationship. Those won't work a_user.followers.filter(status=RelationshipStatus.ACCEPTED.value) or a_user.followers.filter(relationship__status=RelationshipStatus.ACCEPTED.value) since the following exception are raised django.core.exceptions.FieldError: Cannot resolve keyword 'relationship' into field. django.core.exceptions.FieldError: Cannot resolve keyword 'status' into field. -
Django - obtaining a child model from a parent by the childs one to one field?
Good Afternoon, I have a pair of models like the below: class DeviceCircuitSubnets(models.Model): device = models.ForeignKey(Device, on_delete=models.CASCADE) circuit = models.ForeignKey(Circuit, on_delete=models.CASCADE, blank=True, null=True) subnet = models.ForeignKey(Subnet, on_delete=models.CASCADE) ... class BGPData(models.Model): device_circuit_subnet = models.OneToOneField(DeviceCircuitSubnets, verbose_name="Device", on_delete=models.CASCADE) bgp_peer_as = models.CharField(max_length=20, verbose_name='BGP Peer AS', blank=True, null=True) bgp_session = models.CharField(max_length=10, verbose_name='BGP Session', blank=True, null=True) bgp_routes = models.CharField(max_length=10, verbose_name='BGP Routes Received', blank=True, null=True) service_status = models.CharField(max_length=10, verbose_name='Service Status', blank=True, null=True) timestamp = models.DateTimeField(auto_now=True, blank=True, null=True) I am filtering the DeviceCircuitSubnets and then I also want to access the BGPData related model via each filtered item. service_data = DeviceCircuitSubnets.objects.filter(monitored=True, device__site_id=site_id) \ .select_related('device','circuit','subnet') I have tried adding bgpdata to the select related and to prefetch but neither are currently working, I am returned with an error stating the model doesn't exist. how would my query need to look to obtain each one to one field in a query set? Thank you -
Need help identifying language, I believe its Python, but I'm not sure
I just took a part time job as a web developer and need help identifying some code. They told me it was built in html/css/javascript, but they are using what I believe are python template tags. They are comfortable with me learning a new language, I just want to make sure that I'm learning the correct language. I've copy and pasted the code into google and stack overflow search bars, again it looks like python/django or possibly jinja 2, but I don't know those languages and want to make sure I'm on the right track. This is just the opening line of the master.master file, which I am also not used to seeing as a master file. ` <!DOCTYPE html> <html lang="{{ data.Language }}" dir="{% if data.LanguageDetails.IsRtl %}rtl{% else %}ltr{% endif %}"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> {% block meta %}{% endblock %} {% for language in data.Languages %}{% if language.Culture != data.Language %} {% assign currentLanguagePrefix = '/' | Append:data.Language | Append: '/' %} {% assign thisLanguagePrefix = language.Culture | Append: '/' %} <link href="/{{ data.URL | Replace: currentLanguagePrefix, thisLanguagePrefix }}" hreflang="{{ language.Culture }}" rel="alternate"> {% endif %} {% endfor %}` -
Setting supervisor to an existing django-gunicorn-nginx app
I've a live django app, deployed at digitalocean by following this link There's no mention about supervisor service. Now, I realise, I need to use supervisor. Can I accomplish it with the existing setup? Or do I need to start everything from the beginning? Please help. Thanks. -
return message after file download in Django view response
I am downloading a pandas data-frame as a csv file using this approach: view.py .... response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="' + filename + '"' my_df.to_csv(response, encoding='utf-8', index=False, ) return response in my html, I have ... <form class="default_form" method="POST" action="do_export"> {% csrf_token %} <br/> <input type="submit" class="btn btn-primary exportOut" value="Do Export" id="myExport"/> <br/> </form> The file export works fine. However, after the export is done, I need to be able to show a message on the html page .... something like {{ my_message}} without reloading the page. if this is feasible, I would appreciate any suggestion on how to do this, without resorting to AJAX, which I abandoned because some of the downloads can be large. -
pylint(undefined-variable) error on return render
I'm working on a simple project with foreign keys on each model. The program worked well until I tried rendering the fetched data to a template. When I tried getting a simple HttpResponse, it worked well, but rendering to a template gives me an error. I get an error that states Undefined variable 'required' pylint(undefined-variable) My code looks like this: from django.shortcuts import render, redirect from .models import master_courses, course_category, course_series def single_slug(requests, single_slug): categories = [c.course_slug for c in course_category.objects.all()] if single_slug in categories: matching_series = course_series.objects.filter(course_category__course_slug=single_slug) series_urls = {} for ms in matching_series.all(): part_one = master_courses.objects.filter(course_series__course_series=ms.course_series).earliest("date_added") series_urls[ms] = part_one return render(request, "main/category.html", {"the_series": series_urls}) The error points to the last line of the code, which is: return render(request, "main/category.html", {"the_series": series_urls}) And it says undefined variable 'request' pylint(undefined-variable) Other return statements work well except for that statement within the for loop as I've mentioned above. Any suggestions on how I can solve this please? -
Django with legacy database and foreign keys where id=0
I am working with data that has been migrated from a PHP-based MySQL database to Django. In this PHP database they used foreign keys where the id = 0. So naturally when I try to insert a record that references a foreign key of 0 I get the following: "The database backend does not accept 0 as a value for AutoField." Fair enough. It seems this was done to protect folks from MySQL's use of using 0 to auto generate a primary key: https://code.djangoproject.com/ticket/17713 However there appears to be a way to write a "custom backend" to work around this: https://www.mail-archive.com/django-users@googlegroups.com/msg187956.html This seems less than optimal for something that appears to have a session-based solution of setting the following in the MySQL session: SET SESSION SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; Barring switching the database or other hacks to make this work are there better options to get Django and MySQL to play together with id=0?