Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
MultipleHiddenInput widget doesn't get rendered
My MultipleHiddenInput field which I am using to store some choices for another field based on a selector doesn't seem to work. Please consider my code: class LogSearch(forms.Form): platform = forms.ChoiceField(required=True, choices=platforms, initial='v', help_text='The platform to search on') log_type = forms.MultipleChoiceField(required=True, choices=()) keyword = forms.CharField(required=True) other_log_types = forms.MultipleChoiceField(required=False, widget=forms.MultipleHiddenInput, choices=[(1, '3'), (2, 'b')]) As shown in this form code, I would expect the other_log_types to be rendered as hidden. But it doesn't appear at all in my HTML. I am rendering it properly on the template as all other components appear properly. I'm not sure if I am not using the widget right or not. Thanks -
Use the FilteredSelectMultiple widget without using Django's admin
How can I use the FilteredSelectMultiple widget without having the /admin URLs defined and no superusers? I would like to use it in my own form, but I'm not sure how to include the JS without using the built in superusers. The docs show it's possible but as I said I'm not sure about including the JS. -
my django project unit test volume, It's getting bigger
I'm looking for some solution or cases for big testing file what my django-team have... which mean, there is too much Django unit-test files in our django-project.. django_app/tests/tests_xxx.py <--- almost 20 ~ 30 files on tests dir How do I manage all of django-test, more productive and effective methods -
Normal characters&escape seaquence are gotten in my program
Normal characters&escape seaquence are gotten in my program.I wanna get only escape seaquence,so I really cannot understand why.I wrote codes, import re def get_id(request): id= "100¥a" pattern = re.compile(r'[\\u000-\\u037]', re.UNICODE | re.IGNORECASE) if pattern.findall(id): return HttpResponse('<h1>Escape sequence</h1>') else: return HttpResponse('<h1>OK</h1>') In this case,program go into if statement and it is ok.But when I rewrote id into id= "100",program go into if statement too.I wanna only catch escape seaquence in if statement,my ideal system goes into else statement if id does not have escape sequence.What is wrong in my code?How should I fix this? -
rest-framework "get() missing 1 required positional argument"
I want transmit a GET parameters 'pk' to django rest-framework. ![broser][https://i.stack.imgur.com/5sdPR.png] but in my view.py,I was setting my GET method to receive ‘pk’ parameters. ![views.py][https://i.stack.imgur.com/NCpcI.png] It's urls.py code: ![urls.py][https://i.stack.imgur.com/5RdvC.png] and There is another one question,if I models object use 'objects' method in the pycharm,were throw an exception,such as: ![]https://i.stack.imgur.com/9q0OV.png] but my friend was not happen this exception.He use pycharm 2017.4(macOS) cateloydata = category.objects.all() my pycharm version:pycharm 2017.2 python version 3.6 django version 1.11.7 Thank everyone. and I'm sorry,I need at least 10 reputation to post images.So my question composing is very bad. 感谢! -
Filter Django Form Field Based on ForienKey Relation of previous field
Hello guys please how can i filter the items on a form field based of the foreignkey relation with the previous field . somethings like a locations selector in which if the user selects the next field should be filtered based in it. thanks -
Server side pagination for web services api in django
My project structure is as- webservice api : Django database : Mongodb frontend : angular2 I am trying to implement pagination what I have tried- def get_my_large_records_paginated(request): json_data = json.loads(request.body) page_no = json_data["pageNo"] display_records_count = json_data["displayRecords"] records = [very large list around 10000 dictionary objects] # This is large list contains dynamic data which is processed after querying complex query on mongodb paginated_data = self.paginate(records,page_no,display_records_count) return JsonResponse(paginated_data) def paginate(self,records,page_no,display_record): paginatorObj=Paginator(record_obj,display_record) num_pages = paginatorObj.num_pages try: if page_no <= num_pages and page_no >0 : page = paginatorObj.page(page_no) return page.object_list else: print ("Invalid page number or display record count") except Exception as e: error_logger.error(e) return None I am able to paginate records and response. But every time I request new page it process all 10000 records, query mongodb. So is there any way to avoid processing query operation on every consecutive request and return data directly which is processed for first request. If there is alternative solution also for above approach I would love to try. Thanks in advance. -
Dynamically generate fields+1 for model form
I have a model that is basically just a service report. I want this model to contain multiple punches (clock in\clock out). How do I go about doing that? When I pull up the form, I want to be able to add punches obviously. class ServiceReportModel(models.Model): report_number = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) site = models.ForeignKey(customers_models.SiteModel, on_delete=models.PROTECT) request_number = models.ForeignKey(ServiceRequestModel, on_delete=models.PROTECT, null=True, blank=True, related_name='s_report_number' ) reported_by = models.ForeignKey(main_models.MyUser, related_name='reports') reported_date = models.DateTimeField(auto_now_add=True) updated_by = models.ForeignKey(main_models.MyUser, blank=True, null=True, related_name='+') updated_date = models.DateTimeField(auto_now=True) equipment = models.ForeignKey(customers_models.EquipmentModel, on_delete=models.PROTECT) report_reason = models.CharField(max_length=255, null=True) time_in = models.DateTimeField(blank=True, null=True) time_out = models.DateTimeField(blank=True, null=True) actions_taken = models.TextField(null=False, blank=False) recommendations = models.TextField(null=True, blank=True) def get_absolute_url(self): return reverse('service-report', kwargs={'pk': self.pk}) def __str__(self): return '%s - %s, %s' % (self.site.company, self.reported_date.strftime('%d %B %Y'), self.equipment.name) class Meta: ordering = ['reported_date'] verbose_name = 'Service Report' verbose_name_plural = 'Service Reports' -
Escape sequence cannot be gotten in if-else statement
Escape sequence cannot be gotten in if-else statement.I wrote codes, import re def get_id(request): id= "100¥a" if re.search(r"[\0-\037]", id): return HttpResponse('<h1>Escape sequence</h1>') else: return HttpResponse('<h1>OK</h1>') In this case,I think program go into if re.search(r"[\0-\037]", id): ,but always it go into else statement.I really cannot understand why.Is the way of getting escape sequence in if statement wrong?How should I fix this? -
Form invalidad in Django - ManyToMany relationship
I'm trying to insert data in my ManyToMany relationship but i don't get it, my form always is invalidad. I get this error when i try to save the form "The view apps.alumno.views.SubirActividad didn't return an HttpResponse object. It returned None instead." Models: class Alumno(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nocontrol = models.CharField(max_length=8) grupo = models.ForeignKey(Grupo, on_delete=models.CASCADE) def __str__(self): return '{}'.format(self.nocontrol) class Actividad(models.Model): nombre = models.CharField(max_length=50) descripcion = models.CharField(max_length=100) asignatura = models.ForeignKey(Asignatura, on_delete=models.CASCADE) alumno = models.ManyToManyField(Alumno, through='ActividadAlumno', through_fields=('actividad', 'alumno'),) def __str__(self): return '{}'.format(self.nombre) class ActividadAlumno(models.Model): actividad = models.ForeignKey(Actividad, on_delete=models.CASCADE) alumno = models.ForeignKey(Alumno, on_delete=models.CASCADE) fecha = models.DateField(auto_now_add=False, auto_now=True) documento = models.FileField(upload_to='asignatura/tarea/') calificacion = models.IntegerField(null=True) Form: class ActividadAlumnoForm(forms.ModelForm): class Meta: model = ActividadAlumno fields = [ 'actividad', 'alumno', 'documento', 'calificacion', ] labels = { 'actividad': 'Fecha de entrega', 'alumno': 'Entregado', 'documento': 'Estado', 'calificacion': 'Calificacion', } widgets = { 'actividad': forms.Select(), 'alumno': forms.Select(), 'documento': forms.ClearableFileInput(), 'calificacion': forms.NumberInput(), } View: def SubirActividad(request, id_actividad): actividad = Actividad.objects.get(id=id_actividad) if request.method=='POST': form = ActividadAlumnoForm(request.POST) if form.is_valid(): form.save() return redirect('alumno:asignatura_detalle', clave=form.instance.asignatura.clave) else: alumno = Alumno.objects.get(user=request.user) form = ActividadAlumnoForm(initial={'actividad': actividad, 'alumno':alumno}) return render(request, 'alumno/actividad_subir.html', {'form':form}) -
Django Unique constraint failed for user field in model
I've been trying to figure out how to save the user's id with in a model through a form, I keep getting UNIQUE constraint failed: vapp_numobject.user_id. Here's my model: class NumObject(models.Model): title= models.CharField(max_length=50) number= models.IntegerField() ident= models.IntegerField(blank=True, null=True) user= models.ForeignKey(User, on_delete= models.CASCADE) def __str__(self): return self.title def save(self, *args, **kwargs): super(NumObject,self).save(*args,**kwargs) def get_absolute_url(self): return reverse('posts:detail', kwargs={'id': self.id}) my forms.py: class NumForm(forms.ModelForm): class Meta: model = NumObject fields = [ 'title', 'number', ] and my view that saves the form: @login_required def post_createnum(request): form= NumForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return HttpResponseRedirect('/') context= { 'form': form, } return render(request, 'num_form.html',context) I'd like to be a able to sort a list of the NumObjects by user id, and I'm not sure if there's a better method in Django. Any help is appreciated! -
Proper template setup Django?
I'm a new user of Django. I've seen a couple ways people are setting up their templates. I would like to get some thoughts on the proper way in case one leads to problems down the road. The first layout that I've seen is to use multiple template folders. A main one in the root folder and also one under each app directory that you make. The other way I've seen is to use only one templates folder and just name directories under it which match the name of the apps. Hopefully that makes sense. Any thoughts on the right way to do it would be appreciated. -
Understanding Django Model Design and Forms
So I am trying to create a small, but powerful project that manages customers, employee reports, and customer requests. The system stores customer information like address, rates, distance, etc. I have a feeling I am misunderstanding, or over complicating my model design. As an example here is my customer models.py: from django.db import models from django.core.validators import RegexValidator from django.utils.translation import ugettext_lazy as _ ''' The address model is just a generic address container ''' class AddressModel(models.Model): street1 = models.CharField(max_length=255) street2 = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=50) state = models.CharField(max_length=2) zipcode = models.IntegerField() country = models.CharField(max_length=50) ''' The phone model is just a generic address container ''' class PhoneModel(models.Model): 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(_('Phone Number'), validators=[phone_regex], max_length=15, blank=True ) # validators should be a list def __str__(self): return '%s' % (self.phone_number) class Meta: verbose_name = "Phone Number" # verbose_name_plural = "Phone Numbers" class CompanyModel(models.Model): name = models.CharField(_('Company Name'), max_length=255) since = models.DateField(auto_now_add=True) rate = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return '%s' % (self.name) class Meta: ordering = ['name'] verbose_name = 'Company' verbose_name_plural = 'Companies' ''' The site model consists of sites of a company … -
Allow CSRF token header in Django CORS sent from axios call
How can I solve this CORS problem for django? I'm doing a POST http call using axios and need to have a CSRF token to do so. In order to do that, I need to pass in a CSRF header axios.post('/test', data, { headers: { 'HTTP_X_CSRFTOKEN': 'X-CSRFToken', } }) .then((res) => { console.log(res) }) .catch((err) => { console.log(err) }) settings.py CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) CSRF_COOKIE_NAME = "XSRF-TOKEN" CSRF_HEADER_NAME = ( 'HTTP_X_CSRFTOKEN' ) Error: Request header field xsrfHeaderName is not allowed by Access-Control-Allow-Headers in preflight response. -
Django parameter URLs, how to?
I need to write a search based on the URL like this: Example 1: /ad/state/new-york/borough/queens/tag/expensive/tag/beer/ Example 2: /ad/state/new-york/ Example 3: /ad/state/new-york/tag/beer/ I don't know how to handle this in the "urlpatterns" on the urls.py and how should be my view on views.py Can someone give me some help on this? -
Django: override save method on ModelForm that inherits values from another ModelForm
For convention at my company any validation must be done in the form and not in the view of any Django APP. I've this code that applies to my form, as a regular form. But I've "upgradete" it to be a 'ModelForm' and this code, works but doesn't save the "document" attribute on the 'Nana'. What I'm doing wrong? forms.py class NanaForm(forms.ModelForm): class Meta: model = Nana fields = ['nombre', 'apellido_paterno', 'apellido_materno', 'fecha_de_nacimiento', 'direccion', 'telefono_o_celular', 'genero', 'foto', 'latitud', 'longitud'] widgets = { 'fecha_de_nacimiento': DateInput(), 'latitud': forms.HiddenInput(), 'longitud': forms.HiddenInput() } def clean(self): form_data = self.cleaned_data try: tipo_documento = TipoDocumento.objects.get(form_data['tipo_documento']) if not tipo_documento.validar_documento(form_data['documento']): self._errors["documento"] = ["El documento no cumple el formato."] del form_data['documento'] except ObjectDoesNotExist: self._errors["tipo_documento"] = ["No existe el tipo de documento seleccionado."] del form_data['tipo_documento'] return form_data @transaction.atomic() def save(self): valid_data = self.cleaned_data documento_codigo = valid_data.pop('documento') documento_tipo_id = valid_data.pop('tipo_documento') documento = Documento(codigo=documento_codigo, tipo_documento_id=documento_tipo_id) documento.save() nana = Nana(documento=documento, **valid_data) nana.save() return nana class DocumentoForm(forms.ModelForm): class Meta: model = Documento fields = ['tipo_documento', 'codigo'] models.py class TipoDocumento(models.Model): nombre_corto = models.CharField(blank=False, null=False, max_length=25) nombre_largo = models.CharField(blank=False, null=False, max_length=100) tipo_patron = models.IntegerField(blank=False, null=False, choices=TIPO_PATRON) tipo_contribuyente = models.IntegerField(blank=False, null=False, choices=TIPO_CONTRIBUYENTE) tipo_longitud = models.IntegerField(blank=False, null=False, choices=TIPO_LONGITUD) def __str__(self): return self.nombre_corto -
running pyodbc with Django on Heroku
Has anyone managed to install django-pyodbc-azure on Heroku? I am told by Heroku support that odbc is not supported but that it can be installed via 3rd party buildpacks. I have found a couple but can't get them to work: https://github.com/film42/heroku-buildpack-python-odbc and https://github.com/Yesware/heroku-snowflake-odbc-buildpack Someone out there must be using Django with an Azure db??? -
Django 1.11 - Inline Admin Model - Error: admin.E106
I want to access the Image model in the Art admin page as it's written in the docs but something goes wrong: /gallery/models.py: class Image: name = models.CharField(max_length=256) thumb = models.CharField(max_length=256) product = models.ForeignKey(Art, on_delete=models.CASCADE, related_name='images') /product/admin.py: class ArtImage(admin.TabularInline): model = Image extra = 3 class ArtAdmin(admin.ModelAdmin): inlines = [ArtImage] admin.site.register(Art, ArtAdmin) When I apply the makemigrations command I get SystemCheckError: System check identified some issues: ERRORS: : (admin.E106) The value of 'product.admin.ArtImage.model' must be a Model. What could it be? -
django.db.utils.ProgrammingError: relation "users_user" does not exist
I'm trying to migrate my apps, so this error it's happening "django.db.utils.ProgrammingError: relation "users_user" does not exist". I tried with many ways and this not running. I'm using multi-tenant configuration. Help me please. <pre> My manage.py migrate_schemas --list [standard:public] admin [standard:public] [ ] 0001_initial [standard:public] [ ] 0002_logentry_remove_auto_add [standard:public] [ ] 0003_auto_20171127_1309 [standard:public] auth [standard:public] [X] 0001_initial [standard:public] [X] 0002_alter_permission_name_max_length [standard:public] [X] 0003_alter_user_email_max_length [standard:public] [X] 0004_alter_user_username_opts [standard:public] [X] 0005_alter_user_last_login_null [standard:public] [X] 0006_require_contenttypes_0002 [standard:public] [X] 0007_alter_validators_add_error_messages [standard:public] contenttypes [standard:public] [X] 0001_initial [standard:public] [X] 0002_remove_content_type_name [standard:public] foundation [standard:public] (no migrations) [standard:public] sessions [standard:public] [ ] 0001_initial [standard:public] sites [standard:public] [X] 0001_initial [standard:public] [X] 0002_alter_domain_unique [standard:public] tenants [standard:public] (no migrations) [standard:public] users [standard:public] [X] 0001_initial Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 350, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 399, in execute output = self.handle(*args, **options) File "C:\Python27\lib\site- packages\tenant_schemas\management\commands\migrate_schemas.py", line 53, in handle executor.run_migrations(tenants=tenants) File "C:\Python27\lib\site- packages\tenant_schemas\migration_executors\base.py", line 57, in run_migrations if public_schema_name in tenants: TypeError: argument of type 'TenantQueryset' is not iterable </pre> -
Persisting chosen value(s) from a Radio Button in an Django Application
In an Django Application, how can I persist information chosen from two options; two Radio Buttons at the Form - but with the second one offering to the user the ability to type in text boxes two values, 'min' and 'max'? For example: Choose the Temperature: o A fixed-value at _____ or o Values from _____ to _____ How can I implement this? Thanks. -
Django: How can i add recipes to a shopping list model
In my app I have a Recipe model of which I want to add recipes to a shopping list model. However, I don't know how to add an object from one model to another. How do I go about this? (This is my first question so I'm still getting the hang of this, sorry.) -
Websocket timeout in Django Channels / Daphne
Short question version: what am I doing wrong in my Daphne config, or my Consumer code, or my client code? channels==1.1.8 daphne==1.3.0 Django==1.11.7 Details below: I am trying to keep a persistent Websocket connection open using Django Channels and the Daphne interface server. I am launching Daphne with mostly default arguments: daphne -b 0.0.0.0 -p 8000 my_app.asgi:channel_layer. I am seeing the connections closing after some idle time in the browser, shortly over 20 seconds. The CloseEvent sent with the disconnect has a code value of 1006 (Abnormal Closure), no reason set, and wasClean set to false. This should be the server closing the connection without sending an explicit close frame. The Daphne CLI has --ping-interval and --ping-timeout flags with default values of 20 and 30 seconds, respectively. This is documented as "The number of seconds a WebSocket must be idle before a keepalive ping is sent," for the former, and "The number of seconds before a WebSocket is closed if no response to a keepalive ping," for the latter. I read this as Daphne will wait until a WebSocket has been idle for 20 seconds to send a ping, and will close the Websocket if no response is received 30 … -
Using django settings as argument defauts
Is there a reason not to use django settings as default arguments in functions like so: from django.conf import settings def my_function(some_arg=settings.SOME_ARG_DEFAULT): ... the alternative is setting the argument if it is None as is suggested for mutable defaults (such as lists or dicts): from django.conf import settings def my_function(some_arg=None): if some_arg is None: some_arg = settings.SOME_ARG_DEFAULT ... Could there be some unintended side effects from the first option? -
Wagtail: Is there a way to get all pages a snippet is used on?
I am using Wagtail 1.7 and need to retrieve a list of all the pages a snippet is used on. I looked at get_usage, get_usage_url but that didn't seem to be quite what I needed. I am using the sites framework with wagtail and need show different search results based on which site you are on (using elasticsearch). The snippets are the only thing fouling that up at the moment. -
Validation with cleaned_data()
I'd like to ask you if you can briefly and in plain English explain to me how cleaned_data() function validates data ? Reason for asking is that I'm designing a web app powered by Django and initially I thought cleaned_data() is smart enough to block user's input that contains potentially harmful characters. Such as # ; < > and alike. Characters that can be used for SQL injection attacks. To my surprise, when I deliberately slipped few of those characters into form field, the input made it to database. I was quite shocked. So then ... what the cleaned_data() function is good for ? I read about this function in docs, however I couldn't find necessarily answer to this.