Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django forms are not receiving form data using ajax call
I am writing a simple AJAX site using a Django back-end where you can create articles. Each article has an edit button, which can be used to modify that pre-existing article on the page. This button pops up an edit form (the issue at hand) in a Bootstrap Modal. The edit form has only 3 fields: headline, subheading, and a date (for now). Whatever the field inputs are, they are not sent back to Django properly and the is_valid() method returns False every single time. This is what form.errors gives me as output every single time: <ul class="errorlist"><li>headline<ul class="errorlist"> <li>This field is required.</li> </ul> </li> <li>subheading<ul class="errorlist"> <li>This field is required.</li></ul></li> <li>date<ul class="errorlist"><li>This field is required.</li></ul></li></ul> The "This field is required" is likely because the model does not have blank=True, so the form must be sending empty fields. Below is all my code in question, including the form in HTML, the AJAX call, and the Django form. views.py: # Handles editing articles class ArticleEdit(View): def post(self, request, id): editForm = ArticleForm(request.POST) if editForm.is_valid(): print("Debug: Form is valid") # No Logic here yet return JsonResponse({'edited' : 'OK'}, status=200) else: print(editForm.errors) return JsonResponse({'edited' : 'FAIL'}, status=200) forms.py class ArticleForm(ModelForm): class Meta: model … -
how to control the img attributes src in fetching the data from database in Reactjs
I am creating a article related project. And A article can we wrriten by multiple author.In this I want to show image on webpage if it has src and if it has no src then show empty.I fatched the data by using axios <img className="userpic" src={item.author[0].picture} alt="" /> <img className="userpic" src={item.author[1].picture} alt="" /> <img className="userpic" src={item.author[2].picture} alt="" /> currently the above code is working because in author table all id has the picture.But suppose If there is no picture inside the author[2] then I am getting the error on console Uncaught TypeError: Cannot read property 'picture' of undefined How can we solve it? -
python3 manage.py findstatic can't find static file
I am trying to add static file to my project but css doesn't load. I used findstatic but django doesn't see any static directory: In another project django still can find static folder: My settings.py: STATIC_URL = '/static/' My base.html: {% load static %} <!DOCTYPE html> <html> <head> <meta charset = "utf-8"> <link href = "{% static 'css/base.css' %}" rel = 'stylesheet'> <title>{% block title %}Educa{% endblock %}</title> </head> <body> <div id = 'header'> <a href = "/" class = 'logo'>EDUCATION</a> <ul class = 'menu'> {% if request.user.is_authenticated %} <li><a href = "{% url 'logout' %}">Logout</a></li> {% else %} <li><a href = "{% url 'login'%}">Login</a></li> {% endif %} </ul> </div id ='content'> {% block content %}{% endblock %} <script src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/ jquery.min.js'></script> <script> $(document).ready(function(){ {% block domready %} {% endblock %} }); </script> </body> </html> Thank you -
How to filter location inside Lat Long Polygon/Geometry in DJango?
I have a list of lat and long that shape a polygon, and I want to retrieve the location or points that it's lat long inside the polygon. Is Django Geo can do that with MySql database? -
Rading the django model field value in the base template
I have a auth_user model, and a posts model. the posts model has fields like: id, author_id and likes. All I need print likes values related to each user in the base template. like: {{ user.posts.likes }} however it does not work, while {{ user.profile.image.url }} (profile is another model which has user_id) works perfectly. I am importing base templates to other templates like {% extends "app/base.html" %} so I don't see any place in backend to pass the likes values -
Use Django view to group every 3 objects into seperate context variables?
I want to break up my project query projects = Project.objects.all() from my views.py file into groups of 3. I apologize if my question was worded poorly. I'm not entirely sure how to ask this in a short, concise way. Any suggestions on how to better word this and I'll update. My view function currently: def project_index(request): projects = Project.objects.all() project_len = len(projects) project_list = zip(*[iter(projects)]*3) context = { 'projects': projects } return render(request, 'project_index.html', context) I was thinking I could use a dictionary somehow, but after starting to work through this I find myself a little lost as to how to implement it. Ideally, I need to get every 3 objects and create a new context variable for those objects. For example lets say there are 9 objects in total: def project_index(request): projects = Project.objects.all() project_len = len(projects) <---gets the total number of objects project_list = zip(*[iter(projects)]*3) <---converts objects into list, groups of 3(not sure if this will work for what I am trying to do, but it was a thought.) context = { 'projects': projects, 'group1': group1, <---each group contains 3 objects(object1, object2, object3) 'group2': group2, <---(object3, object4, object5) 'group3': group3, <---(object6, object7, object8) } return render(request, 'project_index.html', … -
Django, pass a javascript variable into ListView to filter a queryset
I'd like to use an Ajax variable within a Django Class based ListView. Getting the variable into the view is no problem using request.GET.get however, it seems by doing so, I am put into a dilemma. If I am using def get(self, request) I then have problem using get_queryset and get_context If I skip using def get(self, request) I have problem getting the Ajax variable into the view. I'd like to ask for some help to get it working. The ultimate aim is to produce a filtered context that will be used to produce an email. class ProductListSendView(LoginRequiredMixin, ListView): model = Product template = 'product/product_email.html' def get(self, request): _req_list = json.loads(request.GET.get('ids', None)) _res = [int(i) for i in _req_list] return _res def get_queryset(self, _res): queryset = super(ProductListSendView, self).get_queryset() qs = queryset.filter(id__in=_res) return qs def get_context_data(self): context = super(ProductListSendView, self).get_context_data() context['page_title'] = 'Authors' self.send_email(context) return context the js function (for completeness) var getProducts = function () { var table = $('#product_list-table').DataTable(); var ids = $.map(table.rows('.selected').data(), function (item) { return item[1]}); jQuery.ajax({ type: 'GET', url: "/product/list/send/", data: { ids: JSON.stringify(ids), }, success: function(data) {}, error: function(xhr, textStatus, error) { console.log(error); } }); }; -
Windows + mod_wsgi + Apache 2.4 + Django - mod_wsgi error: ModuleNotFoundError: No module named 'django'\r
I am trying to deploy my first basic Django Application for study purposes. I have not much experience and after few days i decided to find help here. I want to use Apache 2.4 + mod_WSGI + Django at Windows server. I was following instructions from youtube's video: https://www.youtube.com/watch?v=frEjX1DNSpc After all steps done i cannot access duo to error: ModuleNotFoundError: No module named 'django'\r I do not use VEnv Apache seems to work fine Django is in instaled pip list and seems obtainable C:\Apache24\logs\error.txt The 'Apache2.4' service is running. pm_winnt:notice] [pid 12736:tid 596] AH00455: Apache/2.4.46 (Win64) mod_wsgi/4.7.1 Python/3.7 configured -- resuming normal operations [Sun Oct 25 10:08:29.519101 2020] [mpm_winnt:notice] [pid 12736:tid 596] AH00456: Apache Lounge VS16 Server built: Oct 2 2020 11:45:39 [Sun Oct 25 10:08:29.519101 2020] [core:notice] [pid 12736:tid 596] AH00094: Command line: 'C:\\Apache24\\bin\\httpd.exe -d C:/Apache24' [Sun Oct 25 10:08:29.521101 2020] [mpm_winnt:notice] [pid 12736:tid 596] AH00418: Parent: Created child process 13836 [Sun Oct 25 10:08:29.851909 2020] [mpm_winnt:notice] [pid 13836:tid 624] AH00354: Child: Starting 64 worker threads. [Sun Oct 25 10:08:35.795055 2020] [wsgi:error] [pid 13836:tid 1148] [client ::1:61451] mod_wsgi (pid=13836): Failed to exec Python script file 'C:/Users/Mateusz/Documents/GitHub/Production-tool/Zeus/Zeus/wsgi.py'. [Sun Oct 25 10:08:35.795055 2020] [wsgi:error] [pid 13836:tid 1148] [client ::1:61451] mod_wsgi (pid=13836): … -
Django CARDINALITY Query does not allow filtering by equals but does work for < or >
I have a Document model, which contains an ArrayField of pages. I want to find a list of all documents that have zero pages. Model field: content = ArrayField(models.TextField(), default=list, blank=True) I use an annotation function to first create a calculated field for number of pages, and then try to filter on pages equal zero. Here is the query I'm trying to run: qs = Document.objects.all() \ .annotate(content_len=Func(F('content'), function='CARDINALITY')) \ .exclude(content_len=0) # this DOESN'T WORK .exclude(content_len__lt=1) # this WORKS The version that doesn't work generates the following SQL error: WHERE CARDINALITY("dockets_document"."content") = 0::text[] >>> psycopg2.errors.CannotCoerce: cannot cast type integer to text[] -
extra_context variables are not passed to changelist template
Trying to modify standard admin list template, for this I'm passing extra_context: def changelist_view(self, request, extra_context=None): extra_context = extra_context or {} extra_context['stats'] = 'test' resp_view=super().changelist_view(request, extra_context=extra_context) return resp_view And using this in the template: ... <div class="results"> <p> Statistics: {{ stats }} </p> <table id="result_list"> ... But it doesn't pass it for some reason. Although when I look into the fields of resp_view, it's in the context data: (Pdb) p resp_view.context_data {'site_title': 'Django site admin', ..., 'stats': 'test'} What can be the problem here? I understand it's official way of passing extra variables into the template? -
Passing a variable to the form action
So I have first form in which user chooses profile: class ProfileChoice(forms.ModelForm): def __init__(self, *args, **kwargs): self.user_id = kwargs.pop('user_id',None) super(ProfileChoice, self).__init__(*args, **kwargs) self.fields['login'].queryset = Profile.objects.all().filter(created_by_id = self.user_id) login = forms.ModelChoiceField(queryset= None, label='Profile') class Meta: model = Profile fields = ('login',) On submit I need to redirect him to the next form which is this: class TranslatorChoice(forms.ModelForm): def __init__(self, *args, **kwargs): self.user_id = kwargs.pop('user_id',None) super(TranslatorChoice, self).__init__(*args, **kwargs) self.fields['owner'].queryset = Translator.objects.all().filter(owner_id = self.user_id) owner = forms.ModelChoiceField(queryset = None) class Meta: model = Translator fields = ('owner',) with this view: class ProfileOwner(UpdateView): model = Profile template_name = 'registration/update.html' success_url="/account/" form_class = TranslatorChoice @method_decorator(user_passes_test(client_check, login_url='/account/')) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get_form_kwargs(self): kwargs = super(ProfileOwner, self).get_form_kwargs() kwargs['user_id'] = self.request.user.id return kwargs def get_object(self, queryset=None): profile = super(ProfileOwner, self).get_object(queryset) if profile.created_by != self.request.user: raise Http404("Profile doesn't exist") return profile The update needs to be performed on the profile which was chosen in the first form. I am trying to do it with passing a pk to the URL. Here's urls.py: url(r'^update/(?P<pk>\d+)', ProfileOwner.as_view(), name='profile_owner_update') and my template is here: {% extends 'base.html' %} {% block content %} <h2>Add profile</h2> <form method="post" action="{% url 'profile_owner_update' pk=id %}"> {% csrf_token %} {{ form.as_p }} <button type="submit">Choose</button> … -
Cannot resolve keyword 'slug_iexact' into field. Choices are: Tag_Name, id, posts, slug
I am getting the following error: FieldError at /tag/htc_phones/ Cannot resolve keyword 'slug_iexact' into field. Choices are: Tag_Name, id, posts, slug models.py : class Tag(models.Model): Tag_Name = models.CharField(max_length=100) slug = models.SlugField(unique=True,editable=True,max_length=200) def __str__(self): return self.Tag_Name def get_absolute_url(self): return reverse('tag_detail_url', kwargs={'slug':self.slug}) views.py: def tag_detail(request,slug): tag = Tag.objects.get(slug_iexact=slug) return render(request,'website_primary_html_pages/tag_detail.html',context={'tag':tag}) how to fix this problem , thanks -
Reorder siblings with Django-mptt
I have a tree structure as follows: Financial Statements Balance Sheet Non-Current Assets Property, Plant & Equipment Buildings Plant & Machinery Long Term Investments..... The relevant model is as follows: class Category(MPTTModel): name = models.CharField(max_length=255) ordering = models.IntegerField() parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPPTMeta: order_insertion_by = ['ordering'] I need to allow users to be able to reorder siblings from the front-end using the field "ordering". I set the "ordering" of: Long Term Investments to 0 Property, Plant & Equipment to 1 then I ran the following code in views.py: def category(request): Category.objects.rebuild() tree_obj = Category.objects.all() structure = get_structure(tree_obj) print(structure) The result is: <TreeQuerySet [<Category: Financial Statements>, <Category: Balance Sheet>, <Category: Non-Current Assets>, <Category: Property, Plant & Equipment>, <Category: Buildings>, <Category: Plant & Machinery>, <Category: Long Term Investments>... I expected "Long Term Investments" to appear before "Property, Plant & Equipment" and its children. What am I doing wrong? -
Django 3 template date tag return nothing
I'm try to use date template tag to format datetime from database 2020-10-23 08:59:44.792274 on django template {{ item.payment_received_time }} # return 2020-10-23 08:59:44.792274 {{ item.payment_received_time|date:"D d M Y" }} # return nothing but nothing is returned, what am I missing on it ? Thanks -
Django Save Image Path to Database
I'm new to Django and I want to save the image path to the Postgres database. I'm asked to use Charfield in my model not Imagefield. How can I do that? Thanks in advance. -
os.environ not returning environment variables on Elastic Beanstalk
When deploying my Django project, database settings are not configured because 'RDS_HOSTNAME' in os.environ returns false. Running /opt/elasticbeanstalk/bin/get-config environment returns following: {"DJANGO_SETTINGS_MODULE":"myApp.settings","PYTHONPATH":"/var/app/venv/staging-LQM1lest/bin:$PYTHONPATH","RDS_DB_NAME":"ebdb","RDS_HOSTNAME":"xxxx.amazonaws.com","RDS_PASSWORD":"xxxx","RDS_PORT":"xxxx","RDS_USERNAME":"xxxx"} All RDS prefixed variables are set but still somehow os.environ is unable to read it. setting.py file: # [...] if 'RDS_HOSTNAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } # [...] -
Ajax is not sending data to django views
My Html --- <div class="form-group row pt-3 d-flex justify-content-center"> <div class="col-sm-10 d-flex justify-content-center"> <button id="submit_pic" style="width: 70%;" type="" class="btn btn-primary">Combine</button> <script> $("#submit_pic").submit(function (e) { e.preventDefault(); var csrfToken = $("input[name='csrfmiddlewaretoken']"); console.log(`Error ye raha === ${response_send}`) $.ajax({ url: "{% url 'make_combine' %}", //url: "/make_combine", type: "POST", //-------here is problem------- dataType: "json", cache: true, headers: {'csrfmiddlewaretoken': csrfToken.val()}, data: {"for_combine": response_send }, //"success": function (result) { // console.log(data); //}, }); return false; }); </script> </div> </div> django views.py -- import json def make_combine(request): combine_data7 = request.POST.get("for_combine") I have tried a lot of tricks available on internet as well as on StackOverflow, but still getting this error.It tells that combine_data7 is NoneType ---- AttributeError at /make_combine 'NoneType' object has no attribute 'split' -
Save user data in UserProfile with Middleware and GeoIP
I have a small question to ask you. I use GEO IP to locate my users and I would like to record this information every time user log in to improve the user experience of the app. The problem is that it doesn't save absolutely nothing at each connection. UserProfile models is empty... Anyone has an idea about this? user/middleware.py from .models import UserProfile from django.contrib.gis.geoip2 import GeoIP2 from django.utils.deprecation import MiddlewareMixin class LastLoginInfo(MiddlewareMixin): def geolocalisation(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') device_type = "" browser_type = "" browser_version = "" os_type = "" os_version = "" if request.user_agent.is_mobile: device_type = "Mobile" if request.user_agent.is_tablet: device_type = "Tablet" if request.user_agent.is_pc: device_type = "PC" browser_type = request.user_agent.browser.family browser_version = request.user_agent.browser.version_string os_type = request.user_agent.os.family os_version = request.user_agent.os.version_string g = GeoIP2() location = g.city(ip) location_country = location["country_name"] location_city = location["city"] if request.user.is_authenticated(): UserProfile.objects.filter(user=request.user).update(ip_address_ua=ip, device_ua=device_type, browser_ua=browser_type, os_device_ua=os_version, city_ua=location_city, country_ua=location_country) main/settings.py MIDDLEWARE = [ ... 'user.middleware.LastLoginInfo', ... ] -
I want to create a College Management System [closed]
I am working on a College Management System in Django. Now my questions is how to groups users in the semester wise. and also how to promote it into next semester ? Like For example, if user signup they directly assigned to semester 1 and view the semester 1 data ? Anyone know how to do this in Django? -
Why does getting Django's CSRF token from a cookie fail on mobile Chrome browser?
I have a web application built in Django that uses React components. The application currently has been tested and works on desktop Google Chrome, Microsoft Edge, mobile Firefox and mobile Brave browsers. Unfortunately, it produces errors on Google Chrome on mobile. The React components do not seem to recognize that there is a user logged in. The CSRF token is transferred from Django to the React components using a cookie (similarly to the process suggested at: https://django.readthedocs.io/en/stable/ref/csrf.html). // Set what happens when the database is called by React // Define how to get a cookie (such as a CSRF token) export function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } // Define generically what happens when the database is called by React export function backendLookup(method, endpoint, callback, data) { // Convert the data being sent to the database to JSON form let jsonData; if … -
Django + HTML highlight text in textarea on offset and lengths
Having a dictionary like this in my view, I need help in finding out how Insert the correction string directly after the error word Highlight the error strings red and the correction strings green. {'content': [{'offset': 6, 'length': 2, 'error': 'go', 'correction': 'goes'}, {'offset': 22, 'length': 8, 'error': 'everyday', 'correction': 'every day'}, {'offset': 58, 'length': 8, 'error': 'everyday', 'correction': 'every day'}, {'offset': 78, 'length': 9, 'error': 'favourite', 'correction': 'favorite'}, {'offset': 98, 'length': 2, 'error': 'Me', 'correction': 'I'}, {'offset': 173, 'length': 8, 'error': 'wensdays', 'correction': 'wens days'}]} Take the picture below as an example Example visuals -
Send data in Angular to backend Django for sending email
I have contact form in Angular which use httpclient for Post method to django which is sending email with all data information from Angular to my email adress. In PostMan everythink work fine. What is mean "10" and "14" after response 200? I got in console: Dave dave@gmail.com hi how are you?. [25/Oct/2020 12:10:47] "POST /send_email/ HTTP/1.1" 200 10 but when I try in my angular I got: None None None [25/Oct/2020 12:14:11] "POST /send_email/ HTTP/1.1" 200 14 So if PostMan works fine, the problem is somewhere in Angular, but I don't know what is wrong. django def: @csrf_exempt def send_email(request): name = request.POST.get('name') email = request.POST.get('email') message = request.POST.get('message') print(name, email, message) try: send_mail(f'{name} wysłał wiadomość z Zakuro', f'adres: {email}/// wiadomość: {message}', 'email@gmail.com', ['secondemail@gmail.com'], fail_silently=False) send_mail('Thanks for contact with Zakuro', 'Hi. I will response as soon as possible.', 'email@gmail.com', [f'{email}'], fail_silently=False) return HttpResponse('email sent') except: return HttpResponse('email not sent') angular component: import { Component, OnInit } from '@angular/core'; import { CookieService } from 'ngx-cookie-service'; import { Router } from '@angular/router'; import { ApiService } from '../api.service'; @Component({ selector: 'app-contact', templateUrl: './contact.component.html', styleUrls: ['./contact.component.sass'] }) export class ContactComponent implements OnInit { constructor( private cookieService: CookieService, private router: Router, private apiService: … -
Django messages not showing in template
stuck with messages don't show up cant figure whats wrong with my code def studentreg(request): if request.method == 'POST': form = StudentRegisterForm(request.POST) if form.is_valid(): form.save() messages.success(request, f'Student has been created! You can view in the list!') return redirect('dashboard') else: form = StudentRegisterForm() return render(request, 'studentregister.html', {'form': form}) In the base template {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} {% endif %} When i save the student it doesn't show the message but when i view page source on chrome the message is there .help please. </head> <div class="alert alert-success"> Student has been created! You can view in the list! </div> <body> -
How to get multiple columns from different tables in Django and that result should be downloaded to Excel format
Please help me. views.py Error: I'm getting empty excel file. -
Why are the error reporting emails not being sent (Django)?
Python version: 3.6.3 Django version: 3.0.8 I am trying to use enable Django's error reporting via email, but nothing seems to happen when I encounter a 500 error. Here is a copy of my settings file with some comments and sensitive information removed: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '' # The actual value has been omitted DEBUG = False ADMINS = [('', '')] # Omitted. The same email address is used for EMAIL_HOST_USER and SERVER_EMAIL MANAGERS = ADMINS ALLOWED_HOSTS = ['.localhost', '127.0.0.1', '[::1]'] # ALLOWED_HOSTS = [] EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST_USER = '' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_PSSWORD = '' # Omitted SERVER_EMAIL = '' """ LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } """ INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'main.apps.MainConfig', 'register.apps.RegisterConfig' ] 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', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' DATABASES = { 'default': …