Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django render in html Aggregation
I'm trying to output a conditional sum / aggregation via django in html. Though not sure what to put in my template? see below : in views.py: (part of my code ) total_paid = CF.objects.filter(type='Payment').aggregate(Sum('amount') return render(request, 'budget/budget_detail.html', {'paid': total_paid }) in budget/budget.html : {{ paid }} output is as follows in my browser : {'amount__sum': Decimal('-1500')} can anyone help me? thanks !! -
How to print a message in the terminal when debugging the Django app?
In the Django backend I have the following lines of code: csvData = request.GET.get('csvData') print(csvData) X = pd.DataFrame(csvData) It throws the following error message that I see in the terminal: X = pd.DataFrame(csvData) File "/Users/terr/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py", line 422, in init raise ValueError('DataFrame constructor not properly called!') However, the output of print(csvData) does not appear in the terminal. How can I print it out there? -
Django - Transform an address in latitude and longitude through Google API and save the object
I have an Address model where I save the address in different fields: address_1 address_2 zip_code city country latitude longitude First, I ask the user to fill a form with the address (without latitude and longitude, by default they are set to "0"). Then I try to convert this address into latitude and longitude using Google API before saving the object. Here is my code. I don't know if it's the right way to do it but right now it doesn't work and I get the error 'float' object has no attribute 'save' Any idea how to solve this issue? Many thanks in advance.(I'm new to programming and new to Django) from django.db import models from django.contrib.auth.models import User from users.models import Profile from django_countries.fields import CountryField import requests class Address(models.Model): profile = models.OneToOneField(Profile, on_delete=models.CASCADE) address_1 = models.CharField(max_length=255, blank=True) address_2 = models.CharField(max_length=255, blank=True) zip_code = models.IntegerField(blank=True, null=True) city = models.CharField(max_length=255, blank=True) country = CountryField(blank=True) latitude = models.DecimalField( max_digits=9, decimal_places=6, blank=True, default='0') longitude = models.DecimalField( max_digits=9, decimal_places=6, blank=True, default='0') def __str__(self): return f'Adresse de {self.profile.user.username}' class Meta: verbose_name_plural = "addresses" def save(self, **kwargs): super().save(**kwargs) address = " ".join( [self.address_1, self.address_2, str(self.zip_code), self.city]) api_key = "PROJECT_API_KEY" api_response = requests.get( 'https://maps.googleapis.com/maps/api/geocode/json?address={0}&key={1}'.format(address, api_key)) api_response_dict … -
Calling a view from one app into another app
I'm not sure how to do this. I have two apps home and post. I want to call a view from my posts app into my home app. Reason being, I want to display the objects queried by the posts views on the home.html. I don't want to have to go to another url. Essentially that's what I'm doing currently. I would have to go to /posts/ to see the objects. url(r'^$', views.posts_list, name='list'). So my understanding is, if I eliminate the url and call the views inside the home views.py everything would be in one central area. I would see the list of posts and all the home page html. Are there any drawbacks to implementing it this way as well? This is my home/views.py from django.shortcuts import render from posts import views from posts.models import Post # TODO: Found a hacky way to display all posts on home page def home(request): # TODO: If the user is not authenticated then don't show the home page, # but instead show soe other page reporting the error. (Maybe just the login page). return render(request, 'home.html') #Do I make the call here as well? This method is the same in my … -
How to let static CSS files access other files such as .eot, .ttf, .woff, etc... on Django
When I try to access styles.css, Django loads styles.css but not the files that it loads for itself. {% load static %} <link rel="stylesheet" href="{% static 'frontpage/css/style.css' %}"> here is the part of styles.css that I suspect is causing the problem src: url("../fonts/icomoon/icomoon.eot?srf3rx"); src: url("../fonts/icomoon/icomoon.eot?srf3rx#iefix") format("embedded-opentype"), url("../fonts/icomoon/icomoon.ttf?srf3rx") format("truetype"), url("../fonts/icomoon/icomoon.woff?srf3rx") format("woff"), url("../fonts/icomoon/icomoon.svg?srf3rx#icomoon") format("svg"); It seems that the css file is unable to acess the .eot files, but I have no way of knowing because django is showing everything as running smoothly. -
pytest raises TypeError
class Book(Entity): authors = ManyToManyField(Author) name = CharField() # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from .models import * from pytest import mark @mark.django_db def test_book(): b1 = Book.objects.create(name='Book Name') a1 = Author.objects.create(first_name='John', last_name='Stones') b1.authors.add(a1) b1.authors.all() b1.authors.all() raises TypeError def get_queryset(self): try: return self.instance._prefetched_objects_cache[self.prefetch_cache_name] TypeError: 'NoneType' object has no attribute '__getitem__' -
Receiving aliased fields based on request to wagtail REST API
Suppose I have a model with the following fields: class SomePage(Page): other_fields = ... field_en = models.CharField(max_length=280, blank=False, null=False) field_de = models.CharField(max_length=280, blank=False, null=False) field_zh = models.CharField(max_length=280, blank=False, null=False) Where every _lang is the field translated into a certain language. (Their number is known in advance since they're not likely to change in the future) When I use Wagtail's REST API, the responses come including all fields, and I have to start excluding fields manually: { <other fields>: ... "field_en": ... "field_de": ... "field_zh": ... } So, this can be solved by excluding the fields I don't want, however I would like to, ideally, either request them with a ?lang=en parameter, and receive cleaner replies such as: { <other fields>: ... "field": ... // This is actually field_en! } So that my frontend or any other client doesn't have to implement the field_<lang> logic. As a sidenote - the built-in field title in page might also get translated, which means there'll be title, title_de and title_zh for example, which might require some extra logic. I dug around in BaseEndpoint and have been able to create a class to generate _lang-specific endpoints when subclassed, but it would return field_<lang> rather than … -
Django Rest Framework return a JSON file
Using Django and Django REST Framework, I am trying to write a GET request which when called will return a JSON file located on the server. What is the best way to accomplish this? class MyView(APIView): def get(self, request): ... # I get a filepath to 'somefile.json' my_filepath = "/Users/me/Desktop/somefile.json" ... # What do I do in order to return 'somefile.json'? return Response(somefile.json) -
Pass a Numpy Array Image to ImageField()
So i got here is a code that detect if the face in the image is in my encodings. So my problem is what if the face is not in the Encodings can i pass a string variable to a OneToOneField() or can i set a default value to it? and also how can i link the image it is in a Numpy Array format yeah i already think about just saving it inside my MEDIA folder but how can i link it to ImageField()? Here's my code: models.py def log_image_path(instance, filename): extention = filename.split('.')[-1] return os.path.join(settings.LOGS_ROOT, f"{uuid.uuid4()}.{extention}") class MonitorLog(models.Model): student_info = models.OneToOneField(Student, on_delete=models.CASCADE) log_image = models.ImageField(upload_to=log_image_path) log_time = models.DateTimeField(default=timezone.now) tasks.py def identify_face(arr): master_encodings = pickle.loads(open(settings.TRAINING_FILE_DIR, 'rb').read()) arr = np.asarray(arr) rgb = arr[:,:,::-1] faces = face_recognition.face_locations(rgb, model='hog') enc = face_recognition.face_encodings(rgb, faces) main_enc = [encs for encs in enc] for encoding in main_enc: matches = face_recognition.compare_faces(master_encodings['encodings'], encoding) name = 'Unknown' if True in matches: encIds = [encIndex for (encIndex, value) in enumerate(matches) if value] counts = {} for num in encIds: name = master_encodings['student_number'][num] counts[name] = counts.get(name, 0) + 1 name = max(counts, key=counts.get) if name != "Unknown": stud_ins = models.Student.objects.get(student_number=name) -
Using finditer() with string decoded from request.FILES
I'm trying to get my head around this problem and have tried to find something on the internet, to no avail. I am uploading a file which I read from request.FILES and decode it to utf-8 which is saved in a variable. I then need regex to do it's thing with that string so I can iterate through the regex matches. The weird thing is that the regex returns nothing doing it this way, however, if I save the file to disk and open it the regex works. req_file = request.FILES['file'] log_string = req_file.read().decode('utf-8', 'replace') req_file.close() sect_re = re.compile( r'\*(?P<title>[^*]+)\*\s\*+\s{2,3}(?P<body>(?:(?!\*+\n).+\s+(?!\*+\n))+.+|)', re.M ) re_results = re.finditer(sect_re, log_string) # loop through the regex results re.search() with a different regex string will work. Just to make it clear, the Regex string above works perfectly fine and it is most definitely not the problem here. The problem is using re.finditer() on a string that was saved using request.FILES['file'].read().decode('utf-8', 'replace'). For example, the below would work perfectly fine: with open("file.txt") as f: for c in f.chunks(): log_string += c sect_re = re.compile( r'\*(?P<title>[^*]+)\*\s\*+\s{2,3}(?P<body>(?:(?!\*+\n).+\s+(?!\*+\n))+.+|)', re.M ) re_results = re.finditer(sect_re, log_string) # loop through the regex results Is it to do with it being read from memory? … -
How to add messages to a queue in different function and read it
I was making a app in which i had to implement socket. So insted to sending socket message from different functions I thought of add all messages to one queue and read it infinitly and send message from there. But my problem here is when I add message in queue same is not received in reader. Please any help or better idea for handling messages in welcomed. My code is like this :- from queue import Queue from bot.core.utils import singleton @singleton class SocketFeedService: feed_queue = Queue() def add_message(self, username, message): message_dict = dict(user=username, message=message) print("Adding message", message_dict) SocketFeedService().feed_queue.put(message_dict) def reader(self): while True: message = SocketFeedService().feed_queue.get(block=False) print("feed message", message) SocketFeedService().feed_queue.task_done() Singleton is implemented as follows :- def singleton(class_): instances = {} def get_instance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return get_instance And adding message like this :- SocketFeedService().add_message(self.bot.user_instance.username, log_string) I tried reading in different thread as well but it did'nt work Thanks for any help. :) -
Django Rest Framework: JWT Authorization failed
I have an application wrote with Django REST Framework (DRF). Also, there are such registered endpoints: from refreshtoken.views import delegate_jwt_token from rest_framework_jwt.views import obtain_jwt_token urlpatterns = [ path('api-token-auth/', obtain_jwt_token), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path(r'refresh-token', delegate_jwt_token, name='refresh-token'), ] Also, there are some endpoints, which requires authorization. So, I'm trying to extract my token using curl client: curl -X POST -H "Content-Type: application/json" http://127.0.0.1:8000/api-token-auth/ -d '{"username": "test", "password": "testpassword"}' It returns something like this: {"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYTdlMmIyMjItZTZkNy00NjhiLTkxNzYtOTE2YzAwZWRhY2E2IiwidXNlcm5hbWUiOiJ0ZXN0IiwiZXhwIjoxNTUwNTEwNDAwLCJlbWFpbCI6InRlc3RAZHhhbXBsZS5jb20iLCJpc19zdGFmZiI6ZmFsc2UsImdyb3VwcyI6W10sInN1YnNjcmliZWQiOmZhbHNlLCJ0ZWxlZ3JhbV9zdWJzY3JpYmVkIjpmYWxzZX0.OExR9TlO3GUisYAu_D86CJ6hgF1EcofpQA0MZ1ENT2c","refresh_token":"1ab03e609d7a7ae05ce104c73858a346a0438e72"} Then, using this token I want to login, using token: curl -X POST -H "Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYTdlMmIyMjItZTZkNy00NjhiLTkxNzYtOTE2YzAwZWRhY2E2IiwidXNlcm5hbWUiOiJ0ZXN0IiwiZXhwIjoxNTUwNTEwNDAwLCJlbWFpbCI6InRlc3RAZHhhbXBsZS5jb20iLCJpc19zdGFmZiI6ZmFsc2UsImdyb3VwcyI6W10sInN1YnNjcmliZWQiOmZhbHNlLCJ0ZWxlZ3JhbV9zdWJzY3JpYmVkIjpmYWxzZX0.OExR9TlO3GUisYAu_D86CJ6hgF1EcofpQA0MZ1ENT2c" -H "Content-Type: application/json" http://127.0.0.1:8000/api-auth/login/ -d '{"username": "test", "password": "testpassword"}' It returns 403 (Forbidden)CSRF verification failed. Request aborted. Why I'm doing wrong? One interesting point here: Each request for the token returns a new token for the same user:password pair (is it expected or my token expires too fast)? -
Using values() on a filtered Django QuerySet with ManyToMany fields
I have the following models in a Django project: class Category(models.Model): title = models.CharField(max_length=255) def __str__(self): return '{} - {}'.format(self.pk, self.title) class Item(models.Model): title = models.CharField(max_length=255) categories = models.ManyToManyField(Category) def __str__(self): return '{} - {}'.format(self.pk, self.title) I created an item, and associated it with two categories: >>> item1 = Item.objects.get(pk=1) >>> item1.categories.all() <QuerySet [<Category: 1 - C1>, <Category: 4 - C4>]> I can also use filter() and get expected results: >>> Item.objects.filter(categories__title='C1') <QuerySet [<Item: 1 - Item1>]> However, when I use values() on that same queryset, only the relationships that have been filtered will be returned: >>> Item.objects.filter(categories__title='C1').values('categories__title') <QuerySet [{'categories__title': 'C1'}]> compared to: >>> Item.objects.all().values('categories__title') <QuerySet [{'categories__title': 'C1'}, {'categories__title': 'C4'}]> What am I missing? -
Django Rest Framework Views and regular django views for frontend
I'm developing an application with backend which will be also be used by mobile applications. Therefore I chose to create REST API using DRF. Now I'm deciding what to do with my frontend. I don't really want to use any javascript frameworks and would like to stick with Django. I see that I can render HTML templates and forms using DRF (https://www.django-rest-framework.org/topics/html-and-forms/). However I would like to stick with regular Django function based views and develop the application and simply expose REST API with DRF that can be used by mobile developers. Would this be a good programming practice ? If not what are the drawbacks to such approach. -
Trying to Deploy django + wsgi + apache + windows
I'm trying to deploy a django server but I even reinstall all but I got the same error in apache and I do not know how to make it Works, I hope you can help me because it makes me crazy. Wsgi is installed correctly, it works fine with runserver command but not with apache. httpd.conf LoadFile "c:/users/srvpc/appdata/local/programs/python/python35/python35.dll" LoadModule wsgi_module "c:/users/srvpc/appdata/local/programs/python/python35/lib/site-packages/mod_wsgi/server/mod_wsgi.cp35-win_amd64.pyd" WSGIPythonHome "c:/users/srvpc/appdata/local/programs/python/python35" WSGIScriptAlias / "C:\abaa\proyecto\proyecto\wsgi.py" WSGIPythonPath "C:\abaa\proyecto" <Directory "C:\abaa\proyecto"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "C:\abaa\proyecto\aplicacion\static" <Directory "C:\abaa\proyecto\aplicacion\static"> Require all granted </Directory> apache access log: 192.168.1.216 - - [18/Feb/2019:10:57:58 -0600] "GET / HTTP/1.1" 500 530 apache error log: AH00558: httpd.exe: Could not reliably determine the server's fully qualified domain name, using fe80::c109:4f13:c7f3:c19b. Set the 'ServerName' directive globally to suppress this message [Mon Feb 18 10:57:53.985985 2019] [mpm_winnt:notice] [pid 1800:tid 540] AH00455: Apache/2.4.38 (Win64) mod_wsgi/4.5.24 Python/3.5 configured -- resuming normal operations [Mon Feb 18 10:57:53.985985 2019] [mpm_winnt:notice] [pid 1800:tid 540] AH00456: Apache Lounge VC15 Server built: Jan 18 2019 14:26:34 [Mon Feb 18 10:57:53.985985 2019] [core:notice] [pid 1800:tid 540] AH00094: Command line: 'C:\\Apache24\\bin\\httpd.exe -d C:/Apache24' [Mon Feb 18 10:57:53.985985 2019] [mpm_winnt:notice] [pid 1800:tid 540] AH00418: Parent: Created child process 1824 AH00558: httpd.exe: Could not reliably determine the … -
Using the slug rather than ID in django rest framework json api
My ember app expects the JSON response to contain a primary key result for the model ID. Rather than use integer IDs, I want to use slugs. I know that in the standard django framework you can do something like this: from rest_framework import serializers from .models import Page class PageSerializer(serializers.ModelSerializer): id = serializers.CharField(source='slug') class Meta: model = Page fields = ('name','id',...etc ) However, this doesn't work when using the json api - in my response I still have something like "data": [{ "type": "pages", "id": "2", "attributes": { "name": "Some page name", }] When I want the "id" field to be something like "some-page-name" (the slug) Is this not possible with the json api. For clarity the equivalent json api import above would be from rest_framework_json_api import serializers Many thanks -
Django error connecting to MySQL - handshake
I am getting an error: django.db.utils.OperationalError: (2013, "Lost connection to MySQL server at 'handshake: reading inital communication packet', system error: 0") I can connect to the database fine through python outside of django using pyodbc, but when I try to connect through django, it errors out. I originally didn't have the max timeout setting. I added this to see if it helped. My database is an ip connection, 192.168.2.10, port 49170. With pyodbc, I can connect with: import pyodbc server = '192.168.2.10\EDSQL' database = 'spamfilter' # 'acme' username = 'sa' password = 'xxxxx' cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=192.168.2.10,49170;DATABASE=spamfilter;UID=sa;PWD=3dd!3Sn!p3s') cursor = cnxn.cursor() My django settings.py are: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'EDSQL/spamfilter', 'USER': 'sa', 'PASSWORD': 'xxxxxxx', 'HOST': '192.168.2.10', # Or an IP Address that your DB is hosted on 'PORT': '49170', 'CONN_MAX_AGE': 60, } } The error occurs when performing the initial python manage.py migrate -
Migrate Django model to Postgresql schema
I would like to create a new table in a specific Postgresql schema (i.e. "schema1) from a Django migration. Despite following approach 1 from this blog or this post, the migration sends the table to the default schema "public" instead of "schema1". In settings.py, I have: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS': { 'options': '-c search_path=django,public' }, 'NAME': 'myDB', 'USER': 'username', 'PASSWORD': '***', 'HOST': 'my.host.address', 'PORT': '1234', }, 'schema1': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS': { 'options': '-c search_path=schema1,public' }, 'NAME': 'myDB', 'USER': 'username', 'PASSWORD': '***', 'HOST': 'my.host.address', 'PORT': '1234', } } #Path to DBrouter to handle PG schemas https://stackoverflow.com/a/51007441/3976696 DATABASE_ROUTERS = ('djangogirls.dbrouters.MyDBRouter',) In djangogirls/dbrouters.py, I have: from legacydbapp.models import MyUser # Include here any class (i.e. table) that belongs to the schema "schema1" ROUTED_MODELS_SCHEMA1 = [MyUser] class MyDBRouter(object): """ A router to place DB queries into correct schema depending on considered tables. """ def db_for_read(self, model, **hints): if model in ROUTED_MODELS_SCHEMA1 : return 'schema1' return None def db_for_write(self, model, **hints): if model in ROUTED_MODELS_SCHEMA1 : return 'schema1' return None And the model class I'm trying to migrate, in models.py: class MyUser(models.Model): first_name = models.CharField(max_length=30, default='',null=True, blank=True) last_name = models.CharField(max_length=30, default='', null=True, blank=True) profession = models.CharField(max_length=32,default='', null=True, blank=True) def __str__(self): … -
Django does not honor ON DELETE CASCADE
This is my model: class Subscriber(models.Model): ... tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, null=True) ... This is the generated SQL, according to sqlmigrate (and to manual inspection of the database): ALTER TABLE `myapp_subscriber` ADD CONSTRAINT `myapp_subscriber_tenant_id_b52815ee_fk_myapp_tenant_id` FOREIGN KEY (`tenant_id`) REFERENCES `myapp_tenant` (`id`); I was expecting something like this: CREATE TABLE child ( id INT, parent_id INT, INDEX par_ind (parent_id), FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE ) ENGINE=INNODB; With the ON DELETE CASCADE. MySql (MariaDB actually) complains when I delete: SQL Error (1451): Cannot delete or update a parent row: a foreign key constraint fails Which makes sense since there is no ON DELETE CASCADE clause. Why is Django 2.1.5 not honoring the ON DELETE CASCADE clause? -
How to POST/PATCH user model with django restful api
I have a django oscar shop and expanded my user model with a treatment field: class User(AbstractUser): treatment = models.CharField(max_length=128) Now I want to expand the django oscar api in order to post or patch a user (I want to change "treatment"). If I go to http://localhost:8000/api/users/ and try to post a new one, I just get this error: TypeError at /api/users/ int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute' Has anyone an idea how to handle this? views.py: class UserList(basic.UserList): queryset = User.objects.all() serializer_class = CreateUserSerializer def post(self, request, format=None): v_ser = self.serializer_class( data=request.data, context={'request': request}) if v_ser.is_valid(): ser = self.serializer_class( User, context={'request': request}) return Response(ser.data) return Response(v_ser.errors, status=status.HTTP_406_NOT_ACCEPTABLE) serializers.py: class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email', 'treatment') email = serializers.EmailField() treatment = serializers.CharField(max_length=128, required=True) def validate(self, attrs): #oscar expects this always to be uppercase. attrs['treatment'] = attrs['treatment'].upper() request = self.context.get('request') return attrs def create(self, validated_data): return User.objects.create(**validated_data) -
Limit fields when marking subsequent options (in one form). Django
I have a very simple form and I would like to restrict it when I select the first field. For example, after selecting a product, the t-shirt is displayed in the 'add_on' field (red, green, gray) and after selecting the field the shoes are displayed (leather, suede). class ProductForm(forms.ModelForm): class Meta: model = OrderingMassage fields = ('product', 'add_on') How can this be done in the simplest possible way? any help will be appreciated. -
How to create a factory for model with more than one Genereic Foreign Key?
I am trying to setup a factory for my model that has more than 1 generic foreign key. I can't get to work it for more than one GFK. class ContactFactory(factory.django.DjangoModelFactory): class Meta: abstract = True # model = ContactData exclude = ['content_object'] object_id = factory.SelfAttribute('content_object.id') content_type = factory.LazyAttribute( lambda o: ContentType.objects.get_for_model(o.content_object)) email = factory.Faker('email') fax_number = factory.Faker('phone_number') phone_number = factory.Faker('phone_number') mobile_number = factory.Faker('phone_number') external_profiles = factory.Dict({ 'xing': factory.Faker('uri'), 'website': factory.Faker('uri'), 'facebook': factory.Faker('uri'), 'linkedin': factory.Faker('uri') }) class CandidateFactory(factory.django.DjangoModelFactory): class Meta: model = Candidate # id = uuid.uuid4() object_id = factory.Sequence(int) created_at = FuzzyDateTime(datetime.datetime(2008, 1, 1, tzinfo=pytz.UTC)) updated_at = FuzzyDateTime(datetime.datetime(2008, 1, 1, tzinfo=pytz.UTC)) class CandidateContactFactory(factory.django.DjangoModelFactory): content_object = factory.SubFactory(CandidateFactory) class Meta: model = ContactData I tried to create an Contact Factory which can be done with b = CandidateContactFactory() But i have a Generic Foreign Key to another address model. How can I do so with factory boy? -
How to filter based on previous queryset results Django
At the moment I have 2 separate querysets rendering independently of each other on the same page. Q1=users Q2=f Q1 returns all users within a user-posted radius (request.POST). Q2 returns a django_filters.FilterSet depending on the filter chosen (hair color, age, etc) (request.GET) Q2 should only filter the results of Q1. I would like to keep it all on the same page, as opposed to redirect to different urls. If someone could explain the simplest way of doing this, I would be most grateful. views.py class ConnectView(View): template_name = 'connect/home.html' def get(self, request, *args, **kwargs): f = ProfileFilter(request.GET, queryset=Profile.objects.exclude(user=request.user)) context = { 'users': User.objects.exclude(username=request.user), 'filter': f, } return render(request, self.template_name, context) def post(self, request, *args, **kwargs): if 'radius' in request.POST: radius_km = request.POST.get('radius', 0) queryset = User.objects.annotate( radius_sqr=pow(models.F('loc__latitude') - request.user.loc.latitude, 2) + pow(models.F('loc__longitude') - request.user.loc.longitude, 2) ).filter( radius_sqr__lte=pow(int(radius_km) / 9, 2) ).exclude(username=request.user) context = {'users': queryset} return render(request, 'connect/home.html', context) else: return render(request, 'connect/home.html', context) filters.py class ProfileFilter(django_filters.FilterSet): class Meta: model = Profile fields = { 'age': ['exact'], 'gender': ['exact'], } connecthome.html <form method="POST"> {% csrf_token %} <h4>Enter Distance.</h4> <input type="number" name="radius"> <button type="submit">Search.</button> </form> <h4>Filter.</h4> <form method="GET" name='filter'> {{ filter.form|crispy }} <button type="submit">Search.</button> </form> {% if filter %} {% for … -
Django remove label at all
I have a model form. I have a field that begins hidden when the page loads until the user does something (JavaScript). The problem is that this field is still showing its label. class MyModelForm(forms.ModelForm): def __init__(self, filter_on, *args, **kwargs): super(MyModelForm, self).__init__(*args, **kwargs) self.fields['my_field'] = forms.ModelChoiceField( queryset=AnyClass.objects.filter(any_attr=filter_on), empty_label=None, required=True, to_field_name='fieldname', label='', widget=forms.Select(attrs={'class': 'form-control', 'hidden': 'true'}) ) class Meta: model = Plan fields = ['my_field'] I've tried label=None and it shows the default variable name as label. Also tried label='' but it is still showing a ":". How can I fix this? -
Do I install Django first?
So I thought I would try out this Wagtail CMS and followed the documentation from: http://docs.wagtail.io/en/v2.4/getting_started/tutorial.html All was good until I get to step4: $ python manage.py migrate I get an error in my terminal: Traceback (most recent call last): File "manage.py", line 8, in from django.core.management import execute_from_command_line ImportError: No module named django.core.management I assume this part 'No module named django.core.management' is due to Django not being installed, I'm rather confused as I am a complete newbie to this, should the documentation not say install DJango first or am I reading this all wrong? Surely if you had to install Django first it would say so at the beginning of the tutorial no?