Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> … -
Django Binding POST request to class-based view
I am trying to build a class based view to handle a review/update form. The form is built with the following code for the form: class ProcesoCandidato(forms.Form): '''''' hrfrmreclutado_nombres = forms.CharField() hrfrmreclutado_se_presento = forms.ChoiceField( choices=()) hrfrmreclutado_cambio_de_cita = forms.DateField() hrfrmreclutado_entrevista = forms.ChoiceField() hrfrmreclutado_contratado = forms.ChoiceField() hrfrmreclutado_motivo_de_rechazo = forms.ChoiceField() hrfrmreclutado_notas = forms.CharField() def clean(self): '''''' cleaned_data = super(ProcesoCandidato, self).clean() clnfrmreclutado_nombres = \ clnfrmreclutado_se_presento = \ self.cleaned_data.get('hrfrmreclutado_se_presento', '') clnfrmreclutado_cambio_de_cita = \ self.cleaned_data.get('hrfrmreclutado_cambio_de_cita', '') clnfrmreclutado_entrevista = \ self.cleaned_data.get('hrfrmreclutado_entrevista', '') clnfrmreclutado_contratado = \ self.cleaned_data.get('hrfrmreclutado_contratado', '') clnfrmreclutado_motivo_de_rechazo = \ self.cleaned_data.get('hrfrmreclutado_motivo_de_rechazo', '') clnfrmreclutado_notas = \ self.cleaned_data.get('hrfrmreclutado_notas', '') def __init__(self, *args, **kwargs): '''''' super(ProcesoCandidato, self).__init__() self.fields['hrfrmreclutado_se_presento'].choices = [ ('', '------'), ('Si', 'Si'), ('No', 'No'), ] self.fields['hrfrmreclutado_entrevista'].choices = [ ('', '------'), ('Si', 'Si'), ('No', 'No'), ] self.fields['hrfrmreclutado_contratado'].choices = [ ('', '------'), ('Si', 'Si'), ('No', 'No'), ] self.fields['hrfrmreclutado_motivo_de_rechazo'].choices = \ [('', '------')] + [(c.pk, c.razonrechazo) for c in models.RazonRechazo.objects.all()] The views file contains a class based view to handle the GET and POST methods: class ProcesoRH(View): '''''' form_class = ProcesoCandidato initial = { 'procesorh_llego': 'No', 'procesorh_entrevista': 'No', 'procesorh_contratado': 'No', 'procesorh_rechazo': '', 'procesorh_notas': ''} template_name = 'sitio_rh/rhprocess.html' def get(self, request, *args, **kwargs): reclutadoid = request.GET['candidato'] procesodata = models.ProcesoRH.objects.filter( procesorh_reclutado_id=reclutadoid) if procesodata.exists() is False: objproceso = models.ProcesoRH() objproceso.procesorh_reclutado_id = reclutadoid objproceso.save() else: … -
Ajax not firing after I added a GeoJson 'data'
I have an HTML page where a button click will fire an ajax function showDetail(): <a href="#" class="list-group-item" onclick="showDetail({{ test.id }});"> <strong>{{ test.test_name }}</strong></a> The ajax function works well if it's like this on its own: function showDetail(id){ $.ajax({ url : "/test/" + id, type: 'GET', success: function(data){ map.removeLayer(tests); $('#pane-content-edit').html(data); $('.tests_display').animate({right:0}); } }); } I would like to modify it having the current HTML page containing a Geojson. And I'd like to pass it to my ajax to pass it to the url my ajax is pointing at. So I did this: function showDetail(id){ $.ajax({ url : "/test/" + id, type: 'GET', data: {'tests_geojson' : {{ tests_geojson | safe}}}, success: function(data){ map.removeLayer(tests); $('#pane-content-edit').html(data); $('.tests_display').animate({right:0}); } }); } After adding that, it would not fire. I tried opening up the web console, nothing is happening. Can someone help? or tell me how to debug this? Thank you! Edit: Additional info - Django Framework templating Contents of test_geojson showing on Leaflet map so it's most likely validated: Big geojson feature but would look generally like so: alert(JSON.stringify(geojsonFeature)); { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": {"type": "Point", "coordinates": [102.0, 0.5]}, "properties": {"prop0": "value0"} }, { "type": "Feature", "geometry": { "type": "LineString", … -
Date range query in django
I have a calendar table in MySQL in the following format. I have only shown 3 rows but there are thousands of rows in the same format. Name Period Indicator Value ACV 2007-01-07 Actual 0.00 TV 2007-01-14 Actual 0.00 Print 2007-01-21 Actual 0.00 MySQL is linked to Django. I want to write a web service in Django such that data for the first 60 days is displayed. This web service will be linked to an HTML component. So each time I click Next I want the web service to display data for the next 60 days. If I click on previous I want it to display data for the previous 60 days. Can someone help me achieve this? -
django admin related Field got invalid lookup: icontains
I got these Models: @python_2_unicode_compatible class Media(models.Model): the_image = FilerImageField(null=True) title = models.CharField(verbose_name="Title", max_length=255, null=True, blank=True) alt_text = models.CharField(verbose_name="Alt Text", max_length=255, null=True, blank=True) created = models.DateTimeField(default=now) modified = models.DateTimeField(editable=True, auto_now=True) product_image_gallery = models.ForeignKey('Product', related_name="product_image_gallery", null=True, blank=True, verbose_name="Product's Image Gallery") def __str__(self): return self.the_image.__str__() @python_2_unicode_compatible class Product( models.Model ): name = models.CharField(verbose_name="Name", max_length=255) slug = models.SlugField(verbose_name="Slug", max_length=255, unique=True) price = models.PositiveIntegerField(verbose_name='Price', null=True, blank=True) sale_price = models.PositiveIntegerField(verbose_name="Sale Price", null=True, blank=True) sku = models.CharField(verbose_name="SKU", max_length=255) def __str__(self): return "%s" % (self.sku, ) I have these Admin Objects: class Media_Admin(admin.ModelAdmin): search_fields = ['id', 'the_image', 'title', 'product_image_gallery__sku'] list_display = ['the_image', 'image_tag', 'title', 'product_image_gallery', 'created'] readonly_fields = ('image_tag',) fieldsets = [ ( "Data", { 'classes': ('grp-collapse grp-open',), 'fields': ['the_image', 'title', 'alt_text']}), ] admin.site.register(Media, Media_Admin) The list_display works fine but the search always gives an error saying "Related Field got invalid lookup: icontains" I don't know what i did wrong, i use double underscore for the SKU "product_image_gallery__sku", but it still gives an error, i tried "product_image_gallery" it is also an error. -
Moving an current DJango app to a different sub-directory
I have an app that was created in an "old" directory using "django-admin startproject businesscontacts" old location: C:\Users..\backendworkproj\businesscontacts moved to new location: C:\Users..\backendworkproj\appmasterdata\businesscontacts Now, of course, the app that was working is now broken. My understanding is that "C:\Users..\backendworkproj\appmasterdata" needs to be put in the PYTHONPATH. I know that there are other explanations out there - but - I am trying to follow one of the responses listed here: Permanently add a directory to PYTHONPATH It says: Instead of manipulating PYTHONPATH you can also create a path configuration file. First find out in which directory Python searches for this information: To me, it is not clear exactly what is to go into the .pth file. I did not see anything stating whether or not a full-path is needed or a realtive-path or ... In my case, 1. run python -m site --user-site output => C:\Users\...\AppData\Roaming\Python\Python36\site-packages 2. Made sure that the directory existed 3. echo "$HOME/foo/bar" > "$SITEDIR/somelib.pth" Again, not sure what is supposed to be in the .pth file - or - what the name of the file should be (with Step #3) TIA -
The current path, didn't match any of these. error django
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/votes/ Using the URLconf defined in votes.urls, Django tried these URL patterns, in this order: ^$ [name='index'] The current path, votes/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. this is my urls.py of my app. from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] this is my urls of my entire project from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^votes/', include('votes.urls')), url(r'^admin/', admin.site.urls), ] I tried to approach to admin site but i couldn't. how can I fix it?