Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin: Auto Logout And hosting questions
Question 1 Lets take a case where I just create a new Django file and create a new app. In this scenario, in the admin part, How do I ensure that the user gets logged out due to inactivity and also when the user closes all the tabs related to the website. [Im stating this scenario because all the documentations I've read so far seem a little too complex and dont explain to the point. I feel like this would help explain everything easily to a layman like me] Question 2, How do I host a website on my personal Lan Network on my IP address in such a way that the other users in my Network would have to enter a link like xyz.com or something? [My job requires me to make sure that the users dont have to remember my IP addresses because there are a lot of websites being hosted on the Lan at my work place] -
Does this test makes sense?
I'm currently learning how to write tests for a Django application. The guy in the tutorial video wrote the following test for his application: def test_product_url(self): path = reverse('product_detail') self.assertEqual(resolve(path).view_name, 'product_detail') I don't understand how this test makes sense. It just tests if the django resolve functions works correctly right? -
How to accept an Array payload not on a Model table in DjangoRestFramework [Python3.6]
When the code below was ran, I got a 'create' method not implemented error. How do I create a create method on a model that doesn't have an applicant field. What's the best way to handle this? Payload data (as in POSTMAN): { "applicants": [{"id": 1, "status": 2}, {"id": 12, "status": 3}, {"id": 11, "status": 2}] } My serializers.py file: class StringListField(serializers.ListField): applicants = serializers.CharField class UpdateApplicantSerializer(serializers.Serializer): applicants = StringListField() Models.py file: class Applicant(models.Model): APPLICATION_STATUS = ( (1, 'Pending'), (2, 'Accept'), (3, 'Reject'), ) first_name = models.CharField(max_length=200, blank=False, null=False) last_name = models.CharField(max_length=200, blank=False, null=False) email = models.EmailField(max_length=200, blank=False, null=False, unique=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True, null=False, unique=True) # validators should be a list linkedin_url = models.URLField(max_length=255, unique=True) #make sure diff users cant use two same profile twitter_url = models.URLField(max_length=255, unique=True) #make sure diff users cant use two same profile articles = ArrayField(models.URLField(), blank=False, null=False, unique=True, size=3) country = models.ForeignKey(Country, on_delete=models.CASCADE, blank=False, related_name="applicant") category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="applicant", blank=False) status = models.CharField(max_length=200, choices=APPLICATION_STATUS, default=1) -
How to run cloned Django project
I cloned the Django project "cs3" and want to open .html files within the "project" folder. When I open them, however, the python and CSS does not load. How can I fix this? My folder configuration -
sys.path is incorrect when starting pywin32 service installed with virtualenv (Django project)
I'm trying to setup a windows service that will run my Django project with CherryPy and Python3.6. I've done this successfully with Python3.5, but upgrading causes sys.path to appear as though no virtualenv is active. When attempting to run the service, I get a Services error that says "Windows could not start the Project CherryPy Service on Local Computer. For more information, review the System Event Log. If this is a non-Microsoft service, contact the service vendor, and refer to service-specific error code 1." Viewing the event log, I can see that Django won't load: from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' After inspection, I can see that non of my projects virtualenv paths are in sys.path except for "...\lib\site-packages\win32" which is appended twice for some reason. So how do I get the service to run with the correct virtualenv active without manually appending each path needed (so that it works with future development etc)? The following works with Python3.5: CherryPyService.py: import cherrypy import win32serviceutil import win32service import sys import os from my_project import wsgi DEPLOY_DIRECTORY = "C:/home/code/my_project/" ERROR_LOG = os.path.join(DEPLOY_DIRECTORY,"service_logs","cherry_py_err.log") STD_ERR = os.path.join(DEPLOY_DIRECTORY,"service_logs","std_err.log") STD_OUT = os.path.join(DEPLOY_DIRECTORY,"service_logs","std_out.log") sys.stdout = open(STD_OUT,'a') sys.stderr = open(STD_ERR,'a') class ProjectService(win32serviceutil.ServiceFramework): _svc_name_ = "ProjectCherryPyService" β¦ -
Add a date range column to Queryset
Django newbie, thanks in advance for any help. I want to add a field that includes a date range for a grouping. The date range would look like "1/1/2018 to 1/2/2018" where the first date is the minimum date and the second is the maximum date in the set for a particular name. qs = Qs.objects.filter(**filter_kwargs) \ .values('name') .annotate(v1 = Sum('something') , DATE_RANGE = Min('date') + ' - ' + Max('date')) .order_by() The end goal is to be able to display this in the template. -
Page not found (404): django cannot match the path
I don't understand why I am getting a 4040 error while it seems I have defiend everything correctly. The Ticket model class has instances saved in the database so pk from 1 to 5 also exists. The html template is the simplest possible just to figure out why django cannot get and render the requested instance. Note that I can see the instances in the admin page and also other paths like adding new ticket etc are working fine. Any help is appreciated: the path/page that I am trying to get: http://127.0.0.1:8000/ticket/1/ app: urls.py from . import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'ticket/<int:pk>/', views.ticket_detail, name='ticket_detail'), ] project: urls.py from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('mmrapp.urls')), ] views.py def ticket_detail(request, pk): ticket=get_object_or_404(Ticket,pk=pk) return render(request,'mmrapp/ticket_detail.html',{'ticket':ticket}) html {% extends 'mmrapp/__l_single_column.html' %} {% load static %} {% block main_col %} <div class="ticket"> <h2>Ticket: {{ticket.pk}}</h2> </div> {% endblock main_col %} -
Creating a cartesian product with the Django ORM
I currently have three tables; Person, Item and a many to many mapping table called PersonItems. I am looking to output a HTML table of all persons down the left column, then the table header will be the Items. A person may or may not have the item based on an entry in the PersonItems table, which I will indicate in the corresponding cell. Ultimately I will have a HTML table output form a Django template containing Person multiplied by Item 'td' elements. There could be up to about 5000 persons, but only around 30 items. I aimed to produce this table by creating a cartesian between Person and Item, and for each combination, checking if there is an entry in the PersonItem table. The problem I'm having is creating a cartesian product of the Person and Items table, which is then joined against the PersonItems. The only way I can see to do this without SQL is to iterate all Persons, and for each person perform a query to see if the person has the item. However that approach is quite a bit slower than using a raw SQL query. I have experimented with the iteritems.product function to create β¦ -
using return data in models django
I'm fairly new to Django and Python and I'm trying to develop a small website to calculate the total number of minutes per day on a certain period of time. So far I made a model containing fields with all the information I need, and two functions in the model that calculates the number of days and the number of minutes in a time period. But now I'm stuck. I've been trying to multiply the results of my functions, but I can't manage to do it. I don't know if I'm doing this the right way or the most efficient way, I'm open to all advices to improve my code Thanks a lot class Vacation (models.Model): reference = models.CharField(max_length=30, default='test') start_date = models.DateField(default=0) end_date = models.DateField(default=0) start_hour = models.TimeField(default=0) end_hour = models.TimeField(default=0) monday = models.BooleanField() tuesday = models.BooleanField() wednesday = models.BooleanField() thursday = models.BooleanField() friday = models.BooleanField() saturday = models.BooleanField() sunday = models.BooleanField() @property # these are not the actual functions but only the results they give me def calcul_jours(self): work_days = [1, 1, 0, 0, 1, 1, 0] day_list = [6, 6 , 0, 0, 7, 7, 0] return day_list def calcul_heures(self): day_minutes = [180, 90, 0, 0, 90, β¦ -
Embed Bokeh with Django model
I have python program in one development environment to stream data and save Bokeh div and script components to a file on a database. The webserver in a different environment serves the div and script components from the database as the webpage is requested. Viewing the html page source (shown below) seems to display the whole Bokeh package correctly with no visual errors but there is no graph. Please advise. As a side note, I tried how to embed standalone bokeh graphs into django templates, (rendering a graph in the views.py at each page request), but this also failed in my web framework: models.py: from django.db import models class Item(models.Model): name = models.CharField(max_length=32) description = models.TextField() image = models.ImageField(blank=True, null=True) script_com = models.FileField(blank=True, null=True) div_com = models.FileField(blank=True, null=True) def __str__(self): return self.name def get_image(self): return self.image def display_script_com(self): with open(self.script_com.path) as f: return f.read() def display_div_com(self): with open(self.div_com.path) as f: return f.read() views.py: from django.shortcuts import render from sentiment_analysis.models import Item def index(request): return render(request,'sentiment_analysis/index.html', { 'itemContext':Item.objects.get(id=1) }) def get_update(request): return render(request,'sentiment_analysis/index.html', { 'itemContext':Item.objects.get(id=1) }) index.html: {% extends 'sentiment_analysis/layout.html' %} {% block content %} <style> .imgbox { display: grid; height: 100%; } .center-fit { max-width: 100%; max-height: 100vh; display: block; β¦ -
How to update Django's template after backend change
everyone. I'm starting with Python and Django and I want to add some Ajax to my code. I'm practicing by showing a product on the template along with an input to change the price of it. I have been able to change his value on the DB but after that I'd like to update the template's context in order to see the new value. The field that I want to get updated is the last row of the table. {% csrf_token %} <table> <tr> <th>Product</th> <td>{{product.name}}</td> </tr> <tr> <th>Price</th> <td><input id="price" type="text" value="{{product.price}}" placeholder="Price" autocomplete="off"/></td> </tr> <tr> <td colspan="2" style='background:none'><input id="send" type="button" value="Update"/></td> </tr> <tr> <th>Current values:</th> <td>{{product.name}} : ${{product.price}}</td> </tr> </table> The JS: $("#send").click(function(){ $.post("/inicio/acciones/update/", {search: 1, price : $("#price").val()} ).done(function(res){ }) }); Backend def update(request): """backend changes ... """ t = loader.get_template('inicio/index.html') product= Product.objects.get(pk=search) context = { 'product' : product, } t.render(context) return HttpResponse(product.price) The 'product' var has the right values but my template is not updated. How can I update the context? -
Processing from foreignkey table fields while creating multiple objects in django rest?
Models.py class Season(models.Model): name = models.CharField() statuses = models.CharField() class Match(models.Model): SHOT_CHOICES = ( ('W', 'Win'), ('F', 'Fail'), ('D', 'Draw'), ) season = models.ForeignKey(Season, on_delete=models.CASCADE) status = models.CharField(choices=STAT_CHOICE, max_length=1) My view for creating matches class CreateMatches(generics.CreateApiView) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, many=True) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) statuses is a string like "WFFWFDDW", I need to fetch "nth" character from the foreign key season while a modelserializer with above view is used for creating "nth" match. -
Making changes to Python and DJango files on Ubuntu
So I am running django on my Ubuntu instance. I am new to using ubuntu but I am running this very sensitive server where I can not afford to allow it to crash. I plan on making some changes to some py and html files but was wondering what the following steps would be to allow for a smooth update. I am running Django, uwsgi, Nginx and Supervisord. My partner had left with very little notes who would usually be in charge of this all. -
How to Increase User Security on a Django App?
How can I increase the user account security for a django app? Can it be done without creating a API with Django Rest Framework? -
How to use different Dockerfile for production with docker-compose?
I am very new to Docker and have just set up a basic docker-compose.yml and Dockerfile for my projet following the official guide Quickstart: Compose and Django. Here's my projet architecture : . βββ my_project β βββ __init__.py β βββ settings_prod.py β βββ settings.py βββ docker-compose.prod.yml βββ docker-compose.yml βββ Dockerfile βββ Dockerfile-prod βββ my_app β βββ ... βββ ... βββ requirements.txt My Dockerfile and docker-compose.yml are both working as expected for a dev environment but now I need to deploy the project in production. Thanks to the docs, I know I can use several docker-compose.yml with the following command: docker-compose -f docker-compose.yml -f docker-compose.prod.yml [--build] up But now I need to replace settings.py by settings_prod.py in my production container. How can I do that ? Currently, Dockerfile contains all commands required to build the appropriate container while Dockerfile-prod only contains ADD my_project/settings_prod.py /code/my_project/settings.py. But that might not be the way to do what I want. -
Ajax Image Upload - cannot upload .pic has no file associated with it
I'm trying to upload image using ajax. The form takes inputs from the user and after submit the post should load into the div without page refresh and also save in the model. Im not able to receieve the file in the view and im also getting a csrf token error with status code forbidden when using form data with ajax.Image is uploading and displaying after adding from admin side. This is my form in home.html <form action="" method="POST" class="my-ajax-form" enctype="multipart/form-data" > {% csrf_token %} Post Title:<br> <input type="text" name="title" id="titles"><br> Post Text:<br> <input type="text" name="text" id="text"><br> Image: <input id="image" type="file" name="image"><br> <input type="submit" value="submit" class="btn btn-primary" name="" id="submit"> </form> models.py: class Post(models.Model): user= models.ForeignKey(User, on_delete=models.CASCADE) heading = models.CharField(max_length=200, null=False) text = models.TextField(null=False) created_date=models.DateTimeField(default=timezone.now) pic = models.ImageField(upload_to='image', blank='True') def __str__(self): return self.heading def getuser(self): return self.user.username def total_likes(self): return Like.objects.filter(post=self).count() class Like(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) post = models.ForeignKey(Post,on_delete=models.CASCADE) def __str__(self): return self.post.heading plugin.js: var $myForm = $('.my-ajax-form'); $('#submit').click(function(event){ event.preventDefault(); $.ajax({ method:'POST', url: 'save/', data:{ title : $('#titles').val(), text : $('#text').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, datatype:'json', success: function(data) { console.log("Post Added!"); console.log('DATA: ',data) datas=$.parseJSON(data) console.log('author: ', datas.text) $('#postlist').prepend('<form class="like_form"><div class="postcard"><p>Author: '+ datas.author+'</p><p>Created Date: '+datas.created+'</p><p>Title: '+datas.title+'</p> <p>'+datas.text+'</p><p><img src="'+datas.image +'" width="300px"> </p> <div class="like-section">'+' β¦ -
Using a different Manager with refresh_from_db()
I have model set up in a way that it never gets deleted, instead a status is updated to status 'DELETED'. To achieve this I have overridden the delete() method as following def delete(self, using=None, keep_parents=False): self.status = Booking.DELETED self.save() And added two custom managers to track deleted an non deleted bookings, the standard manager is swapped with on that only returns non deleted objects. class BookingManager(models.Manager): def get_queryset(self): return super().get_queryset().exclude(status=Booking.DELETED) class BookingDeletedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status=Booking.DELETED) class Booking(models.Model): PAYED = 0 PENDING = 1 OPEN = 2 CANCELLED = 3 DELETED = 4 objects = BookingManager() deleted_objects = BookingDeletedManager() ... Now when i have a booking object and delete it like this booking.delete() And refresh it like this booking.refresh_from_db() I get the error .models.DoesNotExist: Booking matching query does not exist If i use the correct manager Booking.deleted_objects.get(pk=booking.id) I get the booking correctly presented to me, I am assuming the refresh_from_db method used the standard objects manager which does not find the correct Booking. is there a way to get around this or am i approaching this problem wrong? -
what changes need to be made to django tenant schema to support a fixed url for all tenants?
I am using the django multi-tenant schema application to design multi-tenancy in my django project. What all changes need to be made to customize it to be able to use it with a fix url for all tenants. -
Get all id of the selected rows in my ModelAdmin (Django)
In the django admin page, I created a button:RUN . I would like to click on this button to retrieve the id of the selected lines of the team table. Here is a preview of the button in the Admin page: Here is the code for the button: class ImportAdmin(admin.ModelAdmin): change_list_template = 'team/admin/change_list.html' model = team_temp My template: change_list.html <div class="container" align="center"> <form class="btn-group" id="login_form" method="get" action="/team/team_temp/"> <input type="hidden" id="ids" name="ids" value = {{ ???? }}> <button class="btn btn-warning btn-lg" id="team_temp" name="team_temp" type="submit">RUN</button> </form> </div> My View: def team_temp(request): print(self.request.GET.get('ids')) return redirect(reverse('home')) -
Factory-boy property attributes?
I have a recipe like this: import factory from models import Foobar class MenuItemFactory(factory.Factory): class Meta: model = MenuItem name = 'Default Foobar' slug = factory.LazyAttribute(lambda o: '%s' % o.name) I want to add dynamic properties, like slug, but I want to do it in a separate method. I want this, since writing any more complex logic in lambda one-liners would be, well, ugly. One thought came to mind, using a property method, like they do in Django models. For example: class MenuItemFactory(factory.Factory): ... @property def slug(self): return '%s' % self.name Is there a way, similar to this, that will accomplish what I'm trying to do? -
"couldnt import django.Are you sure its installed..." in the middle of migration
I have django installed and it has been working in my ubuntu environment for months now. I just tried to do a migration and it completed a few of the migrations then gave the error "Couldnt import Django. Are you sure its installed and available on your PYTHONPATH environment variable?..." I am using a virtual env and it is active. also if I try another command like python manage.py collectstatic everything works fine. Has anyone ever seen anything remotely like this before?? What is going on?? -
TypeError at /edit/ __init__() got multiple values for argument 'data'
I am trying to update user profile in Django 2.1 and Python 3.6.5 but am running into this error. TypeError at /edit/ init() got multiple values for argument 'data' views.py from django.shortcuts import render from django.contrib.auth import authenticate, login from . forms import LoginForm, UserRegistrationForm, UserEditForm, ProfileEditForm from django.http import HttpResponse from django.contrib.auth.decorators import login_required from . models import Profile from django.contrib import messages @login_required() def edit(request): if request.method == 'POST': user_form = UserEditForm(instance=request.user, data=request.POST) profile_form = ProfileEditForm(request.user.profile, data=request.POST, files=request.FILES) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, 'Profile Updated Successfully!') else: messages.error(request, 'Error Updating Profile!') else: user_form = UserEditForm(instance=request.user) profile_form = ProfileEditForm(instance=request.user.profile) return render(request, 'account/edit.html', {'user_form': user_form, 'profile_form': profile_form}) edit.html {% extends 'account/base.html' %} {% block title %}Edit Account{% endblock %} {% block content%} <h1>Edit Your Account:</h1> <form action="." method="post" enctype="multipart/form-data"> {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }} <p><input type="submit" value="Update"> </p> </form> {% endblock %} -
Django-tables2 RowSpan
I tried to make a table with rowspan when the cells in the same column have the same value. Like in this image And i want to make it with django-tables2 I tried this code line but it shift the X1 to the field2 column at the second record. Thanks in advance. -
How to subclass Django 2.1 LoginForm and LoginView properly
i'm currently facing a quite stupid problem. i want to subclass LoginView and LoginForm from django.contrib.auth.forms/views in Django 2.1 to add a Captcha from "django-simple-captcha" to the Login. so i start searching for a solution and i already opend a request here on stackoverflow, see: Django Custom Login - Form is valid but no error but the mentioned solutions do not fit in this context due that a captcha field only can be placed into a form. Can somebody explain how i have to subclass this? this is my current state of my own accounts app within my project: accounts/views.py def login (request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): form.save() messages.add_message(request, messages.INFO, "You are now logged-In, welcome") return redirect(reverse('post_list')) else: form = LoginForm(request) args = {'form': form} return render(request, 'registration/login.html', args) accounts/forms.py: class UsernameField(forms.CharField): def to_python(self, value): return unicodedata.normalize('NFKC', super().to_python(value)) class LoginForm(forms.Form): """ Base class for authenticating users. Extend this to get a form that accepts username/password logins. """ username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True})) password = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput, ) error_messages = { 'invalid_login': _( "Please enter a correct %(username)s and password. Note that both " "fields may be case-sensitive." ), 'inactive': _("This account is inactive or β¦ -
Handing session expiration in Django/React
We've added a middleware to implement session timeout. We see that once the session is expired, Django redirects to /signin but React which expects its regular response (one of many) throws an exception. How can I change React to handle Django session timeout and redirect to /signin? Thanks