Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What's the point of using namespace inside include? (Django 2.0)
What's the point of using namespace inside include, if adding app_name in the app's urls is the one that actually lets me use the "app:view" syntax. Blog_app/urls.py from django.urls import path from django.views.generic.base import RedirectView from . import views app_name = 'posts' #APP_NAME urlpatterns = [ path('',RedirectView.as_view(url='posts/'), name='home'), path('posts/',views.post_list, name='list'), path('posts/detail/<int:pk>',views.post_detail, name='detail'), path('posts/delete',views.post_delete, name='delete'), path('posts/create',views.post_create, name='create'), path('posts/update',views.post_update, name='update'),] Project/urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog_app.urls',namespace='posts')),] this code works for reversing the url to posts/detail like this example.html <a href="{% url 'posts:list' %}"> Example <a/> but if delete the namespace it stills reverses my url to posts/detail Project/urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog_app.urls')), #NAMESPACE DELETED ] -
Django save request delay too long
My question is if it's possible to raise an error if, when saving a model, the delay time response of the request is too long. Is it only possible at web server level? Is this an issue that can happen or is it common? It's no currently happening to me, and I'm developing as localhost. I've added a "waiting for..." modal when the submit button is pressed, which raise the doubt I'm posting. Thanks. -
SyntaxError: expected expression, got '}' on Django
I do not know why my code just decided to break this morning. Running a a Django server and the script is located in a static directory. https://pastebin.com/BfzrHiLe setInterval("changeHeaderColor()",300); setInterval("changeBorderColor()",305); setInterval("changeXColor()",300); It says there is an error on line 90 -
Sending Emails through Django - WinError 10060 A connection attempt failed and GetAddrInfo Error
I've been running an instance of Django on Windows R2 2012 for over a year and I've come to a road block. Yesterday something happened, I don't know what it could be. The same two errors keep popping up at different times though when trying to send an email: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond and socket.gaierror: [Errno 11001] getaddrinfo failed Users are able to connect to the IP address of the server and the port Django is running on 192.168.1.5:8000, but they cannot send emails anymore. Though a percentage do go through as described here, but very few. Things I've tried 1) This solution import socket socket.getaddrinfo('localhost', 8000) Since I'm doing python manage.py runserver 192.168.1.5:8000, I added that IP and nothing. 2) I went into the Firewall settings and made sure that the ports were all good. The SMTP one that is declared in the setting.py file in my Django project and 25. All of them, inbound and out. 3) I tried sending things on my local machine and it does work. I used other … -
Django - How to specify nullable on reverse relation of OneToOne?
How do I specify that the reverse relation of a OneToOne is nullable, but the forward relation is not? (sorry if I mixed up forward and reverse) In this example, Something.other can be null and Other.something cannot be null: class Something(Model): name = CharField(...) value = CharField(...) class Other(Model): name = CharField(...) value = CharField(...) something = django.db.models.OneToOneField(Something, related_name="other") -
DRF Serializer update list of nested objects
I write the voting app project using Django-rest-framework. It has two models: question and nested answer. I want to update answers in question serializer upon request such as: { "question":"question", "answers": [{"answer":"first updated answer"}, {"answer":"second update answer"}] } How can I do it properly? I tried to do it, but I deleting answers in every request and create new ones, because of that changes their id every time. serializer.py class QuestionSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField() answers = AnswerSerializer(many=True) class Meta(object): model = Question fields = ('id', 'question', 'answers', 'total_votes', 'user') read_only_fields = ('id', 'total_votes', ) def update(self, instance, validated_data): instance.question = validated_data.get('question', instance.question) instance.save() question = Question.objects.get(id=instance.id) Answer.objects.filter(question=question).delete() answers_data = validated_data.pop('answers') for answer_data in answers_data: Answer.objects.create(question=question, **answer_data) return instance models.py class Question(models.Model): question = models.CharField(verbose_name='Question', max_length=255) total_votes = models.IntegerField(verbose_name='Total Votes', default=0) user = models.ForeignKey(User, verbose_name='Owner', on_delete=models.CASCADE) class Answer(models.Model): question = models.ForeignKey(Question, verbose_name='Question', related_name='answers', on_delete=models.CASCADE) answer = models.CharField(verbose_name='Answer', blank=True, max_length=255) votes_count = models.IntegerField(verbose_name='Count of Votes', default=0) -
How to prevent update a column in Tastypie
class Hello(models.Model): name = models.CharField(max_length=8, blank=True) column_create_no_update = models.CharField(max_length=8, blank=True) class HelloResource(ModelResource): def dehydrate(self, bundle): if (bundle.request.META['REQUEST_METHOD'] == 'PUT') and ('column_create_no_update' in bundle.data.keys()): del bundle.data['column_create_no_update'] return bundle 1) Create a record createData['name'] = 'foo name'; createData['column_create_no_update'] = 'don't update me'; Ajax POST creates a record in db. 2) When updating the table with ajax call, updateData['name'] = 'foo name updated'; Ajax PUT update the record. No 'column_create_no_update' is provided in update. I noticed in function dehydrate(), bundle.data['column_create_no_update'] = '' and bundle.data['column_create_no_update'] is deleted. only bundle.data['name'] exists after delete when 'bundle' is returned. But, in database, 'column_create_no_update' is updated with ''. I want it to be preserved: column_create_no_update = don't update me'. Why it's updated with ''? -
Why is __init__ not being called on this Django model subclass?
It appears the ContentImage model class below's __init__ method is not being called. When I make migrations, the changes to the image_width field's arguments are not being reflected. The similar __init__ method in the ProcessedImage class works as expected, so I'm stumped. Note: All this inheritance is due to the first two classes being in a generic reusable app and the second two being in an app with more specific functions. class BaseMixin(models.Model): created = models.DateTimeField( auto_now_add=True, ) updated = models.DateTimeField( 'last updated', auto_now=True, ) generated_name = models.CharField( max_length=254, blank=True, null=True, ) extra_text = models.TextField( blank=True, ) saved_file = models.FileField( 'uploaded file', storage=RemoveOldFile(), upload_to=create_file_path, validators=[], max_length=254, ) class Meta: abstract = True class ProcessedImage(BaseMixin): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._meta.get_field('saved_file').validators = [ CheckExtMIME(allowed_attributes=CHECK_RAW_IMAGE), ] output_width = models.PositiveIntegerField( blank=True, null=True, ) output_height = models.PositiveIntegerField( blank=True, null=True, ) processed_file = models.FileField( storage=RemoveOldFile(), upload_to='images/processed/', blank=True, null=True, ) class ImageElement(ProcessedImage): description = models.CharField( 'screen reader description', max_length=254, ) caption = models.TextField( 'image caption (optional)', blank=True, ) image_width = models.PositiveIntegerField( 'image size', choices=[], default=0, ) class Meta: abstract = True class ContentImage(ImageElement): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) new_width = self._meta.get_field('image_width') new_width.choices = WIDTHS_CONTENT new_width.default = 200 content_element = models.OneToOneField( ContentSection, on_delete=models.CASCADE, ) -
Django: sorting by datetime field is only accurate to minutes, not seconds?
Is there a way to make Django consider seconds (and even milliseconds) ordering a queryset by a DateTime field? I want to display a table with the results of my blood tests ordered in reverse chronological order. It works, as long as tests aren't added in the same minute. If they are only separated by seconds, they are listed in chronological order for the duration of that minute. models.py class BloodTest(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) name = models.CharField(max_length=20, choices=BLOOD_TEST_CHOICES, default=BILIRUBIN) value = models.PositiveSmallIntegerField(max_length=10) time = models.DateTimeField(default=timezone.now(), validators= [validate_date]) views.py def blood_list(request, blood_id): blood = BloodTest.objects.get(id=blood_id) patient = blood.patient blood_list = BloodTest.objects.filter(name=blood.name).filter(patient=patient.id).order_by('-time') context = {'blood_list': blood_list, 'patient': patient, 'blood': blood} return render(request, 'vitals/blood-list.html', context) blood-list.html template {% for blood in blood_list %} <tr> <td>{{ blood.time }}</td> <td><a href="{% url 'blood' blood.id %}">{{ blood.value }}</a></td> </tr> {% endfor %} -
How to get value especific from ModelForm field in django framework?
I am creating one web system and need to get one value especific from ModelForm for store in another system, in addition to storing in django. Example: get field "nome" from Model Form for to store in LDAP server model.py class Orientado(models.Model): nome = models.CharField(max_length=100,) telefone = models.CharField(max_length=20) email = models.EmailField(max_length=100) forms.py class OrientadoForm(forms.ModelForm): class Meta: model = Orientado fields = ['nome', 'telefone','email'] views.py def person_new(request): form = OrientadoForm(request.POST or None, request.FILES or None) autor = User.objects.get(username=request.user.username) if form.is_valid(): form.save() return redirect('person_list') return render(request, 'person_form.html',{'form': form, 'autor': autor}) html {% block main %} <h3>Novo Orientado</h3> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.non_field_errors }} {{ form.source.errors }} {{ form.source }} {{ form|bootstrap }} <button type="submit" class="btn btn-primary">Salvar</button> </form> {% endblock %} -
Refactoring a Django Boolean query
I'm working on a generic ListView for a Family object. Each Family has a one-to-one field with an employee_user and a partner_user, which in turn have one-to-one fields with a Profile model (with a related name user_profile) which has a Boolean using_app field. A family is considered to be using the app if either the employee or the partner is using the app. Currently, I have the following get_queryset() method def get_queryset(self): queryset = super().get_queryset() if app: using_app = app == 't' if using_app: queryset = queryset.filter( Q(employee_user__user_profile__using_app=using_app) | Q(partner_user__user_profile__using_app=using_app)) else: queryset = queryset.filter( Q(employee_user__user_profile__using_app=using_app) & Q(partner_user__user_profile__using_app=using_app)) return queryset This makes this ListView pass the following tests (using factory_boy test fixtures): from django.test import TestCase from django.urls import reverse from dashboard.tests.utils import AccountMixin from lucy_web.test_factories import FamilyFactory, UserFactory class FamilyUsingAppTest(AccountMixin, TestCase): def setUp(self): self.login_user(UserFactory(is_superuser=True)) def test_filter_families_using_app(self): family = FamilyFactory( employee_user=UserFactory(user_profile__using_app=True), partner_user=UserFactory(user_profile__using_app=False)) self.assertIs(family.using_app, True) response = self.client.get( path=reverse('dashboard:families'), data={'app': 't'}) self.assertEqual(response.context['object_list'].count(), 1) self.assertTrue(response.context['object_list'].first() == family) def test_filter_families_not_using_app(self): family = FamilyFactory( employee_user=UserFactory(user_profile__using_app=True), partner_user=UserFactory(user_profile__using_app=False)) response = self.client.get( path=reverse('dashboard:families'), data={'app': 'f'}) self.assertEqual(response.context['object_list'].count(), 0) However, the get_queryset method contains some code repetition in the if... else clauses, and I'm looking to refactor it, for example by using Queryset.annotate(). From Django Boolean Queryset Filter Not Working, … -
Changes made on css static file doesnt appear on chrome web browser but appears on safari
I was using django to create a simple site and everything looked fine on both safari and chrome. The next day I opened it on chrome and everything was out of proportion (realized that I had to zoom in to 50% to get everything to look the way it was earlier). To fix it I started making changes to my css file but the changes I made will on appear on safari but not chrome. When i inspected the source on chrome the css file was not updated with changes i made. This is my html code {% load static from staticfiles %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"> <meta charset="utf-8" content="width = device-width, initial-scale = 1.0"> <title>Tera Hertz</title> </head> <body> <!-- Header --> <div id="pagetitle"> <img src="{% static 'ub.png' %}" alt="University At Buffalo logo" id="logo"> <h1 style="padding-top: 10px;">THz Channel Model</h1> </div> </body> </html> I removed everything from css file. On chrome how every all the styling remained including colors, height, width, positions, etc. -
Adding a boolean field on a production Django deployment
I have a production Django deployment (Django 1.11) with a PostgreSQL database. I'd like to add a boolean field with a default to one of my models: class MyModel(models.Model): new_field = models.BooleanField(default=False) In order to deploy, I need to either update the code on the servers or run migrations first, but because this is a production deployment, requests can (and will) happen in between my updating the database and my updating the server. If I update the server first, I will get an OperationalError no such column, so I clearly need to update the database first. However, when I update the database first, I get the following error from requests made on the server before it is updated with the new code: django.db.utils.IntegrityError: NOT NULL constraint failed: myapp_mymodel.new_field On the surface, this makes no sense because the field has a default. Digging into this further, it appears that defaults are provided by Django logic. If the server doesn't have the updated code, it will not pass the column to SQL for the update, which SQL interprets as NULL. Given this, how do I safely deploy this new boolean field to my application? -
Reactjs app making requests to Django which exists on different domain
I'm trying to make a request from my reactjs app existing on "localhost:3000" to my django living in "localhost:8000" I was expecting some authentication token in header to passed along with the request, but it's not the case. The request seems to be stripped and the token is nowhere to be found. Unless I pass the token in the url as a parameter (which exposes the token that can be decoded. I don't like it), I can't seem to be able to get the token in any way. so my questions: is this CORS issue? My understanding is that CORS usually deals with javascripts only, and Django already has the middleware to deal with this. I'm currently using a GET as method. Does using a POST help in this case? How would the reactjs script be written? Currently it's just a href attached to a NavItem and ultimately: How do I pass the token from reactjs to django? -
How to get data from django Model
Ok so I have this Model in django: class Training(models.Model): url = models.URLField(max_length=100) title = models.CharField(max_length=100) topic = models.CharField(max_length=100) grouping = models.CharField(max_length=100) month = models.CharField(max_length=100) overallOrder = models.CharField(max_length=100) emailSent = models.CharField(max_length=100) but how do I get the data from those fields? If I drop to the sqlite shell this is what I get: In [1]: from myapp.models import Training In [2]: queryset = Training.objects.all() In [3]: print (queryset) <QuerySet [<Training: Training object>]> But I want to be able to look at all the data in that database. I'm not sure how to do that. Any help is appreciated. Thank you. -
Displaying UoM for a group of fields : Django 2.0.6 / Python 3.6
I am looking to display various quantity fields with (different types of) units of measures. Example: A transportation unit is capable of carrying a laden weight of, say 7500 Kg. The volumetric capacity of the the transportation unit is 12000 liters. How do I produce a record to display like: TPT Unit Number TPT Unit Descrip Laden Wt Vol. Capacity XYZ1234 SOMETHING 7500 KG 12000 L Please note the missing "header" for the UoM fields. Right now I am displaying the above row (of record) using the field name in "list_display" but in the process I end up displaying the unit of measure field names as well. The display gets uglier if I display the record in vertical format like: TPT Unit Number XYZ1234 TPT Unit Descrip SOMETHING Laden Wt 7500 Wt_UoM. KG Vol. Capacity 12000 Vol_UoM. L Is there a way to eliminate the UoM field names from the row header? And also put the UoM alongside their respective values. Thanks. -
local settings can not find the app
Everytime I try to run the app, or migrate my database, it throws this error. My IDE, although, helps me run the app because the configurations seem to be correct but bash fails to run any of the Django commands. This is the error that I get: File "/Users/angy/settings/projname_conf/settings.py", line 1, in <module> from pyup.generic_settings import * ModuleNotFoundError: No module named 'pyup' -
Django: delete an item from a table but keep a record of deleted item
I'm making an inventory app for tools in my workshop. I created a view that manages the tools in toolboxes and to whom the boxes are assigned to, I am able to create tools in the toolbox using the CreateView class, but i don't know how to remove the tool from the box. (Lets say that one of the tools broke and we would have to replace it, I want to keep a record of that transaction, what cart it was in and the reason for discarding the item. Also I want to check if it was a non-disposable item or if was a consumable item(if the item broke by bad use or if the item weared down to an unusable state)). How can I go about this issue? models for creating the tool cart(carrito) =========================================================================== # # MODELO PARA CREAR CARRITOS # =========================================================================== # class Carritos(models.Model): no_carrito = models.CharField(max_length=3, unique=True) empleado = models.OneToOneField(Empleados, on_delete=models.CASCADE) # empleado = models.ManyToManyField(Empleados, through='Transaccion') items = models.ManyToManyField(Item, through='Transaccion', related_name='carritos') f_creacion = models.DateTimeField(auto_now_add=True) f_actualizacion = models.DateTimeField(auto_now=True) activo = models.BooleanField(default=True) def get_absolute_url(self): return reverse('inventario:carrito')#, kwargs={'pk': self.pk}) class Meta: verbose_name_plural = "Carritos" def __str__(self): return self.no_carrito class Transaccion(models.Model): carrito = models.ForeignKey(Carritos, on_delete=models.CASCADE, related_name='items_carrito') Herramienta = models.ForeignKey(Item, on_delete=models.CASCADE, … -
Add the users in Django Admin site into html table on webpage
I am trying to capture the user data that is in the Django-Admin site and turn it into a html table. The problem that I am having is that my table is only displaying one user, which is the user that is logged in. I want to display the name of all of the users that are in the Django Admin database (Similar to a basketball roster). How can I accomplish that? Thank you. Here is my views.py code: from django.views.generic import TemplateView from django.shortcuts import render, redirect from django.contrib.auth.models import User from home.forms import HomeForm from django.contrib.auth.decorators import login_required from home.models import Post class HomeView(TemplateView): template_name = 'home/home.html' def get(self, request): form = HomeForm() posts = Post.objects.all().order_by('-created') users = User.objects.exclude(id=request.user.id).exclude(is_superuser=True) args = {'form': form, 'posts': posts, 'users': users} return render(request, self.template_name, args) Here is the html template code: <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">Player Name</th> <th scope="col">Position</th> <th scope="col">Grade</th> </tr> </thead> <tbody> <tr> <th scope="row">{{ user.userprofile.jersey_number }}</th> <td>{{ user.get_full_name }}</td> <td>{{ user.userprofile.position }}</td> <td>{{ user.userprofile.grade }}</td> </tr> </tbody> -
django : how to make one item True and other all Flase
So i have list of number of years, at a time only one year can be True and other all False. I can change one Year to True but not other years to False, and I have multilple years True. But I want only one year to be True and other all False. models.py file from django.db import models year = models.CharField(max_lenght=10) is_active = models.BooleanField(defaut=False) def __str__(self): return self.year I want to do this through views, can anyone please help me. I am new to dajngo. Thank you -
dataTables not live updating on my local environment, but works fine on the company dev server
We're using the jQuery plugin "dataTables" to create live datagrids. It's pretty neat but I'm having a weird problem. In the footer of each column there is a filter, and when you select a value it's supposed to filter all the entries to only show the ones that match that value. On the company dev website my page works perfectly. However, when I load it up on my local environment the page doesn't live update, and the filter only applies if I hit the "show next/previous 10 entries" buttons. I'm pasting my jQuery code here but the problem is probably somewhere else, but I don't know where. As I said, this works fine on the website and only gives me problems on my local machine. Let me know if there's something else I should paste here. Thanks in advance! (function(){ function findColWidths(table){ var colWidths = {}; function analyzeWidths(index, value){ var rowCols = $(this).find('td'); for(var i=0;i<rowCols.length;i++){ var cell = $(rowCols[i]); if(colWidths[i] == null || colWidths[i] == undefined){ colWidths[i] = cell.html().length; }else{ colWidths[i] = Math.max(colWidths[i], cell.html().length); } } } $(table).find('tbody').find('tr').each(analyzeWidths); $(table).find('thead').find('tr').each(analyzeWidths); return colWidths; } $.fn.dataTable.moment( 'MMM D YYYY' ); var companyName = "{{company_name}}"; var dataTable = $('.dataTable').DataTable({ buttons: [ 'copy', 'csv', { … -
Passing parameters of self in a function inside __init__
The problem is when ever I am calling a function from init and sending parameters of self inside it. And when that particular function is called it can't receive the parameters from the self, but when I send it as str " 123456789" it can receive it. def __init__(self, *args, **kwargs): super(User, self).__init__(*args, **kwargs) self.initial_is_active = self.is_active sum(self.token) sum_modify("123456789") def sum(self, token): print("token",token) -> this would not print token def sum_modify(self, token): print("token",token) -> this would print token -
Django ajax warning on same page after DoesNotExist exception on form POST
I have a django form attached to a view. In the form a user types in a query which is passed to a Model.objects.get( query ) like so: def post(self, request): try: Model.objects.get(query) except Model.DoesNotExist: # something here Upon exception i'd like to send an ajax request to my template that stops it from refreshing, and displays a warning to the user that there's nothing in the database matching that get request. What would I put in the view and the template? -
Django mysql stored procedure error
My stored procedure code DELIMITER $$ USE `moretkt_db`$$ DROP PROCEDURE IF EXISTS `check_new_schedule`$$ CREATE DEFINER=`root`@`localhost` PROCEDURE `check_new_schedule`( IN busid INT, IN schedule_start_time DATETIME, IN schedule_end_time DATETIME, OUT s_status VARCHAR(10) ) BEGIN DECLARE COUNT INT; DECLARE last_end_time DATETIME; SELECT arrive_time INTO last_end_time FROM moretkt_db.administration_schedule WHERE bus_id = 1 ORDER BY id DESC LIMIT 1; IF (schedule_start_time < last_end_time) AND (DATE(schedule_start_time) = DATE(last_end_time)) THEN SET s_status = 'no1'; ELSEIF (schedule_start_time > last_end_time) OR (last_end_time IS NULL) THEN IF schedule_start_time > schedule_end_time OR schedule_start_time = schedule_end_time THEN SET s_status = 'no2'; ELSEIF schedule_start_time < schedule_end_time THEN SELECT COUNT(*) INTO COUNT FROM moretkt_db.administration_schedule WHERE bus_id = busid AND schedule_start_time BETWEEN (SELECT depart_time FROM moretkt_db.administration_schedule WHERE bus_id = busid AND DATE(depart_time) = DATE(schedule_start_time) ORDER BY TIME(depart_time) ASC LIMIT 1) AND (SELECT arrive_time FROM moretkt_db.administration_schedule WHERE bus_id = busid AND DATE(arrive_time) = DATE(schedule_start_time) ORDER BY TIME(arrive_time) DESC LIMIT 1); END IF; IF COUNT = 0 THEN SET s_status = 'yes'; ELSEIF COUNT >0 THEN SET s_status = 'no3'; END IF; END IF; END$$ DELIMITER ; I called stored proc in Django as following: cur = connection.cursor() cur.callproc('check_new_schedule', (request.POST.get('bus'), bus_depart_time, R.approx, "0", )) results = cur.fetchone() return HttpResponse(results) cur.close() I want to output "Yes" or "No" but … -
Django upload excel file, process with pandas, download as csv
I'm running Django on a localhost (Later to run on a LAN) where the idea is I can go onto the webpage, click a button where you're prompted to select an excel file from your computer. Pandas will do work on said excel file and Django/Pandas will make excel file of this Pandas data frame as a download prompt. I've got Django running and using the code below from the module 'Django-Excel' does the basics of what I want. Excel file in ---> excel file out, no saving the file to a database or anything just keeping it in the memory. However, I cannot find a way to shoehorn Pandas into it. The main problem I have is I'm unsure how to return an excel file using Pandas. I've been using '.to_excel()' in my offline python code, however, haven't found a way to use it in a localhost running Django. I'm sure I'm missing something really simple but I just can't get it. Maybe if someone could show a simple example of say, uploading an excel, pandas will multiply a column of numbers in the excel by 2, new excel is outputted to read/save. from django.shortcuts import render, redirect from …