Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Limit the amount of logins Django server
I need limit traffic to Django server, but I don't know about that problem. I need be provided some keyword to to solve that problem. Thanks -
How can I generate QR code in django project?
Can anyone guide me to generate QR code in django project? I want to generate Qr code by taking data from postgres database and display it in the template? -
what is the route_class replacement?
I'm following a tutorial about GraphQL subscriptions with Django. But on routing channels does not have "route_class" member. But I can't found why. Anyone knows how to use channels routing? class Suscription(ObjectType): count_seconds = Int(up_to=Int()) def resolve_count_seconds(root, info, up_to=5): return Observable.interval(1000).map(lambda i: "{0}".format(i))\ .take_while(lambda i: int(i) <= up_to) ROOT_SCHEMA = graphene.Schema(query=Query, mutation=Mutation, suscription=Suscription) #urls from channels.routing import route_class # route_class does not exists from graphql_ws.django_channels import GraphQLSubscriptionConsumer channel_routes = [ route_class(GraphQLSubscriptionConsumer, path='subscriptions') ] -
python - Django ORM retrieve parent model with filtered children model
I have the following models in Django: class Gasto(models.Model): monto = models.DecimalField(default=0,decimal_places=2, max_digits=10) nombre = models.CharField(max_length=30) informacion = models.TextField(blank=True, default="") numero_cuotas = models.PositiveSmallIntegerField(default=1) es_compartido = models.BooleanField(default=False) es_divisible = models.BooleanField(default=False) contrato = models.ForeignKey(Contrato, on_delete=models.PROTECT) class Cuota_Gasto(models.Model): monto = models.DecimalField(default=0,decimal_places=2, max_digits=10) fecha = models.DateField() gasto = models.ForeignKey(Gasto, related_name='cuotas',on_delete=models.DO_NOTHING) factura_rendida = models.ForeignKey(Factura, on_delete=models.DO_NOTHING, null=True, related_name='gasto_rendido') factura_liquidada = models.ForeignKey(Factura, on_delete=models.DO_NOTHING, null=True, related_name='gasto_liquidado') From now on: 'Gasto' will be called Expense, and 'Cuota_Gasto' will be called Share. Expense is the parent model and Share is the children, with a 1..N relationship. I want to retrieve each Expense with its Shares, BUT only those Shares that meet certain conditions. Is this possible? I could get each expense with ALL shares by using related_name and reverse relantionship, for example: { "monto": "-500.00", "nombre": "RRR", "informacion": "Extra", "numero_cuotas": 1, "es_compartido": true, "cuotas": [ { "id": 16, "nombre": "RRR", "informacion": "Extra", "contrato": 3, "monto": "-500.00", "fecha": "07/07/2019", "gasto": 4, "factura_rendida": null, "factura_liquidada": 12 } ] } But I can't get to the query that allows me to exclude the shares i don't want. I was thinking about something like this: Gasto.objects.distinct().filter(cuotas__fecha__lte = date) Even though that query is not correct. I hope someone can help me. Thanks -
Using a personal module with Django
I have created a Python project and stored it as a module with the following file structure - rrs |--main.py |--Pack1 |-- |-- . . |--Pack2 |-- |-- . . Now, I am serving this project through Django. I created a separate django project with just one home app. I have placed the rrs folder inside my home app as I want the home view to access the main.py in the rrs folder myproject |-----home |---views.py |---rrs |--- . . |-----website |----settings.py |--- . . Now when I run the server it throws an error saying no module name Pack1 found. How would I fix this? -
Persisting data _somewhere_ in real-time game
I am building a game where users solve math problems in order to move. Up is one problem, right is another, down is another, and so on. When the user sends an answer to the server, the server needs to check if not only the answer is correct, but what direction of movement the answer corresponds to. In order to do this I would need to persist the data somewhere after initial creation. I thought about using a database but this would be overkill, I think, and the game is very intense and fast and real-time (values would be changing constantly -- I would imagine a database would be too slow for this game). Does anyone have any suggestions? Thanks in advance. -
How to resolve recursion error in python django urls.py
I'm pretty new to django and working on a project from https://github.com/mkaykisiz/DjangoS3Browser/ where I'm ending up with recursion error after adding "url(r'^' + settings.S3_BROWSER_SETTINGS + '/', include('djangoS3Browser.s3_browser.urls'))," line to url.py URL.py from django.conf.urls import url, include from django.conf.urls.static import static from djangoS3Browser.s3_browser import settings from djangoS3Browser.s3_browser import views import sys urlpatterns = [ url(r'^get_folder_items/(.+)/(.+)/$', views.get_folder_items, name='get_folder_items'), url(r'^upload/$', views.upload, name='upload'), url(r'^create_folder/$', views.create_folder, name='create_folder'), url(r'^download/$', views.download, name='download'), url(r'^rename_file/$', views.rename_file, name='rename_file'), url(r'^paste_file/$', views.paste_file, name='paste_file'), url(r'^move_file/$', views.move_file, name='move_file'), url(r'^delete_file/$', views.delete_file, name='delete_file'), url(r'^' + settings.S3_BROWSER_SETTINGS + '/', include('djangoS3Browser.s3_browser.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Settings.py: AWS_ACCESS_KEY_ID = "" AWS_SECRET_ACCESS_KEY = "" AWS_STORAGE_BUCKET_NAME = "" AWS_S3_ENDPOINT_URL = "" AWS_AUTO_CREATE_BUCKET = True AWS_QUERYSTRING_AUTH = False S3_BROWSER_SETTINGS = "djangoS3Browser" AWS_EXPIRY = 60 * 60 * 24 * 7 control = 'max-age=%d, s-maxage=%d, must-revalidate' % (AWS_EXPIRY, AWS_EXPIRY) AWS_HEADERS = {'Cache-Control': bytes(control, encoding='latin-1')} TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'libraries': {'s3-load': 'djangoS3Browser.templatetags.s3-tags',}, 'context_processors': ["django.contrib.auth.context_processors.auth",'django.contrib.messages.context_processors.messages',] } } ] SECRET_KEY = 'y130-j9oz4r5aoamn_n=+s-*7n)*3^s$jmf4(qw6ik28()g^(n' DEBUG = True ALLOWED_HOSTS = ['*'] ROOT_URLCONF= 'djangoS3Browser.s3_browser.urls' LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' STATIC_URL = '{}/static/'.format(AWS_S3_ENDPOINT_URL) STATIC_ROOT = '/static/' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'djangoS3Browser', ] WSGI_APPLICATION = 'djangoS3Browser.s3_browser.wsgi.application' MIDDLEWARE = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) Actual result: … -
Django: NoReverseMatch 1 pattern(s) tried: ['PUTData/(?P<pk>[0-9]+)/$']
So I'm doing my first project using django showing examples of REST API methods like POST, GET, PUT, and DELETE through a made up database of first name, last name, and e-mail. I've been successful with POST and GET but now I am having trouble with PUT. So I have three functions. First, a simple def function that shows all inputs of information so far. Second a class based function that lists the information in a specific order. And third, another class based function that shows the detail of that specific information. All functions work but now when I am linking the two html files together I am getting a error. I've tried a number of different ids when wanting to link to that specific information but they are just not working. But here is my models.py: class Information(models.Model): """Placeholder code that the viewer will be seeing.""" info_id = models.AutoField(primary_key=True,unique=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) e_mail = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return information.""" return f"Info ID: {self.info_id}, First Name: {self.first_name}, Last Name: {self.last_name}, E-mail: {self.e_mail}" Here is my forms.py: class NameForm(forms.ModelForm): class Meta: model = Information fields = ['info_id', 'first_name', 'last_name', 'e_mail'] labels = {'first_name': 'First Name:', … -
Folium map in Django only says 'None'
I am trying to create map in Django using folium. There is no error message, but instead of the map it displays the word 'None'. I have a django web app that reads from a postgressql database and displays the records. That is working. I want to add a map with markers, and the markers will get coordinates from the postgresql data. When I try to create a map using iframe, I get the word 'None'. I have tried just hard coding a starting location to just create the map. I still get the word 'None'. I also typed the hard coded coordinates into google maps, and made a flask app that creates the map. They show up fine. views.py: from django.shortcuts import render from django.http import HttpResponse from .models import PhotoInfo import folium import pandas # Create your views here. def index(request): VarPhotoInfo = PhotoInfo.objects.order_by('DateTaken') context = {'PhotoInfo': VarPhotoInfo } return render(request,'natureapp/index.html',context) def show_map(request): #creation of map comes here + business logic #PhotoInfo1 = PhotoInfo.objects.order_by('DateTaken') map = folium.Map(location=[33.57137166666667, -117.76325]) map.save("natureapp/map.html") context = {'my_map': map } return render(request, 'natureapp/map.html', context) map.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>NatureMapper</title> </head> <h1>Map goes here </h1> {{ my_map.render }} </html> index.html: <!DOCTYPE html> … -
How can I filter my records in django database?
I have these data with same movie_id and cinema_name but I want them to list as one. I am using sqlite3 for my database. Here is my example data: { "result": [ { "id": "06273d05-dd3a-5738-bf44-3eca7e329969", "schedule": { "cinema": "5", "movie": "0f427f18-23d0-54e3-825e-b56a0f93786f", "price": "500.00", "seating_type": "Guaranteed Seats", "show_date": "18 Oct 2017", "start_time": "02 45 00 PM", "theater": "GB3", "variants": "3D/4DX" } } ] }, { "result": [ { "id": "8954b8b4-9ffb-5d19-a4eb-6cc296bc6aaa", "schedule": { "cinema": "5", "movie": "0f427f18-23d0-54e3-825e-b56a0f93786f", "price": "500.00", "seating_type": "Guaranteed Seats", "show_date": "18 Oct 2017", "start_time": "05 10 00 PM", "theater": "GB3", "variants": "3D/4DX" } } ] }, { "result": [ { "id": "1a7ed3d2-c05f-57e6-84aa-24870d47d43e", "schedule": { "cinema": "4", "movie": "0f427f18-23d0-54e3-825e-b56a0f93786f", "price": "500.00", "seating_type": "Guaranteed Seats", "show_date": "18 Oct 2017", "start_time": "12 20 00 PM", "theater": "BHS", "variants": "3D/4DX" } } ] }, { "result": [ { "id": "bb749fd7-b5f6-5fda-84a2-149fc3053b95", "schedule": { "cinema": "4", "movie": "0f427f18-23d0-54e3-825e-b56a0f93786f", "price": "500.00", "seating_type": "Guaranteed Seats", "show_date": "18 Oct 2017", "start_time": "02 45 00 PM" "theater": "BHS", "variants": "3D/4DX" } } ] } How can I make group them by theater or cinema so I would get data like this: "result": [ { "id": "bb749fd7-b5f6-5fda-84a2-149fc3053b95", "schedule": { "cinema": "4", "movie": "0f427f18-23d0-54e3-825e-b56a0f93786f", "price": "500.00", "seating_type": "Guaranteed Seats", "show_date": "18 … -
I cannot paginate with the ListModelMixin class an action decorator
Good night I can not paginate with the ListModelMixin class an action decorator, the question is that I page but I show on each page the total number of objects that are going to be displayed, that is, if I have 27 records, the 27 is shown on each page. class InterfacesViewSet(viewsets.ModelViewSet): queryset = Interfaces.objects.all() serializer_class = InterfaceSerializer pagination_class = PostPageNumberPagination def get_response_data(self,paginated_queryset): data =[ { 'id_interface': interface.id_interface, 'id_EquipoOrigen': interface.id_EquipoOrigen_id, 'EquipoOrigen': interface.id_EquipoOrigen.nombre, 'LocalidadOrigen': interface.id_EquipoOrigen.localidad, 'CategoriaOrigen': interface.id_EquipoOrigen.categoria, 'id_PuertoOrigen': interface.id_PuertoOrigen_id, 'PuertoOrigen': interface.id_PuertoOrigen.nombre, 'estatus': interface.estatus, 'etiqueta_prtg': interface.etiqueta_prtg, 'grupo': interface.grupo, 'if_index': interface.if_index, 'bw': interface.bw, 'bw_al': interface.bw_al, 'id_prtg': interface.id_prtg, 'ospf': interface.ospf, 'description': interface.description, 'id_EquipoDestino': interface.id_EquipoDestino_id, 'EquipoDestino': interface.id_EquipoDestino.nombre, 'LocalidadDestino': interface.id_EquipoDestino.localidad, 'CategoriaDestino': interface.id_EquipoDestino.categoria, 'id_PuertoDestino': interface.id_PuertoDestino_id, 'PuertoDestino': interface.id_PuertoDestino.nombre, 'ultima_actualizacion': interface.ultima_actualizacion, } for interface in self.queryset] return data @action(methods=['get'], detail=False, url_path='registros-data-table', url_name='registros_data_table') def registros_data_table(self, request): queryset = Interfaces.objects.all() page = self.paginate_queryset(queryset) if page is not None: data = self.get_response_data(page) return self.get_paginated_response(data) data = self.get_response_data(queryset) return Response(data) -
Pyzipcode3 not finding ziptable
A process killed my terminal on a Mac and I created a new virtual environment. Pyzipcode3 is installed there. However, whenever I try to run a command on it's zcdb. I get this error: sqlite3.OperationalError: no such table: zip Not sure how to fix this. This is what I have: zcdb = ZipCodeDatabase() path = settings.GEO_DB_PATH This all runs, so the package seems to be installed, but it's not finding the db. The Settings GEO_DB_PATH has a path to the GeoCity2.mmdb. >>> from pyzipcode import ZipCodeDatabase >>> zcdb = ZipCodeDatabase() >>> zipcode = zcdb[54115] Traceback (most recent call last): File "<console>", line 1, in <module> File "/venv/lib/python3.7/site-packages/pyzipcode/__init__.py", line 108, in __getitem__ zip_code = self.get(str(zip_code)) File "~/venv/lib/python3.7/site-packages/pyzipcode/__init__.py", line 105, in get return format_result(self.conn_manager.query(ZIP_QUERY, (zip_code,))) File "~/lib/python3.7/site-packages/pyzipcode/__init__.py", line 35, in query cursor.execute(sql, args) sqlite3.OperationalError: no such table: zip >>> -
Why am in not able to retrieve the manager profile in django 2.1
I am using django 2.1 and for some reason in the views, using Function based views, i am unable to update the information from the models Manager. I have tried to codes below: models.py User = settings.AUTH_USER_MODEL class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='customers') phone_number = models.CharField(max_length=10) city = models.CharField(max_length=30) state = models.CharField(max_length=30) postal_code = models.CharField(max_length=30) def __str__(self): return self.user.username class Manager(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='managers') title = models.CharField(max_length=50) company_name = models.CharField(max_length=30) def __str__(self): return self.user.username forms.py class UserUpdateForm(forms.ModelForm): class Meta: model = User fields = ( 'username', 'email' ) class ManagerUpdateForm(forms.ModelForm): class Meta: model = Manager fields = ( 'title', 'company_name' ) views.py def manager_profile(request): if request.method == 'POST': user_form = UserUpdateForm(request.POST, instance=request.user) manager_form = ManagerUpdateForm(request.POST, instance=request.user.manager) if user_form.is_valid() and manager_form.is_valid(): user_form.save() manager_form.save() return redirect('user:manager_profile') else: user_form = UserUpdateForm(instance=request.user) manager_form = ManagerUpdateForm(instance=request.user.manager) context={ 'user_form': user_form, 'manager_form': manager_form } return render(request, 'user/manager-profile.html', context) Here is the error message from the console. AttributeError: 'User' object has no attribute 'manager' It comes from the line manager_form.... I am just trying to update the information in the profile page from the table Manager. -
Problema ao usar SmartSelect no Django
boa noite! estou com a seguinte dúvida, não sei como resolver. Preciso que as disciplinas que aparece no dropdown sejam apenas as disciplinas que estão vinculadas a turma, ou seja, eu vou selecionar uma turma e ele me traz só as disciplinas daquela turma selecionada, ao alterar a turma, muda as disciplinas. Sendo que uma turma, tem um curso que tem matriz curricular e a matriz por sua vez tem as disciplinas. Consegui resolver parcialmente utilizando o app Django Smart Selects, porém ele só me traz uma disciplina. Sendo que tem várias. Para ajudar, segue o trecho do código: https://gist.github.com/albertojr/f4c4b4c44a12c7e557e1087ea5026da4 -
cant import class if it under another class [duplicate]
This question already has an answer here: Django circular model reference 7 answers can not add primary contact in company table from contact table from django.db import models # from .models import contact # Create your models here. class company(models.Model): name = models.CharField(max_length=80) telephone = models.CharField(max_length=30,null=True) website = models.URLField() PrContact = models.OneToOneField(contact.name, on_delete=models.CASCADE, default="1",null=True,blank=True) def __str__(self): return self.name class contact(models.Model): name =models.CharField(max_length=80) company = models.ForeignKey(company,on_delete=models.PROTECT) email =models.EmailField(null=True) def __str__(self): return self.name also when i put every model in defrant app the same issue i found i cant import , is ther any way to put primary contact in every company andin the same time add every contac in company -
What is the correct why to setup Django static files dirs and URLs
I can't seem to get the situation of the static file correctly in Django and the documentation is terrible. Here is how I have my static files setup in settings.py and url.py settings.py PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') MEDIA_ROOT = os.path.join(PROJECT_ROOT,"media") urls.py urlpatterns = [ path('', admin.site.urls), path('admin/', admin.site.urls), url(r'^tinymce/', include('tinymce.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) when I want to load a js file that exists in the statics folder I get the following error /static/showhide.js HTTP/1.1" 404 1758 but the file actually is in that path so why do I get 404? -
Django Architecture: Where should I schedule a Celery Beat Periodic Task for ALL users?
I have a django-celery-beat periodic task that needs to be run for every user on every Monday of every week. I'm not sure where the right place to create this task is for the first time to schedule it. I understand that per-user celery tasks can be created wherever in the particular code with PeriodicTask and Interval, but since this is run for every user I'm not quite sure where it should go or how to instantiate it. -
method() takes 1 positional argument but 2 were given in pagination decorator action
I have a problem doing a paginator about an action decorator in django rest framework and I can't find the solution, the question is that it gives me the following error: get_response_data () takes 1 positional argument but 2 were given class InterfacesViewSet(viewsets.ModelViewSet): queryset = Interfaces.objects.all() serializer_class = InterfaceSerializer pagination_class = PostPageNumberPagination def get_response_data(paginated_queryset): data =[ { 'id_interface': interface.id_interface, 'id_EquipoOrigen': interface.id_EquipoOrigen_id, 'EquipoOrigen': interface.id_EquipoOrigen.nombre, 'LocalidadOrigen': interface.id_EquipoOrigen.localidad, 'CategoriaOrigen': interface.id_EquipoOrigen.categoria, 'id_PuertoOrigen': interface.id_PuertoOrigen_id, 'PuertoOrigen': interface.id_PuertoOrigen.nombre, 'estatus': interface.estatus, 'etiqueta_prtg': interface.etiqueta_prtg, 'grupo': interface.grupo, 'if_index': interface.if_index, 'bw': interface.bw, 'bw_al': interface.bw_al, 'id_prtg': interface.id_prtg, 'ospf': interface.ospf, 'description': interface.description, 'id_EquipoDestino': interface.id_EquipoDestino_id, 'EquipoDestino': interface.id_EquipoDestino.nombre, 'LocalidadDestino': interface.id_EquipoDestino.localidad, 'CategoriaDestino': interface.id_EquipoDestino.categoria, 'id_PuertoDestino': interface.id_PuertoDestino_id, 'PuertoDestino': interface.id_PuertoDestino.nombre, 'ultima_actualizacion': interface.ultima_actualizacion, } for interface in queryset] return data @action(methods=['get'], detail=False, url_path='registros-data-table', url_name='registros_data_table') def registros_data_table(self, request): queryset = Interfaces.objects.all() page = self.paginate_queryset(queryset) if page is not None: data = self.get_response_data(page) return self.get_paginated_response(data) data = self.get_response_data(queryset) return Response(data) -
website access through IIS windows authentication and django
I am setting up a website through IIS and Django. I would like to secure my IIS site so only the desired people can access it, in particular, I would like to rely on their windows credential within our network for authentication. To do that I have added IIS Windows Authentication and enabled it for the website through. I have also followed the django tutorial on adding REMOTE_USER definitions in settings.py. When I try to access the web site as a user on my network I get the following error: OperationalError at attempt to write a readonly database Request Method: GET Request URL: http://myawesomewebsite.com/ Django Version: 2.2.3 Exception Type: OperationalError Exception Value: attempt to write a readonly database Exception Location: >c:\users\zolo\appdata\local\programs\python\virtualenv\dashboard\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 383 Python Executable: >c:\users\zolo\appdata\local\programs\python\virtualenv\dashboard\scripts\python.exe please help me find the missing piece of the puzzle. I am pretty new to Django and IIS and would appreciate the help Python Version: 3.7.2 DJANGO version 2.23 IIS version: 10.0 Windows Server 2016 -
Django: Should sendgrid emails always be sent from Celery?
I'm using django-sendgrid-v5 and I read somewhere that it isn't good to send emails from the main webserver. Should I process emails from Celery? Or is it fine to call from the main app since I'm using an external service like Sendgrid anyways? -
Diango model property to return list of objects of other model
I have 2 models like this: class Company(models.Model): name = models.CharField(max_length=200) address = models.CharField(max_length=200) class Meta: verbose_name = 'Company' And another model: class Product(models.Model): name = models.CharField(max_length=200) company = models.ForeignKey(to=Company, on_delete=models.PROTECT) class Meta: verbose_name = 'Product' Now, I need to make a property in Company model which could return a list of all Product Objects, like @property def products (self): products = [] for i in Product.objects().filter(company=self.id): products.append(i) return products When I mention products (property) in CompanySerializer fields, it give me an error that it cannot return a list of objects. Can anyone solve my problem and tell me what is wrong with the code? -
column app_element.image does not exist - Django PostgreSQL
I apologize if my question is simple, but the database problems are unfamiliar to me. On my VPS server where is my django app I receives the error below, which occurred after adding a new field in my models.py file (in the local repo and later after merging): Environment: Request Method: GET Request URL: http://167.71.54.97/row-bootstrap/ Django Version: 2.2.3 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', 'crispy_forms'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /home/app/app/app/templates/solution.html, error at line 78 column app_element.image does not exist LINE 1: ...", "app_element"."slug", "app_element"."created", "app_eleme... ^ 68 : <div class="container-fluid"> 69 : <div class="row justify-content-between"> 70 : <div class="col-lg-9 col-xl-8 offset-xl-1"> 71 : <div class="docs-content"> 72 : <div class="docs-page-title mt-2"> 73 : <h2>{{ solution.name }} 74 : </h2> 75 : <p>{{ solution.created }}, {{ solution.category }}, 76 : <p> 77 : </div> 78 : {% for element in solution.element_set.all %} 79 : <h2 id="{{ element.slug }}">{{ element.file_name }}</h2> 80 : <p>{{ element.tips }}</p> 81 : {% if element.image %} 82 : <a href="{{ element.image.url }}" data-fancybox data-caption="{{ element.file_name }}"> 83 : <img src="{{ element.image.url }}" class="w-50 img-fluid rounded mb-2"> 84 : </a> 85 : {% … -
Combine DetailView and UpdateView?
i am new to Django and i need to know how to have DetailView and UpdateView on same Page. I have a two Models: class Company(models.Model): CustomerNo = models.AutoField(primary_key=True) Company = models.CharField(max_length=200) Str = models.CharField(max_length=200) Zip = models.IntegerField() City = models.CharField(max_length=200) Name = models.CharField(max_length=200) Phone = models.IntegerField() Mobile = models.IntegerField() Email = models.EmailField(max_length=200) Web = models.CharField(max_length=200) Info = models.CharField(max_length=200) def __str__(self): return self.Company class Contact(models.Model): Contact_Company = models.ForeignKey(Company, on_delete=models.CASCADE) Contact_Name = models.CharField(max_length=200) Contact_Phone = models.IntegerField() Contact_Mobile = models.IntegerField() Contact_Fax = models.IntegerField() Contact_E_Mail = models.EmailField() Contact_Web = models.CharField(max_length=200) def __str__(self): return self.Contact_Name I want to build a page where i can see the company data from the first model and a update form for contacts realeted to the first model. I enter the page with pk, from the previous page, its a DetailView for the first Model and with additionally context to list the Contact data with a for loop in Template. I can use UpdateView to get data in the form and save it. but i don't know how do display the realeted Company on the same page. Is there a way to use DetailView and UpdateView together? I can use this UpdateView to change the Contact data, but i … -
How can I know the next value of the Django queryset without having to loop and store values?
I'm writing a website using Django and Vue.js. Although I am admittedly a beginner at both, I find this surprising that I can't seem to be able to know, beforehand the value of the next item of a queryset. I need to know if there is a way to do it in Django. For instance, I perform a search on the database, it returns a queryset, and I start to call the elements of the queryset one after the other. Is there a way to know the next beforehand? def fetch_question(request): question_id = request.GET.get('question_id', None) response = Question.objects.filter(pk=question_id) ''' -
how reconnect django signals after disconnected from a for loop formset
i want send signals only for one view in a formset , i disconnected the signal after the first loop views.py def ProductOrderCreate(request): template_name = 'create_product_order.html' if request.method=='GET': formset = ProductFormSet(request.GET or None) elif request.method=='POST': formset = ProductFormSet(request.POST) if formset.is_valid(): for form in formset: product = form.cleaned_data.get('product') quantity = form.cleaned_data.get('quantity') ProductOrder(product=product , quantity=quantity).save() signals.pre_save.disconnect(create_order_instance,sender=ProductOrder) return redirect('/orders/') return render(request , 'create_product_order.html' , {'forms':formset}) signals @receiver(pre_save , sender=ProductOrder) def create_order_instance(sender, instance, **kwargs): Order.objects.create() pre_save.connect(create_order_instance,sender=ProductOrder) @receiver(pre_save,sender=ProductOrder) def create_ordering(sender,instance,**kwargs): if not instance.ordering: instance.ordering = Order.objects.order_by('-pk')[0] pre_save.connect(create_ordering,sender=ProductOrder) models.py class Product(models.Model): name = models.CharField(max_length=50) price = models.PositiveIntegerField(default=1) def __str__(self): return self.name class Order(models.Model): id = models.AutoField(primary_key = True) products = models.ManyToManyField(Product ,through='ProductOrder') @property def total(self): return self.productorder_set.aggregate( price_sum=Sum(F('quantity') * F('product__price'), output_field=IntegerField()) )['price_sum'] class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE,default='' ) ordering = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) forms.py class ProductOrdering(forms.ModelForm): class Meta: model = ProductOrder fields = ['product','ordering','quantity'] ProductFormSet = formset_factory(ProductOrdering , extra=2) now , i want to reconnect the signals for the next view where should i put this code signals.pre_save.connect(create_order_instance,sender=ProductOrder) i put connected code after the render() but doesnt work as i expected , also outside of the function still not reconnected