Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Floatformat error: rounding down instead of up
I am getting strange behaviour using Django floatformat template tag. My tg data point has a value of 58551.5000. The is rendered in my template with: {{ tg|floatformat:0|intcomma }} The result is 58,551 when I am expecting 58,552 Can anyone help me see where I am going wrong in my expectation? -
Templatetag returns None
My tag.py from django import template register = template.Library() @register.simple_tag() def validator(data2, b): nop = False for data1 in b: if data2.pk == data1.mix_id: nop = True else: correct=data2 if nop : pass else: print(correct) return correct My template.html {% for data2 in mix.qs %} {% validator data2 vuelos.qs as data3 %} {{data3}} The Output of {{data3}} None The output of the print in the tag.py file is a list, its exactly what I want to get saved on data3 but the code only exits None. Any sugestions? -
Grab user specific database saves and render to html table
I have this model that saves som data to my database, and this database should be rendered in a HTML template, but only the specific users data so others wont be shown. My model looks like this class Usertasks(models.Model): TaskID = models.CharField(max_length=40) user = models.CharField(max_length=40) TaskStatus = models.CharField(max_length=10, default="missing") OutputPath = models.CharField(max_length=100, default="missing") My HTML looks like this <div class="dashboard-1"> <div class="tasks-running"> <h1>Running tasks</h1> </div> <div class="tasks-list"> <table> <tr> <th>User</th> <th>Task ID</th> <th>Status</th> </tr> {% for item in query_results %} <tr> <td>{{ item.user }}</td> <td>{{ item.TaskID }}</td> <td>{{ item.TaskStatus }}</td> </tr> {% endfor %} </table> </div> </div> This shows every single row that is in the database. But how do I query it so it shows only the current logged in users data -
RelatedObjectDoesNotExist - Usuario has no student
I'm having a problem with RelatedObjectDoesNotExist, i can not list my students, considering that they were created the same ones, since when creating them they are present in the admin, when using my CreateView after the registration the same is shown in the admin. Traceback models.py class Usuario(AbstractBaseUser,PermissionsMixin): username = models.CharField(_('usuario'), max_length=15, unique=True, help_text=_('Requer 15 caracteres ou menos')) password = models.CharField(_('senha'), max_length=15, help_text=('Digite uma senha com 15 caracteres ou menos')) email = models.EmailField(_('email'), max_length=255, unique=True) is_superuser = models.BooleanField(_('Status de Superusuário'), default=False, help_text=_('Designado para Superusuários ')) is_staff = models.BooleanField(_('Status de staff'), default=False, help_text=_('Designado para usuarios da equipe')) is_active = models.BooleanField(_('active'), default=False, help_text=_('Designado para usuários ativos. \ Em vez de deletar, desative o mesmo.')) is_student = models.BooleanField (_('Aluno'), default=False, help_text=_('Designado para usuarios do tipo Aluno')) is_advisor = models.BooleanField(_('Orientador'), default=False, help_text=_('Designado para usuarios do tipo Orientador')) is_supervisor = models.BooleanField(_('Supervisor'), default=False, help_text=_('Designado para usuarios do tipo Supervisor')) date_joined = models.DateTimeField(_('data de ingresso'), default=timezone.now) is_trusty = models.BooleanField(_('Email confirmado'), default=False, help_text=_('Usuários com contas confirmadas.')) matricula = models.IntegerField() objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', 'matricula', 'is_staff', 'is_superuser'] class Meta: verbose_name = _('usuario') verbose_name_plural = _('usuarios') class Student(models.Model): user = models.OneToOneField(Usuario, on_delete=models.CASCADE, primary_key=True) class Advisor(models.Model): user = models.OneToOneField(Usuario, on_delete=models.CASCADE, primary_key=True) class Supervisor(models.Model): user = models.OneToOneField(Usuario, … -
Django ajax search responds with 404 status
I'm trying to make a simple search using ajax in my django application. I have the following model: class Ingredient(models.Model): name = models.CharField(max_length=200) And here's my javascript: function search_success(data){ $('#search_results').hmtl(data); } $(document).ready(function () { $("#id_ingredient").on('change', function () { update_unities(); }); $('#search_ing').on('keyup', function(){ $.ajax({ url: '/ajax/search/', data: { 'search_text': $('#search_ing').val(), }, dataType: 'html', success: search_success, }); }); }); In my urls.py, I added the following: path('ajax/search', views.search_ingredients, name='search_ingredients') And in my view, I defined the following function: def search_ingredients(request): if request.method == "POST": search_text = request.POST['search_text'] else: search_text = '' ingredients = Ingredient.objects.filter(title__contains=search_text) return render('search_ingredients.html', {'ingredients' : ingredients}) I'm getting a 404 error on my request, can someone help me out? -
ugettext_lazy not working in model choices when using format functions
I am trying to translate choices from my models.py from django.utils.translation import ugettext_lazy as _ GRID_LEVEL = [(None, 'null')] for r in range(-15, 15): text = _('Level %s') % str(r) GRID_LEVEL.append((str(r), text)) I have tried brackets and %(var)s syntax but still no luck. Any help would be appreciated -
<myObject> object is not iterable, Django REST Framework
I'm getting the following error when posting a new Product to my application Traceback (most recent call last): File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/viewsets.py", line 116, in view return self.dispatch(request, *args, **kwargs) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch response = self.handle_exception(exc) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception self.raise_uncaught_exception(exc) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch response = handler(request, *args, **kwargs) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/mixins.py", line 20, in create serializer.is_valid(raise_exception=True) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 236, in is_valid self._validated_data = self.run_validation(self.initial_data) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 434, in run_validation value = self.to_internal_value(data) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 488, in to_internal_value validated_value = field.run_validation(primitive_value) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 623, in run_validation value = self.to_internal_value(data) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 662, in to_internal_value validated = self.child.run_validation(item) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 436, in run_validation self.run_validators(value) File "/mnt/c/Users/connect/Desktop/PIM/env/lib/python3.6/site-packages/rest_framework/serializers.py", line 465, in run_validators to_validate.update(value) TypeError: 'Category' object is not iterable my serializer.py from rest_framework import serializers from products_and_categories.models import Product, Category from django.db import models class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', "name", 'products', 'categories') def to_representation(self, obj): if 'categories' not … -
Django DateField format impossible to validate and save to model
Old issue, I know. But I still could not find a working solution so I may have missed something obvious. Here is my form class AddPatientForm(forms.Form): last_name = forms.CharField(label='Nom', max_length=40) first_name = forms.CharField(label='Prénom', max_length=40) birthday = forms.DateField(label='date de naissance', widget=forms.DateInput(format='%d/%m/%Y',attrs={'placeholder': '31/03/1989'}), input_formats=['%d/%m/%Y',]) It follows this format convention and has to do so. Here is my model: class Patients(models.Model): first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) birth_date = models.DateField() inscription = models.DateTimeField(auto_now_add=True) And here is what I tried in setting.py to get rid of the issue DATE_FORMAT = "d-m-Y" DATE_INPUT_FORMATS = ['%d-%m-%Y'] USE_L10N = False Despite of this, I still got the same issue: form = AddPatientForm(request.POST) if form.is_valid(): form.clean() d = Patients(first_name= form["first_name"].value(), last_name= form["last_name"].value(), birth_date= form["birthday"].value()) d.save() >>>>["Le format de date de la valeur «\xa027/10/1987\xa0» n'est pas valide. Le format correct est AAAA-MM-JJ."] [disclaimer] I am not looking to override the model format convention and I know that the question of how dates "are really stored in db" is irrelevant (different from one DBMS to an other; django models are agnostic about it). But that's such a pin in the *** to struggle with such a simple task. Why can't I: use different format for forms and models? override somehow … -
Python - ImportError: No module named site
I recently upgraded to the latest version of Python (3.7.1) for Windows. When I enter the command "python" in the command line I get the following error: ImportError: No module named site. The py command does work however. py example.py will execute regular python files and PyCharm works perfectly. It has become an issue recently because when I go to launch the py manage.py runserver command for Django I get the error. Any help is appreciated. -
Django change Models relations depending on condition (if is staff or not)
I have 2 Moles, User and Account. The User can be staff or normal User. In general a User can have just one Account. This is what I have now: class User(AbstractBaseUser): account = models.OneToOneField(Account, null=True, on_delete=models.CASCADE) but in special cases an User can have multiple or no Account, only if the User is_staff. The logic is to have now a ForeignKey: class User(AbstractBaseUser): account = models.ForeignKey(Account, on_delete=models.CASCADE) But in this case, how do I stop in Django Admin or else, for a User to have multiple Foreign keys if is not staff, and force it for normal users to have a simulated OneToOne Relation. -
django 2.1.3 'django.db.backends.postgis' isn't an available database backend
I am trying to use geodjango for a project. Before I use geodjango I'm trying to do a learn it from the following tutorial: https://docs.djangoproject.com/en/2.1/ref/contrib/gis/tutorial/ I originally had django 1.11 installed and tried following that tutorial (stupid of me). However, after uninstalling django 1.11 and installing django 2.1.3 I am encountering some errors. After I make the model according to the tutorial, I use the command python3 manage.py makemigrations I end up getting the following error: Traceback (most recent call last): File "/home/aihoque2/.local/lib/python3.6/site- packages/django/db/utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django.db.backends.postgis' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/aihoque2/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/aihoque2/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/home/aihoque2/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) … -
Python - Get just the values without the fields queryset
I have this def in my views.py: def listar_animais(request, pk): vacas_no_lote = Animal.objects.filter(id_lote=pk, status=True, sexo=Sexo.F).values('id_animal', 'id_lote', 'id_raca') return JsonResponse({ 'data' : list( vacas_no_lote )}) And I'm getting this return in JSON: { "data": [ { "id_animal": 2, "id_brinco": 5456, "id_raca": 3 }, { "id_animal": 4, "id_brinco": 5456, "id_raca": 3 }, { "id_animal": 5, "id_brinco": 5456, "id_raca": 3 }, { "id_animal": 9, "id_brinco": 5456, "id_raca": 1 } ] } But I just want values, like this: { 'data': [ ['1', '5471', 'Angus'], ['3', '5547', 'Nelore'], ['8', '6874', 'Brahman'] ] } I need in this format because it's how will work with jQuery Datables as explained here: https://datatables.net/examples/data_sources/ajax -
how to save dates into database using django?
this is my code views.py def guardar(request): if request.method == "POST": idpersona = int(request.POST.get('id')) persona = personal.objects.get(id=idpersona) idep = int(request.POST.get('dependencia')) dep = dependencia.objects.get(id=idep) idcon = int(request.POST.get('concepto')) con = concepto.objects.get(id=idcon) fecha = request.POST.get('fecha') print(fecha) db_registro = lista_registro( personal_id=persona, fecha_registro=fecha, dependencia_id=dep, concepto_id=con, descripcion=request.POST.get('descripcion'), monto=request.POST.get('monto'), ) db_registro.save() return render(request, 'registro/exito.html') Models.py class lista_registro(models.Model): personal_id = models.ForeignKey(personal, on_delete=models.CASCADE) dependencia_id = models.ForeignKey(dependencia, on_delete=models.CASCADE) concepto_id = models.ForeignKey(concepto, on_delete=models.CASCADE) fecha_realizado = models.DateField() fecha_registro = models.DateField(auto_now_add=True) descripcion = models.CharField(max_length=1000) pago_id = models.ForeignKey(pago, on_delete=models.CASCADE, default=2) monto = models.CharField(max_length=100) def __str__(self): return "===> " + self.descripcion + " <===" well my problem is that I get a NOT NULL constraint error. I get that this is a date error but I don't know how to solve this -
Django - Admin - on form change
I have a general question to the django-admin. Is it possible to react on form changes? I have a select field in my django-admin detail site. Whenever i change the data from the select field, i want to change fields which are readonly. Anybody ever dealed with this issue? Thanks and Greetings -
Django annotate days between two dates
Trying to annotate the difference between two dates as number of days. Is there a function to extract day of year from a DateField? from django.db.models.functions import ExtractDay from django.utils import timezone date = timezone.localtime(timezone.now()).date() self.annotate( age=date.timetuple().tm_yday - ExtractDay(F('date')) ) -
Django: how to get data created by redirect view into another view
I have a view authorize in my app that redirects user to external authorization page: def authorize(request): url = 'https://www.strava.com/oauth/authorize?client_id=123&response_type=code&redirect_uri=http://127.0.0.1:8000/collect&approval_prompt=force' response = redirect(url) return response This authorization page then redirectes to another view collect (which collects user's data) with user's unique code included in the URL like so: http://127.0.0.1:8000/collect?state=&code=123456. The thing is that I need to somehow pass this code to the collect view first, so the data for the user can be collected. How can I do this? -
How to leave ManyToManyField attributes selected automatically as default? Django 1.10
In the system that is part of the development, there is a field of "authors" in the models that is a ManyToManyField, in which some users of the database are extracted in which the content of the site will be published. In short, the content will only be posted to the people I choose in the "authors" field. I would like all registered authors to be selected by default if I did not choose any, and then the content would be published for all of them. If I wanted a specific author, I could select. Detail that the field is still required even though I having inserted "blank = True". #models.py class Fullimage(models.Model): authors = models.ManyToManyField(settings.AUTH_USER_MODEL, verbose_name=u'Autores', related_name='fullimagelinks', blank=True) -
Unable to use django-kronos
I've been testing django-kronos with the simple example listed in the github readme: I did pip3 install django-kronos, myproject/myapp/cron.py: import kronos import random @kronos.register('* * * * *') def complain(): complaints = [ "I forgot to migrate our applications's cron jobs to our new server! Darn!", "I'm out of complaints! Damnit!" ] print random.choice(complaints) In my myproject/myproject/settings.py: INSTALLED_APPS = [ 'appointments.apps.AppointmentsConfig', 'clinic.apps.ClinicConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'bootstrap4', 'widget_tweaks', 'parsley', 'session_security', 'kronos' ] Ran: ./manage.py runserver I expected the dev server to throw up a message every minute. Nothing seems to be happening. I also created myproject/myapp/management/commands/task.py: from django.core.management.base import BaseCommand import kronos @kronos.register('* * * * *') class Command(BaseCommand): def handle(self, *args, **options): print('Hello, world! KRONOS is running!!') This is also not running. -
MultipleObjectsReturned- get() returned more than one mPurchase -- it returned 2
I am beginner to django. While trying to save mPurchase form I am getting MultipleObjectReturned error. I am trying to get data from form using POST request. Every time I submit the form I am getting an error. views.py def milkPurchase(request): title='Buy Milk' milk = mPurchase.objects.all() if request.method=='POST': form=mPurchaseForm(request.POST) if form.is_valid(): m = get_object_or_404(mPurchase) m.mPurchase_date=timezone.now() m.save() return redirect('milk-purchase') else: form=mPurchaseForm() context = { 'title': title, 'form': form, 'milk':milk } return render(request,'dairyapp/milk-purchase.html',context) forms.py class mPurchaseForm(forms.ModelForm): """ This form is for milk purchase """ seller=forms.CharField( label='Seller Name', max_length=50, ) mPurchase_product=forms.ChoiceField( choices=MILK_CHOICES, label='Milk Type', initial='', widget=forms.Select(), required=True ) mPurchase_qty=forms.FloatField( label='Qty' ) mPurchase_rate=forms.FloatField( label='Rate' ) class Meta: model=mPurchase fields=('seller','mPurchase_product','mPurchase_qty','mPurchase_rate',) here is my models.py class mPurchase(models.Model): mPurchase_id=models.AutoField(primary_key=True) seller=models.CharField(max_length=50) mPurchase_date=models.DateTimeField(default=timezone.now) mPurchase_product=models.CharField(max_length=10,choices=MILK_CHOICES) mPurchase_qty=models.FloatField() mPurchase_rate=models.FloatField() def __str__(self): return self.seller Can you please help me get through this? I have tried using mPurchase.objects.filter() Also, tried to catch exception using ObjectDoesNotExist and MultipleObjectReturned from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned -
extending abstract model in Django
I'm using Django 2.x and OAuth Toolkit. I'm writing an application where I need to add ForeignKey pointing to Application model of OAuth Toolkit plugin, which is defined Abstract. According to the documentation. I can extend the ** AbstractApplication** and then add in settings OAUTH2_PROVIDER_APPLICATION_MODEL='your_app_name.MyApplication' In my case, I have created my app and in models.py class CustomOAuthToolkitApplication(AbstractApplication): pass class OAuthToolkitTrackingLog(models.Model): application_model = settings.OAUTH2_PROVIDER_APPLICATION_MODEL application = models.ForeignKey(application_model, on_delete=models.CASCADE, blank=True, default=None, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, default=None) col_1 = models.CharField(max_length=255) created = models.DateTimeField(auto_now_add=True) and in settings.py INSTALLED_APPS = [ ... 'oauth2_provider', 'my_app', 'django_oauth_toolkit_tracking', ] OAUTH2_PROVIDER_APPLICATION_MODEL = 'my_app.CustomOAuthToolkitApplication' But when I run command to generate migration python manage.py makemigrations It gives error as The field oauth2_provider.Grant.application was declared with a lazy reference to 'my_app.customoauthtoolkitapplication', but app 'my_app' isn't installed. The field oauth2_provider.RefreshToken.application was declared with a lazy reference to 'my_app.customoauthtoolkitapplication', but app 'my_app' isn't installed. How can I fix this issue? -
Calling a view from template works for "a" tag, but not for form button
I have the following in my Django template: <form action="{% url 'explorer_api:authorize' %}" method="POST"> <input id="submit" type="button" value="Click" /> </form> <a href = "{% url 'explorer_api:authorize' %}">Authorize</a> Why does clicking on the form button will not do anything, but clicking on the a element will work fine and call the desired view? -
django app not being served on digitalocean droplet
I'm following this tutorial online https://simpleisbetterthancomplex.com/tutorial/2016/10/14/how-to-deploy-to-digital-ocean.html I get to an intermediary step where I want to check if I can access the app on the IP address. I run python manage.py runserver 0.0.0.0:8000 which returns the following: System check identified no issues (0 silenced). November 22, 2018 - 17:41:08 Django version 2.1.3, using settings 'mysite.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. So no errors. Then I navigate to :8000 and I get a timeout. "took to long to respond." Any idea what's going on here? -
How to update Django file from local machine to Ubuntu server(AWS EC2)?
I am developing an app in my local machine(windows OS) and I am using an AWS Ubuntu Server to deploy the code over there. But my problem is that when i am uploading python file through FileZilla Sftp its not make any change on the production server till I reboot production server using "sudo reboot" I am tired of doing this process again and again. I read about git version control can help me with this situation but I don't know how to do it. Please help me I am stuck from 3 days on this. -
Regex with list Comprehension
Sorry if this is not abiding by normal rules. I'm looking for confirmation on if what I'm doing seems like the best way and if not what would best. I'll try to explain as best as I can. I have a database with "definitions" each definition holds a list of "events", these events have a "highlighted" field which stores a regex string. Text files are uploaded to the server which have "sections". Each section is found with a regex string using finditer. I sort the results of the finditer into a list of dicts .groupdict with a list comp. The result of the groupdict is a "title" and "body" of the section. the loop through them. Each iteration in this loop uses splitlines on the section body. sect_re = re.compile(r'\*(?P<title>[^*]+)\*\s\*+\s+(?P<body>(?:.+\s+(?!\*+\n))+.+)', re.MULTILINE) re_results = re.finditer(sect_re, file_field) sections = [sect.groupdict() for sect in re_results] definitions = Definition.objects.all() for section in sections: title = section['title'] body_list = section['body'].splitlines() I then loop through all the definitions, get a the list of events in the definition then loop through those. for d in definitions: events = d.event_set.all() for e in events: in the events loop I compile the stored regex string from the event get … -
Add Dynamic field to DjangoAdmin Model
I have extended the delivered ModelAdmin class on Django, and I am trying to add an image preview property, when my model has this type of field. I was able to get as far as identifying when this happens, but I am failing when I try to add a dynamic property. Here is my class: class RTFAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): for x in obj._meta.get_fields(): if type(x) == models.ImageField: y = mark_safe('<img src="%s" width=400px></img>' % getattr(obj,x.name).url) RTFAdmin.picture = property(lambda self: y) self.readonly_fields = ('picture',) form = super(RTFAdmin, self).get_form(request, obj, **kwargs) return form But then, it fails with: 'SafeText' object is not callable If I define a property like this (code below), it works, but I dont want to define it manually for my models. class MyAdmin(admin.ModelAdmin): model=Ponto readonly_fields=('see_pic',) def see_pic(self, obj): return mark_safe('<img src="%s" width=400px></img>' % obj.pic.url) Any idea on where the problem is?