Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django count queryset, show object instead of PK
I wrote a query to sort a count count query for biggest to smallest number. Basically a ranking system. users = Referrals.objects.values('friend_id').annotate(Count('friend_id')).order_by('-friend_id__count') It returns the value in json format like this <QuerySet [{'friend_id': 1, 'friend_id__count': 2}, {'friend_id': 5, 'friend_id__count': 1}]> now friend_id appears to be the primary key and yes, it links to the correct one(s) in my DB.. but I have no idea to get it to let it output the actual name / email or whatever based on that PK? This is my template where I'd like it to display the rankings. {% for a in users %} <tr> <td>{{a}}</td> <td>{{a}}</td> </tr> {% endfor %} Here's my full view for what its worth. @login_required def statspage(request): users = Referrals.objects.values('friend_id').annotate(Count('friend_id')).order_by('-friend_id__count') print(users) context = { 'users': users, } return render(request, 'stats.html', context) -
How to design django forms like this template
How to make this design in django forms? Django forms design -
Rounding down a number to nearest 1000 in Django template
I want to round a number down to the nearest 1000 in Django template. Something like {{ 123456 | round(1000) }} 123000 Is there a built-in way to do this in Django or should I just write a custom template tag? -
django orm group by + distinct
from django.db import models class Book(models.Model): name = models.CharField(max_length=100) author = models.CharField(max_length=100) published_years = models.DateField() concat = name + author What is the query for get books by 'concat' field, without doublons, and where published_years is the most recent date Exemple: <table> <tr><th>#id</th><th>name</th><th>author</th><th>published_years</th> </tr> <tr><td>0</td><td>nameA</td><td> author1</td><td> 1996</td></tr> <tr><td>1</td><td>nameA</td><td> author1</td><td> 1997</td></tr> <tr><td>2</td><td>nameA</td><td> author2</td><td> 1687</td></tr> <tr><td>3</td><td>nameB</td><td> author2</td><td> 1987</td></tr> </table> => <table> <tr><td>1</td><td> nameA</td><td> author1 </td> <td>1997</td></tr> <tr><td>2</td><td> nameA</td><td> author2 </td> <td>1687</td></tr> <tr><td>3</td><td> nameB</td><td> author2 </td> <td>1987</td></tr> </table> Thank you -
Url django with django rest framework
this is my url file for my "backend" application. router = routers.DefaultRouter() router.register(r'gamelogs', views.GameLogViewSet) router.register(r'referees', views.RefereeViewSet) router.register(r'players', views.PlayerViewSet) router.register(r'teams', views.TeamViewSet) urlpatterns = [ path(r'reports/<int:game_id>/)', views.get_pdf_report, name='get_pdf_report'), path(r'teams/<int:team_id>/)', views.get_team_formation, name='get_team_formation'), path(r'game-instance/<int:game_id>/)', views.get_match_instance, name='get_match_instance'), url(r'^api-auth/', include('rest_framework.urls')), url(r'^', include(router.urls)) ] Now if I go to 0.0.0.0:8000/backend/game-instance/1/ I get that the url does not exist. What's wrong? -
When I click on submit button on login page, its redirecting to an random csrf token page in django
When I clock on login page, it supposed to save the data in db but instead URL being redirected to csrf token page. url.py from django.conf.urls import url from . import views from django.contrib.auth.views import login, logout urlpatterns = [ url(r'^$', views.home), url(r'home',views.home, name='home page'), url(r'login',login,{'template_name':'section/login.html'}), url(r'logout',logout,{'template_name':'section/logout.html'}), url(r'register',views.register, name='register') ] views.py def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid: form.save() print('data has been saved') return redirect('section/home') else: form = UserCreationForm() args={'form':form} return render(request,'section/reg_form.html',args) reg_form.html {% extends "base.html" %} {% block body %} <br><br><br> <form action="post"> {% csrf_token %} {{ form.as_p }} <button type='Submit'>Login</button> </form> {% endblock %} -
Django url testing
urls.py of my web application is as follows urlpatterns = [ path('u/<int:unit_id>/', views.unit_view, name='unit_view'), path('u/<int:unit_id>/edit/', views.unit_edit, name='unit_edit'), ] I tried to write test as following. Unable to run the tests. Not even getting errors from django.urls import reverse, resolve class TestUrls: def test_unit_view_url(self): path = reverse('unit_view', kwargs={'unit_id': 1}) assert resolve(path).views.unit_view == 'unit_view' def test_unit_edit_url(self): path = reverse('unit_edit', kwargs={'unit_id': 1}) assert resolve(path).views.unit_edit == 'unit_edit' -
Django how to get request.get_host?
you for reading my problem.I am not getting the request get host .I am sending an email to the drivers those who registered in my app. I am sending a Booking link with their id in url.The problem is that i am not getting the host with it . For eg. http://127.0.0.1:8000/driver/3 after hitting the link i want him to redirect to the page where he can see the car. Views.Py from django.template import Context, Template as mailt @csrf_exempt def rentacar_carapp_approve(request): if request.POST: try: args['driver'] = driver = Driver.objects.get(id=request.POST.get('driver_id')) subject = "Please Register Your Car" from_email = settings.EMAIL_HOST_USER to_email = 'bakrshk@gmail.com' if to_email is not None: template = mailt("""Please hit the link and book a car {{ request.get_host }}{% url 'detail' driver_id=driver_id %}""") ctx = Context({'driver_id': driver.id}) join_message = template.render(ctx) send_mail(subject=subject, from_email=from_email, recipient_list=[to_email], message=join_message, fail_silently=False) print("email sent") print(request.get_host) except Driver.DoesNotExist: print("Driver doesn't exists") Url.py url(r'^drivers/(?P<driver_id>\d+)/$', rent_views.detail, name='detail'), Output in mail After sending email : Please hit the link and book a car /drivers/2/ but i want a proper link to send him in mail for eg http://127.0.0.1:8000/drivers/1/ -
Using Bootstrap 4 login form with django UserForm
Hey i want to use Bootstrap's login view with my UserForm but came up with few problems. This is the template: <body class="text-center"> <form class="form-signin" action="" method="post"> {% csrf_token %} <img class="mb-4" src="../../assets/brand/bootstrap-solid.svg" alt="" width="72" height="72"> <h1 class="h3 mb-3 font-weight-normal">Please sign in</h1> <label for="form.id_username" class="sr-only">Email address</label> <input type="text" id="form.id_username" class="form-control" placeholder="Email address" required autofocus> <label for="form.id_password" class="sr-only">Password</label> <input type="password" id="form.id_password" class="form-control" placeholder="Password" required> <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> <p class="mt-5 mb-3 text-muted">&copy; 2017-2018</p> </form> </body> My UserForm: from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): password =forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields =['username','password'] and my views.py: class LoginView(View): template_name = 'accounts/login_form.html' form_class = UserForm def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form':form}) def post(self, request): form =self.form_class(request.POST) user = authenticate(username =request.POST['username'],password=request.POST['password']) if user is not None: if user.is_active: login(request, user) return redirect('travel:main') form=self.form_class(None) return render(request, self.template_name,{'form':form}) def logout_view(request): logout(request) return redirect('travel:main') I basically want to authenticate the input from <input type="text" id="form.id_username" class="form-control" placeholder="Email address" required autofocus> against the form.username and input from <input type="password" id="form.id_password" class="form-control" placeholder="Password" required> against the form.password. Do you know where is the problem ? -
Unable to open database file - Mayan EDMS
I am using Ubuntu 16.04 and I installed PyCharm professional edition so I can run Django easy. I cloned Mayan EDMS from https://gitlab.com/mayan-edms/mayan-edms and after I installed all needed packages to run it in PyCharm. But I could not run it because I am getting error "unable to open database file". I am new to Django and can't figure out what to do. Nothing in tutorials said about fixing this. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f9fbe9438c8> Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/usr/local/lib/python3.5/dist-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.5/dist-packages/django/db/backends/sqlite3/base.py", line 198, in get_new_connection conn = Database.connect(**conn_params) sqlite3.OperationalError: unable to open database file The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 127, in inner_run self.check_migrations() File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 422, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/executor.py", line 20, in _init_ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/loader.py", line 52, in _init_ self.build_graph() File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/loader.py", line 209, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/usr/local/lib/python3.5/dist-packages/django/db/migrations/recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/usr/local/lib/python3.5/dist-packages/django/db/backends/base/base.py", … -
Override Django Unique_Together Validation by adding extra Field
I need some help in saving some records to the DB. Work for a parking app and i want to extend the way how unique_together queries the DB, by having an extra param. Just to understand what my situation is. E.g i give the user possibility of booking a plot on (parking_on) 25th from 9-18 the location P1. Because the way both of the filters are uniques to the DB, someone else can't book the same plot P1 on the same dat 25th but from 19-24 ==>therefore i need some kind of validation here or manually change the way how the unique_together validation works. Can someone please help? Please find below my models and admin from django.db import models from django.conf import settings from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ from datetime import datetime, timedelta, time from django.core.exceptions import NON_FIELD_ERRORS today = datetime.now().date() tomorrow = today + timedelta(1) now = datetime.now() l = now.hour m = int(now.strftime("%H")) class ParcareManager(models.Manager): def active(self, *args, **kwargs): return super(ParcareManager, self).filter(draft=False).filter(parking_on__lte=datetime.now()) class Parcare(models.Model): PARKING_PLOT = (('P1', 'Parking #1'), ('P2', 'Parking #2'), ('P3', 'Parking #3')) user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, default=1, on_delete=True) email = models.EmailField(blank=True, null=True) parking_on = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True, help_text='Alege … -
Is retrieving data from a redis instance slower than retreiving the same from Django's request.session dictionary?
In a Python/Django application, is retrieving a value stored in redis slower than retrieving one stored in the request.session dictionary? Background: I have a Django app where I use DB-based sessions. I.e., instead of using django.contrib.sessions, I used this nifty little 3rd party library. I recently ran a benchmark whereby I saved a test value in a local redis instance via the redis-py wrapper (i.e. my_server.set('test','1')). I saved the same test value in request.session['test']. I then retrieved the test value from each, and compared the time taken. request.session out performed redis by a factor exceeding 2x in this scenario. The application is not distributed in any way, everything is shared and happens on the same machine - very vanilla set up. The result appears counter-intuitive to me. Why? Because my sessions are DB based, and I thought redis would be faster than whatever Django has to offer. Clearly, I am wrong. Can an expert explain what's actually going on here? Maybe the python wrapper on redis' core API is slowing things down? In case you need more information, or are skeptical about how I ran the benchmark, please do ask. P.s. I simply put the two competing ways in a … -
how to render django forrms manually?
am new in Django. Does anybody know how to implement manual? I have newsletter app: newsletter/views.py from django.shortcuts import render from .forms import NewsUserForm from . models import NewsUsers # Create your views here. def newsletter_subscribe(request): if request.method == 'POST': form = NewsUserForm(request.POST) if form.is_valid(): cd = form.cleaned_data instance = form.save(commit=False) if NewsUsers.objects.filter(email=instance.email).exists(): print('your email Already exists in our database') else: instance.save() print('your email has been submitted to our database') else: form = NewsUserForm() context = {'form':form} template = "home/base.html" return render(request, template, context) newsletter/models.py from django.db import models # Subscribe models. class NewsUsers(models.Model): name = models.CharField(max_length = 30) last_name = models.CharField(max_length = 30) email = models.EmailField() date_added = models.DateField(auto_now_add=True) class Meta: verbose_name = "NewsUser" verbose_name_plural = "NewsUsers" def __str__(self): return self.email newslettter/urls.py from django.urls import path from .views import newsletter_subscribe app_name = 'newsletter' urlpatterns = [ path('subscribe', newsletter_subscribe, name='subscribe'), ] How to render this django forms manually, from third app to home template? And i have in home app base template with following code: home/templates/base.html {% csrf_token %} Sign Up or be classical <div class="input-group no-border"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="now-ui-icons text_caps-small"></i> </span> </div> <input type="text" placeholder="Last Name" class="form-control" /> </div> <div class="input-group no-border"> <div class="input-group-prepend"> <span class="input-group-text"> … -
bootstrap 4 collapse (accordion table) in django
I've posted the code for a table in django templates that is generated dynamically using an array from views.py. I've added a bootstrap4 collapse, that runs when a chevron button is clicked. However, it shows ALL of the hidden collapses instead of just the collapsible data for that given row (see img below). <table class="table table-hover"> <thead class> <tr> <th style="width:5%"></th> <th>Sample</th> <th>Reference</th> <th>Cost</th> <th>Sum</th> </tr> </thead> <tbody> <div class="container" id="accordion"> <div class="card"> {% for r in result %} <tr> <td> <button type="button" class="fa fa-chevron-right rotate" data-toggle="collapse" data-target="#demo" onclick=""> </button> </td> <td> {{ r.split.0 }} </td> <!-- sample word --> <td> {{ r.split.2 }}</td> <!-- ref word --> <td> {{ r.split.4 }}</td> <!-- cost --> <td> {{ r.split.3 }}</td> <!-- sum --> </tr> <tr id="map"> <td id="demo" class="collapse" colspan="5" > {{ forloop.counter }} {{ r }} </td> </tr> {% endfor %} </div> </div> </tbody> </table> -
Find the nearest Date on the basis of week of of day in django
Not able to understand how to get nearest upcoming date on the basis of day of week, for example the function could take 'Monday' or '1' and return DateField Object or Date string. -
Managing concurrency in Django
I'm working on a web app developed with Django, which serves a Rest API in order to book tickets. In order to do that, I've defined some views which interact with the database via the ORM. My app has some critical functions, such as the booking function. More or less, it has the following structure: def book(params...): # check ticket availability # define some stuff which will we added to the new ticket entity # save new ticket entity I don't know how does Django manages concurrency, therefore, I'm worried about the possibility of checking the availability of two bookings at the same time while just having availability for one of them. How likely is this to happen and which is the best approach to solve it? I've thought about defining that function as atomic, but I don't know how bad would it be for the system performance. -
Django Rest JWT authentication - refresh token
I have a problem with my Django REST application and JWT authentication module (https://getblimp.github.io/django-rest-framework-jwt) in phase of refresh token. Default logic of refresh token says that "non-expired tokens can be "refreshed" to obtain a brand new token with renewed expiration time". Expiration time is setting to BE. JWT framework provides an API for refresh token and you should use that for obtain new token and so expiration time reset every "user action" on web app. This means that every call to BE from my Angular6 SPA must reset expiration time of a token. I thought three ways to go: 1) Every call to BE from FE must call back api to refresh token. This means that number of calls are duplicate always. Not elegant! 2) Call api to refresh token according to an alghoritm (in FE) to avoid duplicated calls. Which alghoritm? 3) Reset expiration time of token to back end every call from FE, and use the same token from FE. I can not to do this! Any suggestions? Thanks -
How to use Django models from one app for connection to db replica from second app?
My system consists of two domains which are separate Django applications (let's say A and B) with own default databases and own users. Application B also reads from the application A database replica. To achieve such behaviour I included application A into B's INSTALLED_APPS and can access db replica through its models. But everything that is related to users (permissions, groups) is messed. Does using django.contrib.auth in both applications led to this behaviour, and is there a better solution to work with replica through Django ORM? -
How to use nested routes in Django
I have started using Django in my new project and I am stuck with problem. I would like to declare a route like POST /user/disqualify?user_id=<value> Attributes such has user_id will be passed as query parameters. I understand we are deviating too much from RESTful url guidelines, but I still would like to know how can I handle such url in Django2. My current url definition looks url('^user', User.as_view(), name='user'), and User is subclass of APIView. -
ImportError: bad magic number in 'time': b'\x03\xf3\r\n' in django
While running the Django app file which was downloaded from GitHub, I got this error. Anyone, please find the solution for this problem -
Django: Transmit GET-param after form-submit
I call my page with /?wohnungseinheit=1 as a(GET)-parameter. I would like to use the transmitted parameter as an assignment for the "wohnungseinheit". After I filled in and sent my "form", the GET-parameter is missing. How can I assign the "wohnungseinheit"? def mieter(request,id): if request.method == 'POST': form = MieterForm(request.POST) if form.is_valid(): tmp = request.GET.get('wohnungseinheit') mieter = form.save()#wohnungseinheit=tmp print(tmp) #result: None Wohnungseinheit = Wohnungseinheiten.objects.get(id=tmp) Wohnungseinheit.mieter.add(mieter) return render(request,'Immo/user/mieter.html',{'form':form}) # i think i also could use render_to_response else: if not str == None and str(id).isdigit(): #unimportant code here if blnAllowedAccess: form = MieterForm(request.POST) return render(request,'Immo/user/mieter.html',{'form':form}) else: #NOTALLOWEDTOACCESS! TODO pass else: tmp = request.GET.get('wohnungseinheit') if tmp is not None: form = MieterForm(request.POST or None) return render(request,'Immo/user/mieter.html',{'form':form}) else: pass #TODO: 404-error -
django JSONField regex
I'm using Django 2.1 and I have model with JSONField(record): { 'fields': [ {'tag': 'x','value': '12345'}, {'tag': 'y','value': '67890'} ] } To query exact 'value' I use: Data.objects.filter(record__fields__contains=[{'tag':'x', 'value': '12345'}]) My question is, how to use regex with 'value'? e.g. Data.objects.filter(record__fields__contains=[{'tag':'x', 'value': '/^123.*/'}]) -
Is there a django package that would allow me to obtain country from a Point field?
I am currently using GeoDjango and I have a Point field. Is there a django library out there that would allow me to obtain country from a Point field.Plus point if it gives me a zip code as well. I do not want to pay for external services. Something that is free. Will Django Countries help in this case ? -
how to remove an item from django session?
I do have two items in request.session.get('product_key'). I am trying to delete one product. m = request.session['product_key'] m.remove('768') when i am trying to delete one product from the session its getting deleted from the variable but not from actual session. when i am printing m its giving me single product while i am typing request.session.get('product_key') its giving me two products. So, how can i achieve so? -
zeep.exceptions.Fault: The message with To '' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher
I am integrating BSE StarMF (https://github.com/utkarshohm/mf-platform-bse) in django 2.0.2 and python 3.6. I am registering user through create_user_bse(user_id). While calling getPassword, I am receiving this error !! ** "zeep.exceptions.Fault: The message with To 'http://bsestarmfdemo.bseindia.com/MFUploadService/MFUploadService.svc/Basic' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher. Check that the sender and receiver's EndpointAddresses agree." **