Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Annotation and Filter gives me a SQL error in Django
How to filter with an annotate on a queryset? Currently, I am using this code: queryset = queryset.annotate(tags_count=Count("tags")).filter( tags_count=len(ids) ) But it gives me an SQL error of: (1054, "Unknown column 'users.university_id' in 'having clause'") Everytime I remove this code, my whole program works. Is there something I should have not done? -
Sub query using django mongoengine
is there a way to combine the following 2 queries in a single query using django-mongoengine library? Table2 schema = {'_id': int, 'list': Array of int} Table1 schema = {'_id': int, ....} id_list = Table2.objects.get(id=375).list filtered = Table1.objects.filter(id__in=id_list) thanks -
Sendgrid Port shifting
I got the following mail from SentGrid, Twilio SendGrid is removing access to our APIs via http, port 80. Once we remove this access, your requests to APIs via the mentioned endpoints will be rejected if not sent via https, port 443. If you are currently using http, port 80, please update your call to https, port 443. Http, port 80, requests will be rejected on October 1st, 2020." Presently I am sending mails to sendgrid by using following credentials, EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'#gateway_settings.EmailBackend EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_USE_TLS = False EMAIL_PORT = 587 EMAIL_HOST_USER = 'xx@gmail.com' EMAIL_HOST_PASSWORD = 'xxx' Is this change in port affect me? -
How to make user profile showing percentage complete Using Django
if user profile is complete is 25%, message: first of all complete your profile and then do this"apply job" I followed(Django profile showing percentage complete) I have a user profile model. model.py: class profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key=True) random = models.CharField(max_length=50) image = models.ImageField(upload_to="profile_pics") def __str__(self): return f'{self.user.username} profile' def get_absolute_url(self): return reverse('jobseeker:jobseeker_profile') @property def percentage_complete(self): percent = { 'random': 50, 'image': 50} total = 0 if self.random: total += percent.get('random', 0) if self.image: total += percent.get('image', 0) return total Forms.py class ProfileUpdateForm(forms.ModelForm): random = forms.CharField(widget=forms.TextInput( attrs={'class':'form-control', 'placeholder':'write whant you want'} ), required=False, max_length=20) class Meta(): model = profile fields = ['random', 'image'] Views.py: @method_decorator([login_required, jobseeker_required], name='dispatch') class profile_jobseeker(CreateView): model = profile form_class = ProfileUpdateForm template_name = 'profile.html' context_object_name = 'profile' def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) how to render percentage completion value in templates? is it correct: profile.html your profile is {{ pfofile.percentage_complete }} complete -
Django remote server is running but I cannot connect to admin interface in local web browser
So I have set up my Django server through an SSH connection to my remote server. It shows me that the server is actually running: August 10, 2020 - 04:09:47 Django version 3.1, using settings 'risk_areas.settings' Starting development server at http://xx.xxx.xxx.xxx:8000/ Quit the server with CONTROL-C However, if I try to go to the URL above (with my IP address in it) it gives me a connection time out error. What might be the reason for this? -
Keep getting NoReverseMatch error in Django project
I am trying to do a update function for this form. The template page displays properly, but once i click submit button, i keep getting the NoReverseMatch error: Reverse for 'update_page' with keyword arguments '{'title': ''}' not found. 1 pattern(s) tried: ['wiki/(?P[^/]+)/update$'] The project does not have models, as per assignment. The db is basically a folder in the same directory. And the files in this folder are being managed through the list_entries(), save_entry() and get_entry() functions in the util.py. urls: app_name = "entries" urlpatterns = [ path("", views.index, name="index"), path("newpage", views.newpage, name="newpage"), path("<str:title>", views.open_page, name="open_page"), path("search/", views.search, name="search_query"), path("<str:title>/update", views.update_page, name="update_page"), path("random/", views.random_page, name="random_page"), path("<str:title>/deleted", views.del_page, name="del_page") ] My views code: def update_page(request, title): entered_content = util.get_entry(title) form_dict = {'form_title': title, 'form_content': entered_content} if request.method == "POST": form = NewPageForm(request.POST or None, initial=form_dict) if form.is_valid(): title = form.cleaned_data[title] updated_content = form.cleaned_data['form_content'] util.save_entry(title, updated_content) return HttpResponseRedirect(reverse("entries:open_page", args=(title), )) else: return render(request, "encyclopedia/updatepage.html", { "form": form }) return render(request, "encyclopedia/updatepage.html", { "form": NewPageForm(request.POST or None, initial=form_dict), "titles": title, }) The template: {% block body %} <h2>Update the {{titles}} entry:</h2> <form action="{% url 'entries:update_page' title=titles %}" method="post"> {% csrf_token %} {{ form.form_content}} <input type="submit" value="Update"> </form> <form method="GET" action="{% url 'entries:del_page' title=titles … -
My django generic DetailView not displaying queries
This is my urls.py from django.urls import path from .views import PostListView, PostDetailView from . import views urlpatterns = [ path('', PostListView.as_view(), name = "blog-home"), path('post/<int:pk>/', PostDetailView.as_view(), name = "post-detail"), path('about/', views.about, name = "blog-about"), ] I am importing PostDetailView to use with my model Post Here is my view.py from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post class PostListView(ListView): model = Post # Default naming Convection: <app>/<model>_<viewtype>.html template_name = "blog/home.html" context_object_name = "posts" ordering = ['-date_posted'] #This is the my Detail View class PostDetailView(DetailView): model = Post def about(request): return render(request, 'blog/about.html', {'title': 'About'}) My Template name is post_detail.html just as the django convection specifies. Here is the error that comes to my console Not Found: /post/1/ [10/Aug/2020 03:44:27] "GET /post/1/ HTTP/1.1" 404 1728 While loading the home page, it displays all posts in a list as from my list view. This is the post_detail.html <!-- Template Inheritance --> {% extends 'blog/base.html' %} {%block content%} <div class="container-fluid"> <div class="shadow p-3 mb-5 bg-white rounded "> <div class=""> <h1>{{ object.title }}</h1> <small>By {{ object.author }} on {{object.date_posted}}</small> </div> <div class=""> <p>{{object.content}}</p> </div> </div> </div> -
How can i detect what is wrong in this heroku log deploying?
I deployed using the step by step heroku instructions, and the django project is very basic. The page error is: "An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command" I just want to deploy a basic django project, thats my target. > 2020-08-10T02:36:38.842590+00:00 app[web.1]: File "<frozen > importlib._bootstrap>", line 1014, in _gcd_import > 2020-08-10T02:36:38.842590+00:00 app[web.1]: File "<frozen > importlib._bootstrap>", line 991, in _find_and_load > 2020-08-10T02:36:38.842590+00:00 app[web.1]: File "<frozen > importlib._bootstrap>", line 975, in _find_and_load_unlocked > 2020-08-10T02:36:38.842591+00:00 app[web.1]: File "<frozen > importlib._bootstrap>", line 671, in _load_unlocked > 2020-08-10T02:36:38.842591+00:00 app[web.1]: File "<frozen > importlib._bootstrap_external>", line 783, in exec_module > 2020-08-10T02:36:38.842592+00:00 app[web.1]: File "<frozen > importlib._bootstrap>", line 219, in _call_with_frames_removed > 2020-08-10T02:36:38.842592+00:00 app[web.1]: File > "/app/mosh_heroku_project/wsgi.py", line 12, in <module> > 2020-08-10T02:36:38.842592+00:00 app[web.1]: from django.core.wsgi > import get_wsgi_application 2020-08-10T02:36:38.842593+00:00 > app[web.1]: ModuleNotFoundError: No module named 'django' > 2020-08-10T02:36:38.842600+00:00 app[web.1]: [2020-08-10 02:36:38 > +0000] [9] [INFO] Worker exiting (pid: 9) 2020-08-10T02:36:38.886190+00:00 app[web.1]: [2020-08-10 02:36:38 > +0000] [4] [INFO] Shutting down: Master 2020-08-10T02:36:38.886404+00:00 app[web.1]: [2020-08-10 02:36:38 > +0000] [4] [INFO] Reason: Worker failed to boot. 2020-08-10T02:36:38.971065+00:00 heroku[web.1]: Process exited … -
Django pass data to an existing object
I have an Order model, that has a remark field. I'm rendering my Order model objects in an HTML file and currently, I have 2 orders in my order model that are displaying in the HTML file. And both orders in the HTML file have a text field and a submit button, where I can manually enter a text for any order I wish to give a remark to and pass the value into the remark field in Order model. However, when I enter a text in a text field for a particular order in my HTML file and pass the data to the Order model it creates a new object. I want to pass the data into an existing order object that I have given a remark to in my HTML file . models.py class Order(models.Model): item = models.ManyToManyField('Item') name = models.CharField(max_length=30) address = models.CharField(max_length=100) remark = models.CharField(max_length = 100, null=True) views.py def order_list(request): if request.method=="POST": if request.POST.get('remarks'): saveresults=Order() saveresults.remark=request.POST.get('remarks') saveresults.save() order = Order.objects.all() context = { 'order':order, } return render(request, "order_list.html", context) HTML <table class="table table-responsive"> <thead class="bg-secondary"> <tr> <th scope="col">Item</th> <th scope="col">Name</th> <th scope="col">Address</th> </tr> </thead> <tbody> {% for order in order %} <tr> <td>{{order.item}}</td> <td>{{ Order.name … -
Kiwi-tcms Django plugin installation PROBLEMS
Hi I got an error when I try to install kiwi-tcms Django plugin in Ubuntu. I run this command as the documentation says Command: pip install kiwitcms-django-plugin Documentation: https://github.com/kiwitcms/django-plugin The error message in the console Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-kdc6s2yz/gssapi/ I really tried different kind of things to solve it but I didn't get any new good result Why could be the error ? -
How can i integrate the xml available a website into my own web app i am making with Django?
I am using django's latest version which is 3.x The database i plan on using is the one that comes in build with it I want to take the data from the xml of that website and add it to my db so that i can use it in the templates. -
Loading the subsequent model based on the parent selection value
I have three django models as follows TYPES = [ ("A", "A Type"), ("B", "B Type") ] class TypeSelection(models.Model): id = models.AutoField(primary_key=True), type = models.CharField(choices=TYPES, max_length=2) class TypeA(models.Model): id = models.AutoField(primary_key=True), type_selection = models.OneToOneField(TypeSelection, on_delete=models.CASCADE), name = models.CharField(max_length=100, default="") class TypeB(models.Model): id = models.AutoField(primary_key=True), type_selection = models.OneToOneField(TypeSelection, on_delete=models.CASCADE), age = models.PositiveIntegerField() when the TypeSelection model is registered, it will give a dropdown to select between "A" and "B". I want to load the subsequent model (either TypeA or TypeB) in the admin page based on the selection i.e. I want to load the model TypeA with its respective field when "A" is selected from the dropdown and model TypeB with its respective field when "B" is selected from the dropdown. I see that there are ways to do it using custom JS. However, I am wondering if there's a more elegant way to do this. I can add more details to the question if it seems unclear. -
Is there a Flask extension that provides functionality similar to DRF's DefaultRouter class?
I have some experience with Django and Django Rest Framework (DRF). In DRF there's something called a DefaultRouter, which creates a basic CRUD with routes the 4 basic methods: GET, UPDATE, DELETE and POST. It's basically all I need in one line (there are some required settings, admittedly). Is there a Flask extension that provides functionality equivalent to this DefaultRouter class? I failed to find anything like it in SQLAlchemy or any Rest related extension. Any help would be deeply appreciated. -
DJANGO: Static files not loading in live server (but loads locally)?
Django website not loading the css and js scripts from static folder on the live server. But loads locally. Any ideas? The to css seems to be correct but does not go to the css style sheet itself. link to css on localhost host: <link rel="stylesheet" href="/static/website/login/login-style.css"> link to css on live server: <link rel="stylesheet" href="/static/website/login/login-style.css"> settings.py import os # other code... # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' login.html <link rel="stylesheet" href="{% static 'website/login/login-style.css' %}"> static folder structure: blah\project\website\static\website\login -
Django How to Load data to the initial base.html template
My initial template base.html must load menus with items dynamically loaded at the beginning. Is it possible? Some hints? -
Custom Message Tags Django
I am new to Django and I want to define some custom MESSAGE_TAGS. I am using Bootstrap alerts, so for example, I want a message tag for alert-primary and all the other colors. How could I do this? -
Why am I getting this error 'WSGIRequest' object has no attribute 'kwargs'?
I'm trying to create a comment section for my post, and I don't understand why I'm getting this error, here's the code so you can check it out, I'll only share the class in views.py were I'm getting the error views.py class AddCommentView(CreateView): model = Comment form_class = CommentForm template_name = 'app1/add_comment.html' def form_valid(self, form): form.instance.post_id = self.request.kwargs['pk'] return super().form_valid(form) #fields = '__all__' success_url = reverse_lazy('index') models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse from datetime import datetime, date from ckeditor.fields import RichTextField # Create your models here. class Category(models.Model): name = models.CharField(max_length= 255) def __str__(self): return self.name def get_absolute_url(self): return reverse('index') class Profile(models.Model): user = models.OneToOneField(User, null = True, on_delete=models.CASCADE) bio = models.TextField() profile_pic = models.ImageField(null = True, blank = True, upload_to = "images/profile/") website_url = models.CharField(max_length= 255, blank = True, null = True) facebook_url = models.CharField(max_length= 255, blank = True, null = True) twitter_url = models.CharField(max_length= 255, blank = True, null = True) instagram_url = models.CharField(max_length= 255, blank = True, null = True) pinterest_url = models.CharField(max_length= 255, blank = True, null = True) def __str__(self): return str(self.user) def get_absolute_url(self): return reverse('index') class Post(models.Model): title = models.CharField(max_length= 255) header_image = models.ImageField(null = True, blank … -
Javascript .on('click' is not working on span
So I've spend already 2 days trying to solve this. I have a <span class="faicon-add" data-id="id_object_places_proximity_keys-0-place_icon" rel="faicon-add"> and a jquery script loaded $( document ).ready(function() { var icon_field = null; $( '<div id="faicon-modal-cont"></div>' ).appendTo( "body" ); $( "#faicon-modal-cont" ).load( "/faicon/render_icon_list_modal/" ,function() { function close_over() { $('.faicon-screen').removeClass('show'); $('body').removeClass('faicon-active'); } $('.faicon-add').on('click', function(){ $('body').addClass('faicon-active'); $('.faicon-screen').addClass('show'); icon_field = $('#'+$(this).data('id')); }) $('.faicon-screen .close').on('click', function(){ close_over(); }) $('.faicon-screen .list li').on('click', function(){ var i = $(this).find('i'); var i_parts = $(i).attr('class').split(' '); icon_field.val($(i).data('icon')); icon_field.siblings('.icon') .html('<i class="'+i_parts[0]+' '+i_parts[1]+' fa-3x"><i>'); icon_field.siblings('[rel="faicon-add"]').hide(); icon_field.siblings('.faicon-delete').show(); close_over(); }) }); }); The problem is that $('.faicon-add').on('click', function(){ won't trigger... I've tried to add onclick="open_modal();" and directly placing this function under that span <script> function open_modal() { $('body').addClass('faicon-active'); $('.faicon-screen').addClass('show'); icon_field = $('#'+$(this).data('id')); } </script> And it worked, but that is not a solution for me, because I need to give a modal that icon_field variable... Also I tried to add only $('.faicon-add').on('click', function(){ function in the Google DevTools console. Then when I click on span, modal is showing up... That's weird... I've also tried to load script containing also only $('.faicon-add').on('click', function(){ function, but inside it I've put only alert('hello'). That didn't work... It's not a CSS issue, I've added z-index:1000;pointer-events:all; to that span and it's … -
Django Ajax error 403 link forbiden by load() method
I am trying to add a django url(template) in annother one using jquery ajax load() method but there is 403 url forbiden error in the console and when i test the url in the browser the page is displayed views.py def index(request): return render(request,'index.html',{}) def plans(request): plan = Plan.objects.filter(IdPlans=1) return render(request,'plans.html',{'plan':plan}) url.py urlpatterns = [ path('',views.index,name='index'), path('plans/', views.plans, name='plans'),]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) index.html where i want to add <div id="label1">CLICK HERE</div> <section id="liste"> </section> plans.html what i want to add {% for plan in plan %} <article> <img src="{{plan.Image.url}}"> <div> <h2>{{ plan.NamePlan }}</h2> <p>{{ plan.Description }}</p> </div> </article> {% endfor %} JAVASCRIPT LOAD METHOD $(document).ready(function(){ $("#label1").on("click",function(){ $("#liste").load('plans/',{ idcat: idcat, commentNewCount: commentCount }); }); -
list of current logged in users in django channels
i am trying to make a blog where i only wanted to show list of current logged in users. for this, i have used django channels. following is my codes myproject/settings.py: INSTALLED_APPS = [ 'channels', 'accounts', ..... ] ASGI_APPLICATION = 'myproject.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR,'site_static')] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media/') SESSION_EXPIRE_AT_BROWSER_CLOSE = True LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' myproject/routing.py: from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from django.urls import path from accounts.consumers import NewUserConsumer application = ProtocolTypeRouter ({ 'websocket': AuthMiddlewareStack ( URLRouter ( [ path ("new-user/", NewUserConsumer), ] ) ) }) myproject/urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path('', include ('accounts.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) accounts/consumers.py: import asyncio import json from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async from channels.generic.websocket import AsyncJsonWebsocketConsumer from .models import Profile from django.contrib.auth.models import User from django.template.loader import render_to_string class NewUserConsumer(AsyncJsonWebsocketConsumer): async def connect (self): await self.accept () await self.channel_layer.group_add ("users", self.channel_name) user = self.scope ['user'] if user.is_authenticated: self.update_user_status (user, True) await self.send_status … -
Implement row level permissions in multiple database django
I have to implement row-level permissions(object level) in Django, I find out that Django-guardian is a good option for this but problem is that I am using multiple databases in project one database has user table while another database has the table on which I want row-level permission and Django-guardian mentioned that they don't support multiple databases and many-to-many is also not an option because Django does support that across the database. Is there any other way to implement this -
Django passing Foreign Keys with multiple forms on a page
I am fairly new to Django and struggling a bit on how to get the primary keys from form input on a multiform view. I cannot get the keys into the database. I have 3 models: Human, Human_notes, and Location. My form is made of these separate models as forms on one view. I thought I should collect the primary key from each form once saved and apply that to the next form data as a foreign key... <form action="human-add" method="POST"> {% csrf_token %} {{ human_form.as_p }} {{ location_form.as_p }} {{ human_notes_form.as_p }} <button type="submit" class="save btn btn-success">Save</button> </form> Human has FKs to Location...: class Human(models.Model): intaker = models.ForeignKey(User, default=None, on_delete=models.SET_NULL, null=True) location = models.OneToOneField('Location', on_delete=models.SET_NULL, null=True, related_name='humans') Human_notes has FK to Human...(maybe this will become an FK in Human but originally thought many notes for one human) : class HumanNotes(models.Model): human = models.ForeignKey(Human, on_delete=models.SET_NULL, null=True, related_name='humans_notes') My view is: def human_add(request): if request.method == 'POST': human_form = HumanForm(request.POST) location_form = LocationForm(request.POST) human_notes_form = HumanNotesForm(request.POST) if human_form.is_valid() and location_form.is_valid() and human_notes_form.is_valid(): human_form.save(commit=False) location_form.save() locationKey = location_form.id human_notes_form.save(commit=False) human_notes_form.intaker = request.user human_notes_form.save() noteKey = human_notes_form.id human_form.location = locationKey human_form.note = noteKey human_form.intaker = request.user human_form.save() return redirect('/intake/success-form') else: context = { … -
Is it possible to dockerize Django flatpages?
I need to handle Django pages that don't have their own app, and the Django documentation recommends I use flatpages for one-off pages. However, these pages are stored in the database attached to Django, not the filesystem. This is causing issues because I can't transfer data in the database the same way I can transfer files in the filesystem. When I run the website through docker-compose, it starts with a fresh postgres image with no data. As a result, the flatpages are left behind anytime I re-run the docker container without migrating all of the data. The only solution I can think of is simply copying over the flatpages manually every time I bring the website to a new machine. Unfortunately, this seems like a terrible solution because it adds more deployment steps and goes against the ideology of dockerizing websites. Is there a better solution available? -
Pandas: Removing Pandas timestamp from DateField in all Columns
I can't remove timestamp from DateField in Pandas. for column in required_columns.values(): temp_df = values_df.loc[values_df[column] == ""] if len(temp_df.index): for row in temp_df.index: temp_df.groupby(temp_df.index).first() errors.append( f"Missing required value: Row {row+1} in column '{column}' in sheet '{sheet_name}'." ) if len(errors) >= 15: raise MissingRequiredValueError( message="Some required values are missing from the rows in the file.", errors=errors ) Few fields have DateTime Columns and need to remove timestamp in those columns. Please advise. -
Unable to store contact details in postgresql database?
try: form = ContactForm(request.POST) newform = form.save(commit=False) user = User.objects.create_user(request.POST['username'],request.POST['email'],request.POST['subject'],request.POST['message']) user.save() newform.user = request.user newform.save() return redirect ('success') except ValueError: return render(request, "jobs/success.html", {'form': ContactForm(),'error':'Bad data passed in. Try again.'})