Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't create registration form with image uploading in Django application
I have a problem related to registrations form. I tried to implement One To One field, but it didn't bring any results. My problems: I can not add to the User model ImageField and some other fields(I'm not sure about it) and when I fill image field in the registration form I can not get the image back in Profile page. The only thing I want is to create registration form with some specific additional fields and image uploading. You can also suggest other ways of realizing this. Models.py from django.db import models from django import forms from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) picture = models.ImageField(upload_to='profile-photos') profile_sphere = models.CharField(null=True,max_length=1000,blank=True,verbose_name='Сфера деятельности', choices=(['it','Информационные технологии'],['wood','Деревообработка'])) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() forms.py from django import forms from .models import Profile from django.contrib.auth.forms import UserCreationForm , UserChangeForm from django.contrib.auth.models import User from django.core.validators import EmailValidator class SignUp(UserCreationForm): email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') class Meta: model = User fields = ('username','first_name','last_name', 'email','password1',) class NewForm(forms.ModelForm): class Meta: model = Profile fields = ('profile_sphere','bio','picture',) views.py (def register and def profile) def register(request): … -
Django Pillow error name has attr no defined, possible WSGI issue
I have no problems working with Pillow in my development environment - and have not had any issues with it either on a public server where I have implemented mod_wsgi. However, today, when attempting to upload an image in the admin, I get this error message File "/home/<username>/virtualenvs/<sampleenv>/lib/python3.6/site-packages/PIL/Image.py", line 585, in __del__ NameError: name 'hasattr' is not defined It must relate to mod_wsgi since this is the only difference between my development and production environment. Why this has suddenly happened is a mystery. This is my /etc/apache2/mods-available/wsgi.load file: LoadModule wsgi_module /home/<username>/virtualenvs/<sampleenv>/lib/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so WSGISocketPrefix /var/run/apache2/wsgi WSGIPythonHome /home/<username>/virtualenvs/<sampleenv> I have not attempted to copy the mod_wsgi module into the Apache installation - perhaps this is the problem but I'm not sure how to do this. I hope I've managed to explain the problem clearly - any help would be great! -
Django "AttributeError: 'function' object has no attribute 'as_view'"
when i use user_passes_test decorators an error display : "AttributeError: 'function' object has no attribute 'as_view'" this is my code : urls.py : url(r'^user/admin/$', UpdateAdminView.as_view(), name='admin'), views.py : @user_passes_test(lambda u: u.is_superuser) @method_decorator(login_required, name='dispatch') class UpdateAdminView(TemplateView): template_name = "admin.html" -
Can't access the value of the `to` form field
I'm creating a blog using Django and there's this feature I implemented that allows users to share posts via email. Here's the form from django import forms from .models import Post class EmailPostForm(forms.Form): name = forms.CharField(max_length=100, required=True, widget=forms.TextInput( attrs={'placeholder' : 'your name'} )) email = forms.EmailField(max_length=200, required=True, widget=forms.TextInput( attrs={'placeholder' : 'your email'} )) to = forms.EmailField(max_length=200, required=True, widget=forms.TextInput( attrs={'placeholder' : 'recipient\'s email'} )) comments = forms.CharField(max_length=500, required=False, widget=forms.Textarea( attrs={'rows' : 5, 'placeholder' : 'Tell recipient what you think about this post (optional)'} ), help_text='The maximum length of the text is 4000') Here's the view def post_share(request, post_id): # Retrieve the post by id post = get_object_or_404(Post, id=post_id, status='published') sent = False if request.method == 'POST': # Form was submitted form = EmailPostForm(request.POST) if form.is_valid(): # Form fields passed validation cd = form.cleaned_data post_url = request.build_absolute_uri(post.get_absolute_url()) presubject = '{} ({}) recommends you reading "{}"' subject = presubject.format(cd['name'], cd['email'], post.title) premessage = 'Read "{}" at {}\n\n{}\'s comments: {}' message = premessage.format(post.title, post_url, cd['name'], cd['comments']) send_mail(subject, message, 'admin@sayc.com', [cd['to']]) sent = True else: form = EmailPostForm() return render(request, 'post_share.html', {'post' : post, 'form' : form, 'sent' : sent}) Here's the url urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^(?P<post_id>\d+)/share/$', views.post_share, name='post_share'), ] And here's the … -
Can we fill the fields I don't need in Serializer fields?
I have a User Model, and it has many fields in it: class User(models.Model): openstackcloud_id = models.CharField(max_length=32, null=True) # username = models.CharField(max_length=16) password = models.CharField(max_length=40) # sha1加密 real_name = models.CharField(max_length=12, null=True,blank=True) phone = models.CharField( max_length=11) # 手机号码 email = models.EmailField(blank=True, null=True ) qq = models.CharField(max_length=10, null=True, blank=True) address = models.CharField(max_length=64, blank=True, null=True) # 地址 id_card = models.CharField(blank=True, null=True, max_length=18, validators=[RegexValidator(regex='^.{18}$', message='身份证长度必须为18', code='nomatch')]) id_card_img_front = models.CharField(max_length=256, blank=True, null=True) id_card_img_back = models.CharField(max_length=256, blank=True, null=True) nickname = models.CharField(max_length=16, blank=True, null=True) profile = models.CharField(max_length=256, blank=True, null=True, default='我爱旗云') # 个人简介 usertype = models.ForeignKey(to='UserType', default=1, blank=True) # 默认是:1.普通用户 user_c_type = models.CharField(max_length=4, null=True) # 用户类型(个人 or 企业) fixed_phone = models.CharField(max_length=16, null=True) # 固定电话 fax = models.CharField(max_length=16, null=True) # 传真 main_bussiness = models.CharField(max_length=16, null=True) # 主营业务 main_industry = models.CharField(max_length=16, null=True) # 所属行业 company_name = models.CharField(max_length=32, null=True) # 公司名称 company_address = models.CharField(max_length=32, null=True) # 公司地址 province = models.CharField(max_length=32, null=True, default="--省--") # 省市县 town = models.CharField(max_length=32, null=True, default="--市--") # 省市县 country_level = models.CharField(max_length=32, null=True, default="--县--") # 省市县 ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) # 更新时间 status = models.CharField(max_length=1, null=True, default=1) # 1.存活 2.禁用 3.注销 You see, there is many fields in User model. But I am using rest framework, like: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', … -
Unable in getting data from list containing many objects
I am trying request.data.get('student_name') but it says that list has no attribute get. I just want to get the name of all students before passing to the serializer. I am sending the POST request data in the form of [ {"student_name": "jack", "last_name": "cale", "fathers_name":"carlos"}, {"student_name": "alex", "last_name": "magasa", "fathers_name":"greg"}, {"student_name": "sia", "last_name": "gunns", "fathers_name":"brett"}, {"student_name": "jacob", "last_name": "woods", "fathers_name":"john"} ] my views.py @api_view(['POST']) def add_students(request): student_name = request.data.get('student_name') fathers_name = request.data.get('fathers_name') serializer = StudentsSerializer(data=request.data, many=True) if serializer.is_valid(): serializer.save() return Response("success") else: return Response(serializer.errors) my serializers.py class StudentsSerializer(serializers.ModelSerializer): class Meta: model = Students fields = ('student_name', 'last_name', 'fathers_name') my models.py class Students(models.Model): student_name = models.CharField(max_length=100, null=True) last_name = models.CharField(max_length=100, null=True) fathers_name = models.CharField(max_length=100, null=True) -
Timing issue with image upload on Heroku + Django Rest Framework + s3
ok this is a mix of architecture design and code question.. I've had this problem on a couple of applications and I'm not sure how to handle this. The problem is fairly basic, an app which allows users to attach files/images to an object. Let's say I have the following Django models: Document and Attachment. class Document(models.Model): body = models.TextField(blank=True, help_text='Plain text.') class Attachment(models.Model): document = models.ForeignKey(Document, on_delete=models.CASCADE, related_name='attachments') attachment = models.FileField(upload_to=get_attachment_path, max_length=255, null=False) filesize = models.IntegerField(default=0) filetype = models.CharField(blank=True, max_length=100) orientation = models.IntegerField(default=0) The get_attachment_path callable simply builds a path based on the document pk and the user. When a user creates a document, he can attach files to it. As it's a modern world, you want to be able to upload the files before creating the document, so I have a TempUpload object and a direct connection from the web application to S3 (using pre-signed URL). When the user clicks save on the document form, I get an array of all the TempUpload objects that I need to attach to the new document. Now here's the problem... within the heroku 30s timeout constraint, I need to: create the document (quite fast) iterate the array of TempUpload objects, and … -
HTML pages loading problems and buffer
Hi have a project that use Django/Python to create a web app, my problem is that on some page that rely heavely on Jquery Dialog and forms it takes up to 20 seconds to load the page. When the page load, it does like a buffer and for a few seconds display everything on the page on top of each other (like jquery tabs and dialog poping on top of the page) so i wanted to add a loading buffer and hide everything until the page is load. i just added divs in the body <div class="loader"></div> <div id="body" style="display:none;"> and this in the document.ready $('#body').show(); But my problem is that the page buffer for a few seconds, display nothing (not even the loader) then the loader pop for not even 3 seconds and the page end up fully loaded. What i don't understand is that if my page take so long to load why isn't the loading buffer image staying during the whole loading phase ? -
not able to host django app it on Heroku
So i created a new Django app with static files,its running perfectly in localhost,i saw Heroku is a good place to publish my app,but after following all the proceedures,i'm not able to get any output from it,it successfully deploys without any errors,but if i open the app it says Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. I'm not sure what to do at this point,the log says nothing any help would be appreciated -
Django force redirect to home page
this is easiest to explain with an example. I have an HTML button, when it is clicked it is supposed to change a status-field in the database. After the status-field is changed, the user is supposed to be redirected back to home. Below is the HTML-button that calls a Javascript function: {% for group in groups %} <button id="approve-btn" onclick="approvePendingGroup({{ group.pk }})">Approve</button> {% endfor %} Here is the Javascript-function: function approvePendingGroup(id) { window.location.href = "/result/approve/" + id; } The Javascript-function calls the following URL, which calls a method in views. urlpatterns = [ url(r'^result/approve/(?P<pk>\d+)/$', views.approve_group, name ='approve_group'), ] Here is the views-method that is supposed to redirect back to home: @csrf_exempt def approve_group(request, pk): group = Group.objects.get(pk=pk) group.status = Status.approved group.save() return reverse('home') Unfortunately, this does not lead to the http://127.0.0.1:8000/home page It takes me to the: http://127.0.0.1:8000/result/approve/1/home page instead. It just appends "home" to the previous URL. How can I force this method to redirect directly to home, and not just append it at the end of http://127.0.0.1:8000/result/approve/1/? Thank you for your time! -
Django class based view and template with some div section
I have my Django class based view in which in the get method I am rendering a template with 4 div section(when one div section is being displayed, other three are hided, just for information). Each div section in the template displays a different set of data from a model. The logic of the extraction of data that I want to display is mixed and code is such a mess. Now my code is like this: class MyClass(View): def post(...): .... def get(self, request): # about 50 lines of code in which I am extracting data from models # but is too messy ... # in context I put extracted data context={'proposte_richieste': proposte_richieste, 'proposte_richiedibili': proposte_richiedibili, 'offerte_richiedibili': offerte_richiedibili, 'offerte_richieste': offerte_richieste, 'richiesteapprovate': richiesteapprovate, 'richiesteOapprovate': richiesteOapprovate, 'studente': studente, } return render(request,'myapp/mytemplate',context) I want something like this: class MyClass(View): def post(...): .... def get(self, request): def functionForDiv1(): ...#code for extract data for div1 def functionForDiv2(): ...#code for extract data for div2 -
paypal IPN is in json format body , how to append verify cmd?
def paypalNotify( tag, request ) : logger.info( "get notify from " + tag + "Paypal:" ) logger.info( "QueryDict: ") logger.info( request.POST ) logger.info( "body: " ) logger.info( request.body ) logger.info( "content_type : " ) logger.info( request.content_type ) notify = json.loads( str( request.body, "utf8") ) verify_cmd = "?cmd=_notify-validate" ok = False if tag == "sandbox" : resp = requests.post( SANDBOX_PAYPAL_VERIFY_IPN + verify_cmd , data = request.body ) elif tag == "live": resp = requests.post( LIVE_PAYPAL_VERIFY_IPN + verify_cmd , data = request.body ) logger.info( resp ) if resp.ok and resp.text == "VERIFIED": logger.info( "verify paypal notify success " ) ok = True elif resp.ok and resp.text == "INVALID" : logger.info( "verify paypal notify failed " ) ok = False return HttpResponse(); else: logger.info( "verify paypal notify failed " ) ok = False return HttpResponse() I get following log: get notify from sandboxPaypal: QueryDict: body: b'{"id":"WH-60T842431C033902E-45C96888PP9193402","event_version":"1.0","create_time":"2017-10-23T09:26:04.086Z","resource_type":"sale","event_type":"PAYMENT.SALE.COMPLETED","summary":"Payment completed for $ 2.0 USD","resource":{"id":"9C282227JW286135M","state":"completed","amount":{"total":"2.00","currency":"USD","details":{"subtotal":"2.00"}},"payment_mode":"INSTANT_TRANSFER","protection_eligibility":"ELIGIBLE","protection_eligibility_type":"ITEM_NOT_RECEIVED_ELIGIBLE,UNAUTHORIZED_PAYMENT_ELIGIBLE","transaction_fee":{"value":"0.37","currency":"USD"},"invoice_number":"","custom":"[\"xxxxxeg@qq.com\", \"primary\", \"1\"]","parent_payment":"PAY-12T27562BA472264LLHW3K4Y","create_time":"2017-10-23T09:25:30Z","update_time":"2017-10-23T09:25:30Z","links":[{"href":".....sandbox.paypal.com/v1/payments/sale/9C282227JW286135M","rel":"self","method":"GET"},{"href":".....sandbox.paypal.com/v1/payments/sale/9C282227JW286135M/refund","rel":"refund","method":"POST"},{"href":"....sandbox.paypal.com/v1/payments/payment/PAY-12T27562BA472264LLHW3K4Y","rel":"parent_payment","method":"GET"}]},"links":[{"href":".....sandbox.paypal.com/v1/notifications/webhooks-events/WH-60T842431C033902E-45C96888PP9193402","rel":"self","method":"GET"},{"href":"......sandbox.paypal.com/v1/notifications/webhooks-events/WH-60T842431C033902E-45C96888PP9193402/resend","rel":"resend","method":"POST"}]}' How can I verify the IPN with JSON body ? the suck document said I need append " cmd=_notify-validate ", I tried to append the verify cmd to response body, it doesn't work. -
What's the Django User password's encryption method?
In django project, there is auth_user table: and its structure is like this: You see its length is 128, I don't know whats the meaning of encryption method of the password field. -
redirect_field_name DJANGO didn't work
I would redirect the user to "admin" page if he is superuser, else to normal "profile" but it didn't work urls.py url(r'^user/login/', LoginUserView.as_view(), name='login'), url(r'^user/profile/', UpdateUserView.as_view(), name='profile'), url(r'^user/admin/$', UpdateAdminView.as_view(), name='admin'), views.py class LoginUserView(auth_views.LoginView): template_name = "Login/login.html" #TODO def dispatch(self, request, *args, **kwargs): if self.request.user.is_superuser: self.redirect_field_name = reverse_lazy("admin") else: self.redirect_field_name = reverse_lazy("profil") return super(LoginUserView, self).dispatch(request, *args, **kwargs) -
Redirect to a custom admin view in Django
I have created a custom view (dashboard) using admin.py and it is showing in Django admin panel. I need to get this dashboard to be shown after admin login. I have tried using LOGIN_REDIRECT_UR="admin/project/dashboard". But it is showing /accounts/profile/ -
AttributeError: 'Meta' object has no attribute 'app_config'
I'm trying to run an already existing project on my local machine from a git repo. Trying to run the command "python manage.py runserver" produces an AttributeError as stated on my title. The error is on line 81: def check(self, app_configs): if app_configs is None: app_configs = apps.get_app_configs() app_configs = set(app_configs) # Speed up lookups below errors = [] modeladmins = (o for o in self._registry.values() if o.__class__ is not ModelAdmin) for modeladmin in modeladmins: if modeladmin.model._meta.app_config in app_configs: #ErrorHere errors.extend(modeladmin.check()) return errors Command prompt AttributeError image -
Django not listening on port when execute runserver remotely (python - paramiko)
I have several Django applications on a Ubuntu computer (not in a production environment). When I connect via putty (ssh) from my Windows computer to that Ubuntu computer and start the applications with: 'python ./manage.py runserver x.x.x.x:yyyy'. I can connect to x.x.x.x:yyyy/app from every other computer in our network. So far, so good. For my co-workers however, I want to make a script so that they can start/stop the applications without using putty. I'm trying to do that with Python and the paramiko lib. I have these lines in my script: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ubuntu.server, username=ubuntu.uname, password=ubuntu.pwd) ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("nohup python {0}/manage.py runserver {1}:{2} &".format(subpad, ubuntu.server, port)) When the script is executed I can see the Django server is running in the 'ps -aux' output, but I cannot connect to the app(s) from my browser. Also when I run 'netstat -vatn' I cannot see the Ubuntu computer listening to the specified port(s) (while the Ubuntu PC is listening to these port(s) when starting the servers via putty). Why is this? And how can I solve this problem? -
Django Chatterbot: installation
I built my own chatbot with Chatterbot library, but for local work. Now I want to build it for Telegram but when I try to install packages of Django with pip install django chatterbot, the Terminal shows me this: Requirement already satisfied: django in /Library/Python/2.7/site-packages Requirement already satisfied: chatterbot in /Library/Python/2.7/site-packages Requirement already satisfied: pytz in /Library/Python/2.7/site-packages (from django) Collecting python-dateutil<2.7,>=2.6 (from chatterbot) Using cached python_dateutil-2.6.1-py2.py3-none-any.whl Requirement already satisfied: nltk<4.0,>=3.2 in /Library/Python/2.7/site-packages (from chatterbot) Requirement already satisfied: python-twitter<4.0,>=3.0 in /Library/Python/2.7/site-packages (from chatterbot) Requirement already satisfied: pymongo<4.0,>=3.3 in /Library/Python/2.7/site-packages (from chatterbot) Requirement already satisfied: jsondatabase<1.0.0,>=0.1.7 in /Library/Python/2.7/site-packages (from chatterbot) Requirement already satisfied: chatterbot-corpus<1.1,>=1.0 in /Library/Python/2.7/site-packages (from chatterbot) Requirement already satisfied: sqlalchemy<1.2,>=1.1 in /Library/Python/2.7/site-packages (from chatterbot) Requirement already satisfied: six>=1.5 in /Library/Python/2.7/site-packages/six-1.10.0-py2.7.egg (from python-dateutil<2.7,>=2.6->chatterbot) Requirement already satisfied: requests-oauthlib in /Library/Python/2.7/site-packages (from python-twitter<4.0,>=3.0->chatterbot) Requirement already satisfied: future in /Library/Python/2.7/site-packages (from python-twitter<4.0,>=3.0->chatterbot) Requirement already satisfied: requests in /Library/Python/2.7/site-packages (from python-twitter<4.0,>=3.0->chatterbot) Requirement already satisfied: ruamel.yaml<=0.15 in /Library/Python/2.7/site-packages (from chatterbot-corpus<1.1,>=1.0->chatterbot) Requirement already satisfied: oauthlib>=0.6.2 in /Library/Python/2.7/site-packages (from requests-oauthlib->python-twitter<4.0,>=3.0->chatterbot) Requirement already satisfied: idna<2.7,>=2.5 in /Library/Python/2.7/site-packages (from requests->python-twitter<4.0,>=3.0->chatterbot) Requirement already satisfied: urllib3<1.23,>=1.21.1 in /Library/Python/2.7/site-packages (from requests->python-twitter<4.0,>=3.0->chatterbot) Requirement already satisfied: certifi>=2017.4.17 in /Library/Python/2.7/site-packages (from requests->python-twitter<4.0,>=3.0->chatterbot) Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /Library/Python/2.7/site-packages (from requests->python-twitter<4.0,>=3.0->chatterbot) Requirement already satisfied: ruamel.ordereddict in /Library/Python/2.7/site-packages … -
Authentication infromation is not provided when I use Django rest framework
I use the Django Rest Framework, but there seems I can not access, need permission to do this: Authentication infromation is not provided. How to resolve this issue? -
how to assign a worker a job once a day
I am a newbie in django and python. I have a Staff, Job and Track models and what I want is track/assign a staff worker to a job only once a day. I have no clue how to go about this. I have this model and views and I wish to add this function as it is not the first time I am dealing with this. Models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.utils import timezone from django.conf import settings from django.db import models from django.contrib.auth.models import User from decimal import Decimal class CompanyDetail(models.Model): STATUS_CHOICES = ( ('inactive', 'Inactive'), ('active', 'Active'), ) authorized_user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='company_user', default=1) name = models.CharField(max_length=100, default="Company Name") tel = models.CharField(max_length=15, default="Company Tel") contact_person = models.CharField(max_length=100, default="Contact Person") status = models.CharField(max_length=10, choices=STATUS_CHOICES, default="inactive") logo = models.ImageField() def __str__(self): return self.name class Job(models.Model): STATUS_CHOICES = ( ('inactive', 'Inactive'), ('active', 'Active'), ) company_user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='job_user', default=None) job_name = models.CharField(max_length=100) job_contact_number = models.CharField(max_length=15) job_address = models.CharField(max_length=250) published = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='active') def __str__(self): return self.job_name class StaffSkill(models.Model): STATUS_CHOICES = ( ('inactive', 'Inactive'), ('active', 'Active'), ) skill = models.CharField(max_length=100, default="Company Name") status = models.CharField(max_length=10, choices=STATUS_CHOICES, default="inactive") def __str__(self): return … -
Django memcache ignores caching of big html pages
I have a view that depending on get parameters can give pretty bit html output. I noticed that if html is big enough, django is not caching it. Is there any way to make this working? https://www.yenotes.com/en/?from_lang=fr&q=%C3%AAtre&to_lang=uk - caching is OK https://www.yenotes.com/en/?q=run&from_lang=en&to_lang=uk - cache is not working. It is worth noting that everything works fine with FileBasedCache. -
Whats the meaning of the model default params?
When I read a project, there I saw the params for create the field: class Task(models.Model): title = models.CharField('标题', max_length=100) description = models.TextField('描述') completed = models.BooleanField('是否完成', default=False) create_date = models.DateTimeField('创建时间', auto_now_add=True) Such as: title = models.CharField('标题', max_length=100) I don't understand the 标题 here has what function. -
Django - Comment form
I have 4 models: User, Blogger, Post and Comment. Now, in 'post_desc.html', i want to insert a comment box. {% if user.is_authenticated %} <form method="post"> {% csrf_token %} <input type="text" name="comment" style="width: 800px; height: 145px;"></br></br> <button type="submit">Submit Comment</button> </form> {% else %} <p><a href="{% url 'login' %}">Login</a> to comment</p> {% endif %} So, this form will only take comment from the user. But how to store information like 'commented_by' which will the user that is currently logged in and 'commented_on' which will be the post_topic in which he/she is commenting. How to store these information automatically? in views.py i tried 'request.user' but that didn't worked. Any solutions? -
Slow distance query in GeoDjango with PostGIS
I am using GeoDjango with Postgres 10 and PostGIS. I have two models as follows: class Postcode(models.Model): name = models.CharField(max_length=8, unique=True) location = models.PointField(geography=True) class Transaction(models.Model): transaction_id = models.CharField(max_length=60) price = models.IntegerField() date_of_transfer = models.DateField() postcode = models.ForeignKey(Postcode, on_delete=models.CASCADE) property_type = models.CharField(max_length=1,blank=True) street = models.CharField(blank=True, max_length=200) class Meta: indexes = [models.Index(fields=['-date_of_transfer',]), models.Index(fields=['price',]), ] Given a particular postcode, I would like to find the nearest transactions within a specified distance. To do this, I am using the following code: transactions = Transaction.objects.filter(price__gte=min_price) \ .filter(postcode__location__distance_lte=(pc.location,D(mi=distance))) \ .annotate(distance=Distance('postcode__location',pc.location)).order_by('distance')[0:25] The query runs slowly taking about 20 - 60 seconds (depending on filter criteria) on a Windows PC i5 2500k with 16GB RAM. If I order by date_of_transfer then it runs in <1 second for larger distances (over 1 mile) but is still slow for small distances (e.g. 45 seconds for a distance of 0.1m). So far I have tried: * changing the location field from Geometry to Geography * using dwithin instead of distance_lte Neither of these had more than a marginal impact on the speed of the query. The SQL generated by GeoDjango for the current version is: SELECT "postcodes_transaction"."id", "postcodes_transaction"."transaction_id", "postcodes_transaction"."price", "postcodes_transaction"."date_of_transfer", "postcodes_transaction"."postcode_id", "postcodes_transaction"."street", ST_Distance("postcodes_postcode"."location", ST_GeogFromWKB('\x0101000020e6100000c425c79dd2c1ccbf17a06d35ebc44940'::bytea)) AS "distance" FROM "postcodes_transaction" INNER JOIN … -
How to hide button/form with django templates?
I want to hide form if user already pushed on the button. I tried to use a bit of JS code, it works well, but after refreshing page, button on form stay valid. It not a huge surprise for me)) I want hide form using Django templates, but it is not so easy as I thought. my html : <div class="who_come"> <p>Who come : </p> {% for u in who_come %} {%if u.visiter.username != request.user.username %} <form class="form-inline" role="form" method="post" id="joinToEventForm"> {% csrf_token %} <p align="left"><b ><button type="submit">I want join</button></b></p></b></p> </form> {% endif %} {% endfor %} <div id="who_come_links"> {% for u in who_come reversed %} <p><a href="profile/{{u.visiter.username}}" title="{{u.visiter.first_name}} {{u.visiter.last_name}}">{{u.visiter.username}}</a></p> {% endfor %} </div> <script> $('#joinToEventForm').submit(function() { $(this).find("button[type='submit']").prop('disabled',true); }); </script> <script> $('#joinToEventForm').on('submit', function(event){ event.preventDefault(); console.log("form submitted!") // sanity check $.ajax({ type:'POST', data:{ action: 'joinEvent', csrfmiddlewaretoken:'{{ csrf_token }}' }, success : function (data) { //console.log(data); var usernames = JSON.parse(data); var html_str = ''; for (var i=0; i < usernames.length; i++) { html_str += '<p><a href="profile/' + usernames[i] + '">' + usernames[i] + '</a></p>'; } $('#who_come_links').html(html_str); } }); }); </script> </div> my model : class WhoComeOnEvent(models.Model): visiter = models.ForeignKey(User, related_name='WhoComeOnEvent') which_event = models.ForeignKey(Topic, related_name='WhoComeOnEvent') in this place : <p>Who come : </p> …