Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django or SQL: finding how many unique values of a given column for an grouped queryset
I have a dataset that looks like this member position 0 1 0 0 0 1 0 1 1 0 1 1 1 0 1 1 1 1 2 0 2 0 2 0 What I'm trying to achieve is to know which member only has one position. I've started with SQL: SELECT * FROM 'table' GROUP BY member, position and it gives me member position 0 0 0 1 1 0 1 1 2 0 From this result, how can I enucleate all the members that appear only once? I've tried DISTINCT, but it doesn't solve the problem. Also, I'd like to write this in Django ORM, with a single queryset, but group_by must be used with annotate or aggregate, but these only work with Sum, Count, Avg... Would that be the right approach? -
How to send <textarea> text to python view in django?
I have a textview in my html template that allows the user to enter text <textarea name="texteditor" id="texteditor" style="width:100%; height:100vh; resize:none; font-size:20px; font-family:sans-serif; border:none;" placeholder="Start Writing!"></textarea> I want to get that text on a button click into my view def write_view(request, *args, **kwargs): texteditor = request.POST.get('texteditor') print(texteditor) return render(request, "write.html", {'texteditor': texteditor}) Is there a solution for this? -
How an endpoint can be generated with Angular, to send POST requests
I am new to Angular and Django, I am working with angular and django on a project, with angular from the frontend and Django from the backend, the question is that I need to send POST request from a form (Angular) to a set of views through a point final. The point is that I do not understand this endpoints well, I mean I am consuming an api rest from angular with Django Rest Framework to show it in the frontend, but the concept endpoint is new to me. The reason for sending this request is to send a parameter to DJANGO to generate and download a custom excel according to the parameter sent to you in the request (for example, filter me and just fill in the EXCEL with this condition EquipoOrigen = P79COL01, where EquipoOrigen is a The column of the table. -
Can I annotate on a OneToMany relationship for performance?
I have the following simplified models. class Service(models.Model): ... class ServiceLogs(models.Model): service = models.ForeignKey(Service, related_name='logs', ...) who_did = models.ForeignKey(User, ...) role_played = models.CharField(choices=(('CA','CA'), ('CO', 'CO'), ('TO', 'TO')), ...) I know I can find out who played what role by calling <service obj>.logs.filter(role='CA'), but this approach hits the database 3 times per object given I have 3 roles. I was reading the documentation about aggretation and annotation, but all the examples use numeric values like Sum, Avg, etc. Can I make this query more efficient so I hit the database once per object? -
How to import list of emails separated by semicolon using django import export
Wondering the easiest way to import a csv file that imports info into two tables using django import export ex: csv file: id,field1,primary,CC,alert 1,my_value,email1@e.com;email2@e.com,email3@e.com,email4@e.com;email5@e.com Desired import foo model: id field1 1 my_value email model: id type email_address foo_id 1 primary email1@e.com 1 2 primary email2@e.com 1 3 CC email3@e.com 1 4 alert email4@e.com 1 5 alert email5@e.com 1 I already used ForeingKey and ManytoMany widgets to export and import other data into single tables. But I don't have ideas for this particular request. I'm thinking to override some methods like before_import. What should be the best approach? Any help will be appreciate :) Thanks!! -
Django runserver error - No Module found cx_Oracle
I am trying to create a web application on Django with oracle backend on my local machine. I have python 3.7, Django 2.2, oracle 12c on win 10. I have installed cx_Oracle. I can connect to oracle from python without an issue. But when I tried to run python manage.py runserver on virtual env then I got following error: File "C:\Users\local.virtualenvs\ab1-k_8ZC6ny\lib\site-packages\django\db\backends\oracle\base.py", line 48, in raise ImproperlyConfigured("Error loading cx_Oracle module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading cx_Oracle module: No module named 'cx_Oracle' I tried to put the cx_Oracle folder location on the PATH but still did not work. I appreciate any help you can provide. -
deploy a django app from localhost app to web application using windows
i have a little experience in django applications but only all applications it was localhost, Now i would like to know step by step how to deploy a django localhost app to web application using www and donain name to be accessible to everyone. i have no idea how this can be done and i haven't found any guide for this task . only where I know is : I need static ip(?) Buy domain name. 3.settings.py ALLOWED_HOSTS = ['static ip','www.name.com'] I use windows os (or I can use windows server for application) in my machine where I want to have this app. any idea ?thank you -
How to pass dictionary value to html template after i append the dictionary into array of dictionary?
item = [] data = { 'name':'john', 'age' : 5, } # i am not able to pass value to html template below: # first i use this , it does not work item.append(data.copy()) # second i use this one item.append(data) # still it does not work. # this is how i pass to html template {{ item.name }} #but it still does not work. i am trying use both method i am not able to pass value to html template below: There is no error. However, the only problem is the value does not display anything on html template. -
How to check if celery task is already running before running it again with beat?
I have a periodic task scheduled to run every 10 minutes. Sometimes this task completes in 2-3 minutes, sometimes it takes 20 minutes. Is there any way using celery beats to not open the task if the previous task hasn't completed yet? I don't see an option for it in the interval settings. -
CSRF Breaks Django Server
Django 2.1.4, Python 3.7, Django Test Server When I send an Ajax request that includes a CSRF token to an invalid URL and then follow it up with any request afterwards, body data from the first Ajax request is prepended to the next request, making the request invalid. [01/Aug/2019 16:57:27] "POST /profile/add_favorite HTTP/1.1" 404 4132 Forbidden (CSRF token missing or incorrect.): / [01/Aug/2019 16:57:50] "title=Video+TitleGET / HTTP/1.1" 403 2513 Notice that second line, the "title" parameter is from the previous request. It is possible to send requests such that middle "Forbidden (CSRF token missing or incorrect.):" is not present but the invalid processing is still done by the server. If that second request is coming from a new browser window, the “invalid CSRF” page is returned even though it is the first time opening the home page of my site from a fresh window. The following requests are then processed correctly assuming they’re valid. The problem occurs any time a request with an csrf token header is sent to an invalid URL. So, if I don't include the CSRF token in a header my server works fine. Not sure how to solve this other than removing CSRF altogether which is … -
can't use nextjs as frontend and django and backend
So I was starting a project that I'll probably use Next and Django in. and I know how to integrate client-side react with Django but it turned out there's no actual way to run nextjs with django because of next use express. so I decided to make a two different apps, django api, and next frontend but i cant decide whether i can put both on the same VPS and run them with Nginx or should I deploy them separately. what's more efficient? -
Updating data in Database from Django form
I'm trying to add a form to alter some data in my database. Basically, when the user submits the button, the new value should update the old value. This is what the template looks like: {% for row in mydb %} <form method="post" novalidate> {% csrf_token %} {% include 'main/includes/bs4_form.html' with form=form3 %} {{row.firstfield}} {{row.secondfield}} <button name="button3" type="submit" class="btn btn-danger style="background-color: red;">CANCEL</button></td> </form> {% endfor %} The for statements is to display each row of the data in my table in a single line. Near each line, there is a submit button. When this button is clicked, the field secondfield is updated with the value New Value, as you can see in my form. Thi is the part of the view involved: def myview(request, tvticker): row = mydb.objects if request.method == 'POST': ... if 'button3' in request.POST: form3 = form = UpdateForm(request.POST) if form3.is_valid(): profile = form.save(commit=False) profile.save() messages.success(request, f"Success") ... render(request, "main/mytemplate.html", context={'row': row,}) And here is the form: class UpdateForm(forms.ModelForm): SomeField = forms.CharField() class Meta: model = MyModel fields = ("SomeField",) def save(self, commit=True): send = super(UpdateForm, self).save(commit=False) send.secondfield = 'New Value' if commit: send.save() return send My actual code it's not working, is seems to send a … -
Django: How to convert url to path-urlpatterns in urls.py
So I'm having a small problem cleaning up a bit of code for url paths in an old django project. Previously I was importing a Newsletter app to the master application using the old url pattern like so... urls.py url(r'^newsletter/', include('newsletters.urls', app_name="newsletter", namespace="newsletter")) Now I'd like to bring it into an array of urlpatterns. All other patterns are working as intended aside from this one. urls.py ... from django.urls import path, include path('admin/', admin.site.urls), path('articles/', include('articles.urls')), path('', views.main, name='main'), path('register/', sub_views.register, name="register"), path('summernote/', include('django_summernote.urls')), ... I think it has something to do with the views.py file, and how I'm supposed to bring it in, so I'll include it here. from django.shortcuts import render from .models import Newsletter from .forms import NewsletterUserSignUpForm # Create your views here. def newsletter_signup(request): form = NewsletterUserSignUpForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) if Newsletter.object.filter(email=instance.email).exists(): print("Sorry. This email already exists") else: instance.save() context = { "form": form, } template = "newsletters/sign_up.html" return render(request, template, context) def newsletter_unsubscribe(request): form = NewsletterSignUpForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) if Newsletter.objects.filter(email=instance.email).exists(): Newsletter.objects.filter(email=instance.email).delete() else: print("We did not find your email address") context = { "form": form, } template = "newsletters/sign_up.html" return render(request, template, context) It's been quite some … -
full_clean() missing while Creating a related object in Django
I have two models my django app, on model is a foreign key in the other. My two models are : User and Attribute. each user has lot of attributes I am using generic views to create,update and delete my models. for my first model (User) everything works fine. But when i want to to create rows for my second models i get this error :full_clean() missing 1 required positional argument: 'self' This is my view : class AttributeCreate(CreateView): form_class = AttributeForm template_name = 'myapp/attribute_form.html' def get_form_kwargs(self): kwargs = super(AttributeCreate, self).get_form_kwargs() if kwargs['instance'] is None: kwargs['instance'] = Attribute kwargs['instance'].userid = self.kwargs['pk'] return kwargs And this is my form.py class AttributeForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AttributeForm, self).__init__(*args, **kwargs) # if userid: for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'form-control' class Meta: model = Attribute exclude = ['userid'] I am using Django 2.1, by the way, I've developed this use case in Django 1.9 and it works. -
Django Error 500 related to staticfiles when DEBUG = False
Here is my settings.py: import os import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'secret_key' DEBUG = False ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'corsheaders', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', 'rest_framework', 'django_celery_beat' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', # CORS support [keep load position] 'django.middleware.common.CommonMiddleware', #'django.middleware.cache.UpdateCacheMiddleware', #'django.middleware.common.CommonMiddleware', #'django.middleware.cache.FetchFromCacheMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_WHITELIST = [ "http://localhost:8080", "http://127.0.0.1:8080", "http://localhost:80" ] CSRF_TRUSTED_ORIGINS = [ 'http://localhost:8080', ] ROOT_URLCONF = 'django_backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'django_backend.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'name', 'USER': 'user', 'PASSWORD': "pw", 'HOST': 'localhost', 'PORT': '5432' } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) CELERY_BROKER_URL = 'redis://url:port' CELERY_RESULT_BACKEND = 'redis://url:port' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'console':{ 'level': 'DEBUG', … -
Is there a django package that sends desktop notifications with sound
I am working on a django application that consumes data from other systems and creates notifications on the users interface. I am currently using django-notifications for this although it does not have an option for desktop notifications. I have also searched and can't seem to find anything to use. I would like to implement desktop notifications(with sound) so that even if the user is not on that application's page, they will get notified. Is there a django package that does this kind of thing. Thanks in advance for the help. -
Djange Queryset .annotate - Add 45 days to a date field
I want to display my_date + 345 days using Django .annotate. In the code below, date_plus_1=ExtractYear('my_date')+1, works fine to give me a the year plus one, but I want the date plus 345 days. CODE: .annotate( date_plus_1=ExtractYear('my_date')+1, #date_plus_345=('my_date' + timedelta(days=345)), ) When I remove the # (in the code), my page will not generate. After searching around, I also tried this: date_plus_345=ExpressionWrapper(F('my_date') + timedelta(days=345)), but that did not work either. What is the correct way to use timedelta within .annotate? -
What's the fobi form url? And how do I embed it in another template?
I'm using Django-fobi, and I don't know how to do the following: 1) get a url for sharing the form without allowing a user to edit the form 2) include the form in another existing template Any help is appreciated. -
How to set filter to generate a custom EXCELl with DRF renderer-xlsx
Good afternoon I have the following query, I am using the library Renderer-xlsx of DRF to generate an excel, I download it when passing the respective url, the question is that I want to apply filter to this excel, so that I do not download everything that is in the database, but what I I indicated in the filter. In summary: I have a download button in the frontend (ANGULAR), I press it, I indicate the filter that for example in the excel only comes the records that meet this condition (EquipoOriggen = C65CAN01) I pass it as a request and return get the excel As you see download, but all the records, and I need it with filter My serializer class InterfaceSerializer(serializers.ModelSerializer): # Las siguientes lineas me permiten agregan campos de otros modelos al modelo en cuestion que estoty serializando a traves de llaves foraneas. #Se le agrega la propiedad de read_only=True para que el campo no sea editable. EquipoOrigen = serializers.CharField(source='id_EquipoOrigen.nombre',read_only=True) PuertoOrigen = serializers.CharField(source='id_PuertoOrigen.nombre',read_only=True) LocalidadOrigen=serializers.CharField(source='id_EquipoOrigen.localidad',read_only=True) CategoriaOrigen=serializers.CharField(source='id_EquipoOrigen.categoria',read_only=True) EquipoDestino = serializers.CharField(source='id_EquipoDestino.nombre',read_only=True) PuertoDestino = serializers.CharField(source='id_PuertoDestino.nombre',read_only=True) LocalidadDestino=serializers.CharField(source='id_EquipoDestino.localidad',read_only=True) CategoriaDestino=serializers.CharField(source='id_EquipoDestino.categoria',read_only=True) Vendedor=serializers.CharField(source='id_EquipoOrigen.vendedor',read_only=True) class Meta: model=Interfaces fields=('id_interface','id_EquipoOrigen','EquipoOrigen','id_PuertoOrigen','PuertoOrigen','LocalidadOrigen','CategoriaOrigen','Vendedor','estatus','etiqueta_prtg','grupo','if_index','bw','bw_al','id_prtg','ospf','description','id_EquipoDestino','EquipoDestino','id_PuertoDestino','PuertoDestino','LocalidadDestino','CategoriaDestino','ultima_actualizacion',) class PostPageNumberPagination(PageNumberPagination): page_size=10 page_size_query_param = 'page_size' max_page_size = 1000 #Funcion Para El Filtro del Modelo Interfaces. class InterfacesFilter(filters.FilterSet): EquipoOrigen=filters.CharFilter(field_name='id_EquipoOrigen__nombre',lookup_expr='contains') … -
Java rest client framework for Django QuerySet syntax
There are a bunch of public rest APIs built with Django which expose Django's QuerySet filtering and field selecting features For example: https://api.hubapi.com/content/api/v2/pages?hapikey=demo&translated_from_id__is_null&name__icontains=test&order=created&property=id&property=name&property=current_state&property=translated_content where: &name__icontains=test means case insensitive lookup by the field name which value contains subsgtring test &translated_from_id__is_null means that field translated_from_id is not null &property=id&property=name&property=current_state means that only these declared properties should be returned Other examples: https://www.ebi.ac.uk/chembl/api/data/molecule?molecule_properties__full_mwt__range=200,500 https://www.ebi.ac.uk/chembl/api/data/molecule?molecule_chembl_id__in=CHEMBL25,CHEMBL941,CHEMBL1000 Is there any Java framework which provides high-level abstractions above this query syntax? -
Python/Django Saving m2m with Through
The code below is stripped down to illustrate the issue. While there are things that you may want to say "why would you do this anyway", there is probably a reason in the larger context :) Here is my view: class SubmissionCreate(CreateView): model = Submission fields = '__all__' template_name_suffix = '_create_form' success_url = '/' Here is the relevant models.py code: def custom_filename(instance, filename): author = instance.publishers[0] return 'papers/{0}.pdf'.format(author.pseudonum) class Submission(models.Model): name = models.CharField( max_length=200, blank=False ) upload = models.FileField( blank=True, upload_to=custom_filename ) publishers = models.ManyToManyField( 'Publisher', blank=False, related_name='publisher_of', through='SubmissionPublisher' ) class Publisher(models.Model): user = models.ForeignKey( User, blank=False, on_delete=models.CASCADE ) pseudonym = models.CharField( max_length=200, blank=False ) class SubmissionPublisher(models.Model): publisher = models.ForeignKey( 'Publisher', blank=False, on_delete=models.CASCADE ) submission = models.ForeignKey( 'Submission', blank=False, on_delete=models.CASCADE ) The problem is in the custom_filename, because I need the first publisher from the instance to generate the filename. The Submission is not yet saved when the SubmissionPublisher needs it to be saved. What would the best way to do this be. Hopefully I have made sense here. Thanks for any help! -
how does django channels knows that a client has disconnected?
I fear that a client loses connection abruptly and get disconnected without leaving any info to the backend. If this happens, will the socket keep active? -
Django-filters is it possible to skip values that aren't a choice in the filter?
I want to filter events by who hosts them in my API. NOTE: Hosts do not have their own tables. They are just a field on an event. I want to be able to send multiple values and grab all their events. So for instance if I query like this api/events?host=ashley&host=bob, it will return both bob's and ashley's events. But if a user enters in another name that doesn't have an event, I'd still like it to return the other hosts events. Is that possible, to skip non existent choices? I've been using the django-filter AllValuesMultipleFilter function to filter all the hosts. Is there a way to skip over a choice if it doesn't exist? class EventFilter(dr_filters.FilterSet): after_start_date = dr_filters.DateTimeFilter(field_name="start_date", lookup_expr="gte") before_end_date = dr_filters.DateTimeFilter(field_name="end_date", lookup_expr="lte") category = dr_filters.AllValuesFilter(field_name="categories__name") venue = dr_filters.AllValuesFilter(field_name="venue__name") status = dr_filters.AllValuesMultipleFilter(field_name="event_status") host = dr_filters.AllValuesMultipleFilter(field_name="host") class Meta: model = Event fields = ( "after_start_date", "before_end_date", "internal_only", "category", "venue", "status", "host" ) # Define ViewSets class EventViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = EventSerializer filter_backends = (filters.SearchFilter, dr_filters.DjangoFilterBackend,) filter_class = EventFilter search_fields = ("name",) ordering_fields = ("name", "start_date", "venue",) def get_queryset(self): qs = Event.objects.filter(start_date__gte=timezone.now()) qs = qs.order_by("start_date") return qs { "host": [ "Select a valid choice. emma is not one of the available … -
Dynamically Adding a Field to Django modelformset ManagementForm data is missing or has been tampered with
In my app, I have to dynamically add a field to the modelformset in the init method of the custom modelformset by extending BaseModelFormSet. class BaseInvoiceFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): excluded_fields = kwargs.pop('excluded_fields', None) super(BaseInvoiceFormSet, self).__init__(*args,**kwargs) for form in self.forms: form.fields.update({'min_unit_share': forms.IntegerField(validators = [validate_positive,] ) }) form.fields.move_to_end('min_unit_share', last=False) # Note that self.fields is an ordereddict. To move an item to the front of an ordered dict in Python 3.0+ I get Exception Type: ValidationError Exception Value: ['ManagementForm data is missing or has been tampered with'] When I comment out the dynamically added field, the error goes away. So, the post method of the class view calls the init method as expected. But, for some reason it thinks that I am changing the ManagementForm data. The question is how to get around or resolve this issue. Is there a way to pop out the added field before calling super(BaseInvoiceFormSet, self).init(*args,**kwargs) Note that it seems all the modelformset data is passed through using *args. It is sitting at args[0] and I could not pop the additional field using args[0].pop('min_unit_share') Also, to make things simple, in my template, I use: {% for form in formset %} {{ form.as_p }} {% endfor %} Any … -
Select users with common answers to questions
I have four models including the CustomUser table. class Question(models.Model): question = models.CharField(max_length=140) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') answer = models.CharField(max_length=70) class Response(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.ForeignKey(Answer, on_delete=models.CASCADE) Each question has multiple answers but each user can only pick one answer to each question. Each user can answer multiple questions. How do I select a list of users with a nested list of their common answers to a reference user with just the ORM? I can think of a hacky solution of retrieving the list of common answers and then a python loop to increment the count for each user but I would like to confine it to the ORM as I need to append this to a parent serializer (UserSerializer -> ResponseSerializer).