Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Search Form Pagination Not Saving Filter Criteria To URL After Clicking Pagination Link
My search form is not saving the query string in the URL after clicking a pagination link after searching / filtering something. In other words, when I search by criteria, the form properly filters but then clicking the next pagination link causes that criteria to disappear and the pagination starts again as if there was no search criteria present. I want to keep that criteria in the URL throughout the pagination. How do I do this? HTML: form id='courseform' action="." method="get"> <div class="form-row"> <div class="form-group col-12"> {{ form.title__icontains }} </div> <div class="form-group col-md-2 col-lg-2"> {{ form.visited_times__gte.label_tag }} {{ form.visited_times__gte }} </div> <div class="form-group col-md-2 col-lg-2"> {{ form.visited_times__lte.label_tag }} {{ form.visited_times__lte }} </div> <div class="form-group col-md-2 col-lg-2"> {{ form.created_at__gte.label_tag }} {{ form.created_at__gte }} </div> <div class="form-group col-md-2 col-lg-2"> {{ form.created_at__lte.label_tag }} {{ form.created_at__lte }} </div> <div class="form-group col-md-2"> {{ form.skill_level.label_tag }} {{ form.skill_level }} </div> <div class="form-group col-md-2"> {{ form.subjects.label_tag }} {{ form.subjects }} </div> </div> <script src='https://www.google.com/recaptcha/api.js?render=6LeHe74UAAAAAKRm-ERR_fi2-5Vik-uaynfXzg8N'></script> <div class="g-recaptcha" data-sitekey="6LeHe74UAAAAAKRm-ERR_fi2-5Vik-uaynfXzg8N"></div> <button type="submit" class="btn btn-primary form-control">Search</button> <p>This site is protected by reCAPTCHA and the Google <a target="_blank" rel="noopener noreferrer" href="https://policies.google.com/privacy">Privacy Policy</a> and <a target="_blank" rel="noopener noreferrer" href="https://policies.google.com/terms">Terms of Service</a> apply. </p> </form> <div class="pagination"> <span class="step-links"> {% if page_obj.has_previous %} <a … -
Django label_for_id on CheckboxSelectMultiple widget not showing
I am trying to build a form containing a CheckboxSelectMultiple widget. When using the build-in rendering like so {{ f.activities }} I get the following result <ul id="id_reviewitem_set-0-activities"> <li> <label for="id_reviewitem_set-0-activities_0"> <input type="checkbox" name="reviewitem_set-0-activities" value="1" id="id_reviewitem_set-0-activities_0" /> Test </label> </li> ... An ID is generated for the field as a whole (as seen in the ul tag) and for each individual option (as seen in the input tag). This is the result I would expect. However, if I do the whole thing manually like so <ul id="{{ f.activities.id_for_label }}"> {% for option in f.activities %} <li> {{ option }} </li> {% endfor %} </ul> The ID for the activities field is not returned, so I get <ul id=""> <li> <label for="id_reviewitem_set-0-activities_0"> <input type="checkbox" name="reviewitem_set-0-activities" value="1" id="id_reviewitem_set-0-activities_0" /> Test </label> </li> ... It would be useful for me to have the id as I am using it for some js stuff. Is it possible to access the id of the field (i.e. "id_reviewitem_set-0-activities") or do I need to create my own in the template? -
Django exception middleware: simultaneously show traceback in browser and local console
While in development, I managed to redirect traceback messages (which by default appeared in the local console) to the client's browser console with some custom middleware. However, when doing this, the traceback no longer displays in the console. Is there a way to have it both in the local console, and in the client's browser? The middelware used (based on solutions from here and here): import traceback from django.http import HttpResponse class ErrorMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_exception(self, request, exception): tb = traceback.format_exc() return HttpResponse(tb) -
Strange query pattern showing in postgres slowlogs
I have started seeing strange queries with the pattern SET CONSTRAINTS ... IMMEDIATE; ALTER TABLE ... DROP CONSTRAINT showing up in the postgresql slowlogs. One of them also seemed to be the result of a pretty nasty deadlock that blocked all access to that table. My understanding of this query is that it sets a constraint for a particular table, then right after drops the constraints on the table (I omitted the name of the table and constraint). It seems kinda strange to me. I wasn't able to track down exactly where it's coming from, but it seems to correlate with a .bulk_create call in django. I guess my question has two parts. First, how would I verify that the query is coming from that particular line in django. I am also SUPER curious as to what the purpose of such a query coukd be since it seems to make no sense to me. If it helps, I am running django 1.11 and postgres 9.5. -
Django Expiration Job does not pass test
I am quite new to testing in Django, so please excuse any obvious blunders. For some reason, my test that is checking if the token is deleted is failing and I don't understand why. Perhaps I am doing the database query wrong? Thanks in advance! def delete_expired_auth_tokens(): expiration_time = make_aware(datetime.now() - timedelta(hours=TOKEN_LIFETIME_HOURS)) expired_tokens = DefaultTokenModel.objects.filter(created__lte=expiration_time) for token in expired_tokens: token.delete() class AuthTokenDeleteTest(TestCase): def setUp(self): now = datetime.now() date_to_delete = now - timedelta(hours=(TOKEN_LIFETIME_HOURS+1)) user_1, user_2 = User.objects.create(), User.objects.create(username='lol') DefaultTokenModel.objects.create(key='deletethistoken', created=date_to_delete, user_id=user_1.id) DefaultTokenModel.objects.create(key='dontdeletethistoken', created=now, user_id=user_2.id) delete_expired_auth_tokens() def test_does_not_delete(self): self.assertIsNotNone(DefaultTokenModel.objects.get(key='dontdeletethistoken')) def test_does_delete(self): self.assertIsNone(DefaultTokenModel.objects.get(key='deletethistoken')) -
How can you make a notification system without using a ridiculous amount of database space
I'm trying to figure a way to minimize database usage for a social media site I'm making, the original way I was going to make notifications was by making a notification class then saving the acting user and the action they performed (like posting a picture) and then using those objects in a dropdown which uses ajax to check for new objects every few seconds. But let's say I have 1,000 users and each posts 100 times, thats 100,000 notifications saved to the database and can't be deleted until all the users mark it as read. Wouldn't that be really inefficient and cost a decent amount? What if I used an HStoreField in postgres and had the key as the notification (that is displayed to the user) then use the value to redirect to the post and after redirecting, delete that notification from the Field? Then everything would be stored in that field but then I would have to query the database everytime I needed to delete something. Not to mention the fact that I would have to parse the information for getting the post. Would that work or am I just overthinking these things? I don't want to use … -
Fastest Way to Parse Large Body of Text into Pages using Flask/Django
What's the fastest way to parse a large body of text into page using Flask or Django? I'm working on parsing books into pages and rendering the parsed pages in a JSON. The raw text file does not have anything indicating page number. Therefore, we'll be parsing the page by number of words (about 400 words per page). The JSON response might look something like this: { book : {[ {page 1: Some example text....}, {page 2: Some example text....}, {page 3: Some example text....}, {page 4: Some example text....}, .... {page 1000: Some example text....} ]}} We would like to parse a book as large as Lord of the Rings. What's the fastest way to do this? Are there any package or external apis we could use? Thank you. -
Give permission according to data in Django
I'm working a project wherein there are multiple institutions. All the institutes have the same hierarchy of students, teachers and staff members. My problem is how do I keep the institutions apart? For example: the data profile of student from institute A should not be editable by a staff member in institute B. And vice versa. I'm able to use AbstractUser class to give my own roles but what about users (like Staff Members) who have the same permissions but shouldn't interfere with other institutions? -
django rest framework vin decoding
has anyone ever done vin decoding in django restframework? if yes please can you share example or if anybody knows how to do it can you show the piece of code please? I am going to do but I do not know how to do it. Thank you for understanding! -
How to filter with graphene.filter
I want to filter Notifications by user.username, how can I do it? models.py class Notification(BaseModelo): user = models.ForeignKey(User, on_delete=models.CASCADE) text = models.CharField(max_length=200) state = models.BooleanField(default=False) schema.py class NotificationNode(DjangoObjectType): class Meta: model = Notification filter_fields = ['user'] interfaces = (Node, ) class Query(ObjectType): user = Node.Field(UserNode)) all_users = DjangoConnectionField(UserNode) notification = Node.Field(NotificationNode) all_notifications = DjangoFilterConnectionField(NotificationNode) -
Line Graph in django template
To be very honest, I've played with matplotlib a little but iam new to django. I have wandered all over google to search to plot a line graph in django using csv. Unfortunately i couldnt find anything apart from 'bokeh' and 'chartit'. Although they arent very useful to help me make a start. My Goal: I need to plot a line graph, where x-axis have dates, y-axis have some numbers. Now, what should my views.py look like? What thing should i include in template? Anyone please help me out, or send me some provide some video tutorial to start with -
Django - creating a user through the admin interface with just an email, then allowing the user to complete the rest of the process themselves
So I have a rough idea of how to make this work, so I am looking for advice from anyone if I am barking up the right tree and if possible what areas I need to be looking into to make this work. The basic idea is explained in the title but I will try and provide more depth here: I would like to create a user on the admin interface, I will only know the person I am signing up's email at this point. So I want to make an account with just the email field occupied. With this I would then like to send an email to that person based on the email I used to sign them up. The email will then have a one time link similar to the password reset form. This link will take the user to an 'account creation' form, but instead of create an account for them one will already exist, so I want to the information they provide (username, first name, last name, password etc) to just update their existing account. I believe I have a rough idea on how I can do this but I am looking for a little … -
How I get data from model field and calculate with data from template?
hello I am new in django and I have some questions (I do not speek english so good ,sorry) I want to recive data from the template (input element) and calculate this with model data field. for exemple I have money_for_month = 1000$ in model field. and the input from the user is "3" (e.g. 3 month) so I want the result to be 3000$ store it in a variable and display it bellow the input element. if someone can help. thanks. this is my models class Mitnadv(models.Model): f_name = models.CharField(max_length = 30) money_for_month = models.CharField(max_length = 4) and this is my view class MitnadvDetailView(DetailView): model = Mitnadv template_name = "mit_app/mitnadv-detail.html" context_object_name = "mit" def post(self,request, **kwargs): num_m = request.POST["num-month"] self.list_var["num_month"] = num_m return HttpResponseRedirect(self.request.path_info) and this is my template <h2>pay for x mounth</h2> <form action="" method="POST"> {% csrf_token %} <input type="number" name="num-month"> <input type="submit" value="submit"> </form> -
How to implement Reactjs app into Django view?
I'll start with a little background on my situation. So initially I was just using a Django website. Both the front end and back end were handled by Django. Then I was tasked to create a Reactjs/Redux app to implement separate functionality. Now I would like to display my Reactjs app inside a Django template if possible. What is the best way to do this/is this possible? I found a video tutorial on a package called reactify-ui (I think it's called Reactify Django) which seems to do what I'm looking for, but I'm wondering if there is a different/better approach? Just ask if you need any additional information! Thanks! -
How to re use the code from a class based view - Django Rest Framework
I'm new to Django/Django rest framework class-based view. If it is a repeated question kindly excuse. Consider I have a class-based views like this. class UserBucket(APIView): def get(self, request): ... ... return Response(some_data) def put(self, request): ... ... return Response(some_data) class FilterView(APIView): def get(self, request): data_to_filter = request.query_params.get('filterData') # filter logic goes here ... ... return Response(filtred_data) If I want to use this FilterView code in the UserBucket's put method so that I can maintain DRY principle how can I achieve it? What I really want to do here is that from UserBucket put method I want to call the FilterView's get method with few arguments and get back the result. -
UnboundLocalError local variable 'comentarios' referenced before assignment
I dont know why I keep getting this error. UnboundLocalError local variable 'comentarios' referenced before assignment Here's the code where I use the variable def detallesPelicula(request, pelicula_id): peliculas = get_list_or_404(Pelicula.objects.order_by('titulo')) pelicula = get_object_or_404(Pelicula, pk=pelicula_id) actor = get_list_or_404(Actor.objects) comment_form = CommentForm(request.POST or None) if request.method == 'POST': if comment_form.is_valid(): idpelicula = request.POST.get('idpelicula','') fecha = timezone.now() texto = comment_form.cleaned_data['texto'] comentarios = Comentario.objects.filter(usuario=request.user,pelicula=idpelicula).order_by('fecha') comentarios.save() return HttpResponseRedirect(pelicula.get_absolute_url()) context = {'pelicula': pelicula, 'peliculas': peliculas, 'comentarios':comentarios,'comment_form':comment_form} return render(request, 'detallesPelicula.html', context) -
Django - int() argument must be a string, a bytes-like object or a number, not 'SimpleLazyObject'
I get this error after installing a component into a project running django 2.1 : int() argument must be a string, a bytes-like object or a number, not 'SimpleLazyObject' view class TrackLikeToggle(RedirectView): def get_redirect_url(self, *args, **kwargs): id = self.kwargs.get("id") obj = get_object_or_404(Post, id=id) url_ = obj.get_absolute_url() user = self.request.user if user in obj.likes.all(): obj.likes.remove(user) else: messages.add_message(self.request, messages.INFO, '1') obj.likes.add(user) return url_ Full Traceback: https://pastebin.com/FmkFKDW3 Thank you very much -
Why is my django session not working as specified in the view function
from time import time from django.shortcuts import render, redirect import requests, json from django.core.paginator import Paginator from django.http import HttpResponse from math import ceil def access_session1(request): url = "https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=stackoverflow" resp = requests.get(url) resp = json.loads(resp.text)['items'] paginator = Paginator(resp, 3) page = request.GET.get('page') print("reqiest", request.session) contacts = paginator.get_page(page) try: if request.session['count']: print("Inside Loop", request.session) if ceil(request.session['time'] - time()) <= 60: if request.session['count'] < 5: resp = request.session['count'] return HttpResponse(resp) # return render(request, 'StackAPI/home.html', {'contacts': contacts}) else: rsp = str(request.session['count']) return HttpResponse(rsp) # return render(request, 'StackAPI/warn.html') else: return render(request, 'StackAPI/warn.html') except: request.session['count']= 0 request.session['time']=time() rsp = str(request.session['count']) return HttpResponse(rsp) print(request.session['count']) if request.session.get('name') and request.session.get('password'): request.session['count'] += 1 return HttpResponse("<h1>Hello</h1>") # return render(request, 'StackAPI/home.html', {'contacts': contacts}) # return HttpResponse(response) else: return redirect('createsession') -
attributes of form elements don't show on the webpage (django)
Hope y'all good. In the code below, i tried to give attributes to the form fields, though except the username one, the rest wont accept the placeholder attribute. Do i have to use anything else except the 'TextInput'? (If needed i can provide other parts of the code) Thank You. With Respect Umer Selmani from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.forms import TextInput from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] widgets = { 'username': TextInput(attrs={'class': 'mycssclas', 'placeholder':'Username'}), 'email': TextInput(attrs={'class': 'mycssclas','placeholder':'Email'}), 'password1': TextInput(attrs={'placeholder': 'Password'}), 'password2': TextInput(attrs={'placeholder': 'Repeat Password'}) } class UserUpadteForum(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForum(forms.ModelForm): class Meta: model = Profile fields = ['image'] -
Url sent as parameter to $.ajax() function is not being used for handling the POST request
I'm trying to submit this form. I have other fields where I'm using ajax call for auto-sugestion. Before adding the below code, auto-suggestion works fine. But when I add the below code, aut-sugestion does not work. When I remove the code inside $.ajax() function, auto-sugestion works fine. And with this code, if I try to submit the form it does the POST request but url is localhost:8000 not the one I have provided as parameter in $.ajax() function. Also, when I try to look into the django shell for data, nothing is saved. Please help. I'm stuck here from last 3 hours. I tried everything that I could. $(document).on('submit', '#info-form', function(e){ e.preventDefault(); // this prevents from refreshing the page $.ajax( url: '/create/new/', //ajax call will be made to this url type: 'post', data:{ date:$('#tentative-date').val(), time:$('#tentative-time').val(), is_better:$('#is-better').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function(){ alert("Successful!"); } ); }); -
'git push heroku master' problem with heroku
When i want to deploy i get this in cmd: >> git push heroku master remote: ! WARNING: remote: ! Do not authenticate with username and password using git. remote: ! Run `heroku login` to update your credentials, then retry the git command. Note that article doesn't help: 'git push heroku master' is still asking for authentication -
Django custom AUTH_LDAP_USER_FLAGS_BY_GROUP
I'm working with a django ldap application and i'm in need to assign all users to a custom django group at user creation time. I understand that the AUTH_LDAP_USER_FLAGS_BY_GROUP option allow me to somewhat map a 'is_active', 'is_staff', and 'is_superuser' groups. What i want to is to map to a 'readonly' django group. Reading the docs i'm not figuring out. Is it possible? if so, how? -
when sent the mail it shows an error like,AttributeError: 'int' object has no attribute 'splitlines'
when sent the mail it shows an error like,AttributeError: 'int' object has no attribute 'splitlines',can slove this issue views.py from django.conf import settings from django.core.mail import send_mail from random import randint def send_emails(request,email): n = 8 range_start = 10**(n-1) range_end = (10**n)-1 passgenarate = randint(range_start, range_end) print passgenarate password = make_password(passgenarate) print password updatepassword = User.objects.filter(email=email).update(password=password) subject = 'newpassword' from_email = settings.EMAIL_HOST_USER recipient_list = email message = passgenarate send_mail(subject, message,from_email,[recipient_list], fail_silently=False, auth_user=None, auth_password=None, connection=None, html_message=None) -
How can I run an existing Django application?
What is the command-line command for running an existing Django app? I created the project and the app, but I forgot what the command to start the app was. -
django..db.utils.operationserror on port 5432
I am getting that error, along with message TCP/IP connections on port 5432. I HAVE installed psycopg2 2.8.4m, running Django 3.0 and python 3.6 I get that error, when I run my application firs ttimne.I am still unable to run my app first time. Is it because database not created yet? and I tried solutions posted here django.db.utils.OperationalError Could not connect to server but it did not help