Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Heroku postgres connectivity error
I'm trying to push a basic Wagtail Django site (pip install wagtail) to Heroku following this guide with guidance from the Heroku docs and I am getting a very common postgres connectivity error (below). I can see from the dashboard that Heroku is providing the live database, and I can access it with heroku pq:psql. The project runs locally and also when I run heroku local. My `project/app/settings/production.py' is set up as recommended: import os env = os.environ.copy() SECRET_KEY = env['SECRET_KEY'] from __future__ import absolute_import, unicode_literals from .base import * DEBUG = False try: from .local import * except ImportError: pass # Parse database configuration from $DATABASE_URL import dj_database_url DATABASES = {'default': dj_database_url.config(default='postgres://localhost')} print('check') print(DATABASES) # Honor the 'X-Forwarded-Proto' header for request.is_secure() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Allow all host headers ALLOWED_HOSTS = ['*'] The error I get: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? Can anyone … -
Django: Is it OK to set a field to allow null which is assigned in clean func?
My Career model has fields, since, until, and currently_employed. # resume/models.py ... class Career(models.Model): resume = models.ForeignKey(Resume, on_delete=models.CASCADE) since = models.DateField() until = models.DateField(blank=True, null=True) currently_employed = models.BooleanField() company = models.CharField(max_length=50) position = models.CharField(max_length=50) achivement = models.TextField(default='') I'd like to set until to current date if currently_employed is checked in the django(python) code, not in the template(html/js), as possible. # resume/forms.py ... class CareerForm(forms.ModelForm): ... def clean(self): cleaned_data = super().clean() if cleaned_data['currently_employed'] == True: cleaned_data['until'] = timezone.now().date() # Check since < until if cleaned_data['since'] >= cleaned_data['until']: raise ValidationError('"Until" should be later than "Since"') ... Is it OK to set the until nullable?(and its form field set required=False) However, it would not be null in my logic since by currently employed, or user put that. -
Django Unit Tests - Unable to create the django_migrations table
I'm trying to write some unit tests and run them using manage.py test but the script can't create the django_migrations table for some reason. Here is the full error: Creating test database for alias 'default'... Traceback (most recent call last): File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\utils.py", line 83, in _execute return self.cursor.execute(sql) psycopg2.ProgrammingError: no schema has been selected to create in LINE 1: CREATE TABLE "django_migrations" ("id" serial NOT NULL PRIMA... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\migrations\recorder.py", line 55, in ensure_schema editor.create_model(self.Migration) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\base\schema.py", line 298, in create_model self.execute(sql, params or None) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\base\schema.py", line 117, in execute cursor.execute(sql, params) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Program Files (x86)\Python36-32\lib\site-packages\django\db\backends\utils.py", line 83, in _execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: no schema has been selected to create in LINE 1: CREATE TABLE "django_migrations" ("id" serial NOT NULL PRIMA... ^ During handling of the … -
Add a field using javascript in django-admin
In my admin I want a select field with choices based on the user choice in another admin field, so I think I have to use javascript. Here my models.py (simplified): class Society(models.Model): name = models.CharField(max_length=32, unique=True) class Title(models.Model): name = models.CharField(max_length=32, unique=True) society = models.ForeignKey(Society, on_delete=models.PROTECT) class Mymodel(models.Model): society = models.ForeignKey(Society, on_delete=models.PROTECT) class Myuser(User_Add, BaseUser): ... myfield = models.ManyToManyField(Mymodel, through='Mytable') ... class Mytable(models.Model): myuser = models.ForeignKey(Myuser, on_delete=models.CASCADE) myfield = models.ForeignKey(Mymodel, null=True, on_delete=models.CASCADE) title = models.ForeignKey(Title, on_delete=models.CASCADE) My admin.py: class MytableInline(admin.TabularInline): model = Mytable extra = 0 exclude = ('title',) class MyuserAdmin(admin.ModelAdmin): inlines = [MytableInline] Mytable is showed inline with myuser and it has just one field: myfield. When I choose the value of this field (so a Mymodels instance) I want another field to appear (or become active): title. In this new field I don't want all the Title instance but only the one with society field ugual to the society field of the Mymodel instance choosen. First thing is to write the javascript function. In my javascript.js: $(document).ready(function() { document.getElementById('id_myuser_mytable-__prefix__-myfield').addEventListener('change', function() { console.log('changed') }); }); This dosn't do nothing. I find that id looking at the source of my django generated admin page. -
What's the best non-volatile way of storing data for a Django 2.0 project?
I want to create an app using Django that users can interact with and post to using HTTP requests, but I don't want to store the data in a database, the data should be lost once the server is turned off. I was thinking of using arrays and sessions but I'm just wondering if there are other options. It is a very simple app only storing strings and integers. Thank you in advance! -
Merging PDFs using reportlab and PyPDF2 loses images and embedded fonts
I am trying to take an existing PDF stored on AWS, read it into my backend (Django 1.1, Python 2.7) and add text into the margin. My current code successfully takes in the PDF and adds text to the margin, but it corrupts the PDF: When opening in the browser: Removes pictures Occasionally adds characters between words Occasionally completely changes the character set of the PDF When opening in Adobe: Says "Cannot extract the embedded font 'whatever font name'. Some characters many not display or print correctly" Says "A drawing error occured" If there were pictures pre-edit, says "Insufficient data for an image" I have made my own PDF with/without predefined fonts and with/without images. The ones with predefined fonts and no images work as expected, but with images it throws "There was an error while reading a stream." when opening in Adobe, and just doesn't show the images in the browser. I have come to the conclusion that missing fonts is the reason for the problems with the characters, but I'm not sure why the images aren't showing. I don't have control over the contents of the PDFs I'm editing so I can't ensure they only use the predefined … -
Reactstrap + django + django framework
I am working on a project and I want to know if it's possible integrate reactstrap with Django and Django Framework and how to go about it -
Django allauth AssertionError
Hello received AssertionError when try to add ACCOUNT_USERNAME_VALIDATORS = ('allauth.socialaccount.providers.battlenet.validators.BattletagUsernameValidator',) Same happen when it is a list, and if i add just str , i am receiving error that ACCOUNT_USERNAME_VALIDATORS must be a list -
How to create a compound form in Django
There are models: class Account(models.Model): num_account = models.CharField(max_length=11,blank=False,primary_key=True) ... class Counter(models.Model): num_account = models.ForeignKey(Account, on_delete=models.CASCADE) service = models.ForeignKey(Service, on_delete=models.CASCADE) class HistoryApplication(models.Model): counter = models.ForeignKey(Counter, on_delete=models.CASCADE) application = models.DecimalField(max_digits=4, decimal_places=1, blank=False, null=False, validators=[MinValueValidator(0)]) Imagine: there is Account, two Counter are tied to the Account, each Counter has Histories Application. How to make a form that displays fields for input from History Applicaton for each Counter from Counter model tied to Account -
django-python3-ldap Does TLS Encrypt Passwords over http
I have implemented django-python3-ldap and integrated AD with my Django project. The project will be hosted on IIS as an intranet site that is served solely over http. I am deciding between using this solution or Django's RemoteUserBackend. Using RemoteUserBackend with IIS and enabling Windows Authentication prevents clear text passwords from being sent across the network. Is the same thing happening when I set LDAP_AUTH_USE_TLS = True and my LDAP_AUTH_URL is pointing to an LDAPS domain controller? Is it more secure (all relative, I know) to use this solution or the IIS RemoteUserBackend solution? -
how to reference a foreign key's value in a django model?
I'm trying to build a simple Queue app, where a user can take a ticket with a number in a queue of a certain room. The problem I have is that I don't know how to create a field that on the ticket creation the ticket value should be the value of the next free number in the room, however, when another ticket will be created the value of the first ticket shouldn't be changed. Here is my failed attempt (its failing on the save method of ticket): from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Room(models.Model): name = models.CharField(max_length=100) room_master = models.ForeignKey(User, on_delete=models.CASCADE) current_visitor_number = models.BigIntegerField(default=0) next_number_to_take = models.BigIntegerField(default=0) def __str__(self): return self.name + ' ' + str(self.room_master) def get_cur_room_q(self): return Ticket.objects.filter(room=self.name).order_by('request_date') class Ticket(models.Model): request_date = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) number = models.BigIntegerField(default=0) def save(self, *args, **kwargs): self.number = self.room.next_number_to_take self.room.next_number_to_take += 1 super(Ticket, self).save(*args, **kwargs) def __str__(self): return str(self.user.first_name) + ' ' + str(self.user.last_name) + ' ' + str(self.request_date) I have previously tried the following which also failed: class Ticket(models.Model): request_date = models.DateTimeField(default=timezone.now) user = models.ForeignKey(User, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) number = … -
Which do I would use between Sylius (Symfony) and Oscar (Django) as a component or service for another system?
I currently have to decide between using Oscar or Sylius framework to add e-commerce functionalities to a custom learning management system (LMS). I had noticed that both are good, modular and component-oriented, also they have ReST API to use them from another app, but even so, I can't choose one of the two. So I want opinions or ideas of anyone with experience on this stage. -
python Django API, How to Serialize and POST and GET files in DJANGO? [on hold]
i am having trouble seeking about the logic and how to implement a serializer and a view for the Files. as the Files are going to be represented in an API so the pdf files must go through some sort of changing like we do in the images and change them to string64! i searched alot and could run to any thing helpful so can someone guide a fellow lost programmer? -
Django - How to assign a instance to a foreign key attribute
I'm having a problem to assign an foreign key attribute to a new object. When I try to make that I get this error Cannot assign "(< ConceptType: Producto >,)": "Receipt.concept" must be a "ConceptType" instance. Well, this is the code in the view if form.is_valid(): receipt = form.save(commit=False) receipt.concept = ConceptType.objects.get(id=1), this is for create a receipt using django-afip (https://gitlab.com/WhyNotHugo/django-afip) Thanks -
Django display table in templates
I am using Django 2.0.1, and I have the following code: Models.py: class Category(models.Model): category_name = models.CharField(max_length=50) class CategoryItems(models.Model): category_name = = models.ForeignKey(Categories, related_name='categoriesfk', on_delete=models.PROTECT) item_name = models.CharField(max_length=50) item_description = models.CharField(max_length=100) Thereafter my views.py: def data(request): categories_query = Categories.objects.all() category_items_query = CategoriesItems.objects.all() return render_to_response("data.html", {'categories_query': categories_query,'category_items_query': category_items_query} In the template I'm trying to display all items for each category, for example, suppose there are 4 categorizes, e.g. Bicycle, then it display all items belonging to that category only. For example, as follows: Category 1: Category_Item 1, Category_Item 2, Category_Item 3, and so on ... Category 2: Category_Item 1, Category_Item 2, Category_Item 3, and so on ... I have tried to write so many different for-loops, but they just display all items, I need it to show items only for that category, then for loop to next category and show items for that. Please may I kindly ask for some help? -
How to use a field of subquery in Django for joins?
SELECT CSR1.ConsumerProductID, CSRF1.Rating, CSRF1.CreatedDate FROM (SELECT CP.ConsumerProductID, COUNT(CSRF.Rating) FROM consumer_servicerequest_feedback CSRF INNER JOIN consumer_servicerequest CSR ON CSRF.ConsumerServiceRequestID=CSR.ConsumerServiceRequestID INNER JOIN consumer_product CP ON CP.ConsumerProductID=CSR.ConsumerProductID WHERE CSRF.Rating IS NOT NULL AND CSRF.CreatedDate GROUP BY(CSR.ConsumerProductID) HAVING(COUNT(CP.ConsumerProductID)>1)) AS T INNER JOIN consumer_servicerequest CSR1 ON T.ConsumerProductID=CSR1.ConsumerProductID INNER JOIN consumer_servicerequest_feedback CSRF1 ON CSRF1.ConsumerServiceRequestID=CSR1.ConsumerServiceRequestID ORDER BY T.ConsumerProductID, CSRF1.CreatedDate; I have to perform a query something like above in Django. innerq = ConsumerServicerequestFeedback.objects.values_list('csrfconsumerservicerequestid__csrconsumerproductid').exclude( csrfcreateddate__isnull=True).exclude(csrfrating__isnull=True).order_by( 'csrfconsumerservicerequestid__csrconsumerproductid').annotate( count_status=Count('csrfconsumerservicerequestid__csrconsumerproductid')).filter( count_status__gt=1) res_list = [x[0] for x in innerq.values_list('csrfconsumerservicerequestid__csrconsumerproductid')] q = ConsumerServicerequestFeedback.objects.values_list('csrfconsumerservicerequestid__csrconsumerproductid', 'csrfrating', 'csrfcreateddate').filter(status).filter( csrfconsumerservicerequestid__csrconsumerproductid__in=(res_list)).exclude(csrfcreateddate__isnull=True).exclude( csrfrating__isnull=True) I am doing something like this. Now I need to use the consumerproductID of the new table(innerq) as I did in SQL in my q query(wanted to use as join), How can I do that? -
Django : Unable to run server
I am new to Django and this is the first project Im working on. I have an error while executing the runserver command. Im working with Python 3.6.4. I havent found a solution in previous posts which were already very few. This is the error I get : Unhandled exception in thread started by <function check_errors. <locals>.wrapper at 0x0000022D586C2C80> Traceback (most recent call last): File "C:\Users\Ines\Anaconda3\envs\DjangoApps\lib\site- packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\Ines\Anaconda3\envs\DjangoApps\lib\site- packages\django\core\management\commands\runserver.py", line 151, in inner_run ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) File "C:\Users\Ines\Anaconda3\envs\DjangoApps\lib\site- packages\django\core\servers\basehttp.py", line 164, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\Users\Ines\Anaconda3\envs\DjangoApps\lib\site- packages\django\core\servers\basehttp.py", line 74, in __init__ super(WSGIServer, self).__init__(*args, **kwargs) File "C:\Users\Ines\Anaconda3\envs\DjangoApps\lib\socketserver.py", line 453, in __init__ self.server_bind() File "C:\Users\Ines\Anaconda3\envs\DjangoApps\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "C:\Users\Ines\Anaconda3\envs\DjangoApps\lib\http\server.py", line 138, in server_bind self.server_name = socket.getfqdn(host) File "C:\Users\Ines\Anaconda3\envs\DjangoApps\lib\socket.py", line 673, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe8 in position 2: invalid continuation byte PS : Please dont ask me to uninstall all and reinstall because I did it several times in vain. -
My django app on heroku is running but logs says it is crashed
I have a django app running on heroku. It is online, and I can access it and it is working on http://demo.dagenssalg.dk But I can't submit changes to it, and in the log it says it is chrashed. Feb 02 07:17:17 dagenssalg app/web.1: ImportError: bad magic number in 'form.admin': b'\x03\xf3\r\n' Feb 02 07:17:17 dagenssalg app/web.1: [2018-02-02 15:17:17 +0000] [9] [INFO] Worker exiting (pid: 9) Feb 02 07:17:17 dagenssalg app/web.1: [2018-02-02 15:17:17 +0000] [8] [INFO] Worker exiting (pid: 8) Feb 02 07:17:17 dagenssalg app/web.1: [2018-02-02 15:17:17 +0000] [4] [INFO] Shutting down: Master Feb 02 07:17:17 dagenssalg app/web.1: [2018-02-02 15:17:17 +0000] [4] [INFO] Reason: Worker failed to boot. Feb 02 07:17:17 dagenssalg heroku/web.1: Process exited with status 3 Feb 02 07:17:18 dagenssalg heroku/web.1: State changed from up to crashed What am I missing? Any help is most appreciated. Best regards Kresten -
Django : changing a specific form in modelformset
Here is the riddle. This is a simplified version of the problem I am dealing with, just so we can capture the core problem. So, for the sake of simplicity and relevance, not all fields and relationships are shown here. So, I have a modelformset and I would like to access each individual form to change the field based on the queryset. class PlayerType(models.Model): type = models.CharField(max_length=30, choices = PLAYER_TYPES) class Player(models.Model): name = models.CharField(max_length=30, blank=False, null=False) player_type = models.ForeignKey(PlayerType, related_name ='players') contract_price = models.DecimalField(max_digits = 10, decimal_places = 2, blank = False, null = False) price_unit_of_measurement = models.CharField(max_length=20, choices=STANDARD_UOM) Forms.py class PlayerForm(ModelForm): class Meta: fields = ['name','price_unit_of_measurement'] views.py PlayerFormSet = modelformset_factory(Player, form = PlayerForm, extra = 5) Now, say I want to display a different unit of measurement depending on which player I am showing. For instance, player 1's contract may be based on lump sump or amount per game, and another player's contract may be based on number of minutes played, price per month, etc. depending on the player type. In essence, I would like to know how to access each form in a modelformset and change the unit of measurement for that form alone, from the default … -
Django model filefield clear checkbox function is not working with using clean method of field
Clear checkbox for filefield like (image) is not working when i am using the clean function for the field clean function: def clean_image(self): #file = self.cleaned_data['image'] file = self.cleaned_data['image'] if file: if not os.path.splitext(file.name)[1] in [".jpg", ".png"]: raise forms.ValidationError( _("Doesn't have proper extension")) return file But if i remove the clean function the checkbox clear functionality is working fine, is there any conflict in using these two methods -
NOT NULL constraint failed: courses_course.owner_id
I'm creating a school, kinda, and I get NOT NULL constraint failed: courses_course.owner_id whenever I try to create a course via the URL http://127.0.0.1:8000/course/create/. Here are my files: models.py from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from .fields import OrderField class Subject(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) class Meta: ordering = ('title',) def __str__(self): return self.title class Course(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='courses_created') subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='courses') title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) overview = models.TextField() created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created',) def __str__(self): return self.title class Module(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='modules') title = models.CharField(max_length=200) description = models.TextField(blank=True) order = OrderField(blank=True, for_fields=['course']) class Meta: ordering = ['order'] def __str__(self): return '{}. {}'.format(self.order, self.title) class Content(models.Model): module = models.ForeignKey(Module, on_delete=models.CASCADE, related_name='contents') content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to={ 'model__in':('text', 'video', 'image', 'file') }) object_id = models.PositiveIntegerField() item = GenericForeignKey('content_type', 'object_id') order = OrderField(blank=True, for_fields=['module']) class Meta: ordering = ['order'] class ItemBase(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)s_related') title = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: abstract = True def __str__(self): return self.title class Text(ItemBase): content = models.TextField() class File(ItemBase): file = models.FileField(upload_to='files') class Image(ItemBase): file … -
Always image cannot be sent normally
Always image cannot be sent normally. I wrote in views.py def photo(request): d = { 'photos': Post.objects.all(), } return render(request, 'registration/accounts/profile.html', d) def upload_save(request): form = UserImageForm(request.POST, request.FILES) if request.method == "POST" and form.is_valid(): data = form.save(commit=False) data.user = request.user data.save() return render(request, 'registration/photo.html') else: return render(request, 'registration/profile.html') in profile.html <main> <div> <img class="absolute-fill"> <div class="container" id="photoform"> <form action="/accounts/upload_save/" method="POST" enctype="multipart/form-data" role="form"> {% csrf_token %} <div class="input-group"> <label> <input id="file1" type="file" name="image1" accept="image/*" style="display: none"> </label> <input type="text" class="form-control" readonly=""> </div> <div class="input-group"> <label> <input id="file2" type="file" name="image2" accept="image/*" style="display: none"> </label> <input type="text" class="form-control" readonly=""> </div> <div class="input-group"> <label> <input id="file3" type="file" name="image3" accept="image/*" style="display: none"> </label> <input type="text" class="form-control" readonly=""> </div> <div class="form-group"> <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control"> </div> <input id="send" type="submit" value="SEND" class="form-control"> </form> </div> </div> </div> </main> In my system,I can send 3 images at most each one time, so there are 3 blocks.Now always program goes into else statement in upload_save method, I really cannot understand why always form.is_valid() is valid.When I send only 1 image, same thing happens.So the number of image does not cause the error.How should I fix ?What is wrong in my code? -
Django get_or_create race condition when creating related objects
I have an ExtendedUser model like this, that just points to Django's User model: class ExtendedUser(models.Model): user = models.OneToOneField(User) When a request comes in, I want to get or create an User and its related ExtendedUser if the user that I'm looking for doesn't exist. I have this code : def get_or_create_user(username): with transaction.atomic(): user, created = User.objects.get_or_create( username=username, defaults={ 'first_name': "BLABLA", }, ) if created: extended_user = ExtendedUser() extended_user.user = user extended_user.save() return user I wrap it inside a transaction, to be sure I don't create an User but not its associated ExtendedUser. But, when two requests come in simultaneously that will create the same user, this fails from time to time with an IntegrityError, for both requests. So I end up with no user being created.. IntegrityError: (1062, "Duplicate entry 'BLABLABLA' for key 'username'") Note that I use MySQL, but I force READ COMMITTED isolation level. What do I do wrong ? How should I handle this ? The models need to stay as they are. -
Django 2.0 FormView for searching
I am using Django for few weeks, so I am still bit new in this. I want a page where I will have searching form and table with results. So each time I click search it will stay on same page and results will changed. I did read a lot of threads here about that, but some of them are old. So I did get quite confuse because find a lot of ways how to do that. I did find some solution but want to be sure that is it in "django" way. first target is to have page with searching for only. So after click search I will get search text under form, which will keep text. urls.py: from django.urls import path from . import views app_name = 'pocitadla' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('pokus', views.Pokus.as_view(), name='pokus'), ] forms.py: class PokusForm(forms.Form): name = forms.CharField(label='text to search', initial='what you want') processing with GET template: pocitadla/pokus.html {% extends "hlavna/header.html" %} {% block content %} <h2>testing</h2> <div> <form action="" method="get"> {{ form.as_p }} <button class="btn btn-success" type="submit">search</button> </form> </div> <h3>you did search for this</h3> <p>{{ pokus_pokus }}</p> {% endblock %} VIEW: class Pokus(FormView): template_name = 'pocitadla/pokus.html' search = None def get(self, … -
Django: get all objects among the foreignkey and inheritance related models?
Belows are my model design: class Exchange(BaseModel): name = models.CharField(max_length=20) class Symbol(BaseModel): exchange = models.ForeignKey(Exchange) name = models.CharField(max_length=20) class ASymbol(Symbol): a_property = models.CharField(max_length=20) class BSymbol(Symbol): b_property = models.CharField(max_length=20) my_exchange = Exchange.objects.first() How can I get all BSymbol objects using my_exchange variable and related manager? Something like my_exchange.symbol_set.filter(~~~)? Notice : Symbol is not an abstract class. Thanks