Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django logging setup help for new website in prod
Alright so the development phase is over and now my website is live in prod. However, I have not set up the logging. My website is located in /var/www/html dir. Ideally I would like to have Django logging in /var/log/django but that would require permissions. Is it standard practice to keep Django logs in /var/log/? What type of permissions I need for the logs to store in /var/log. I just want logs for last 2 days and today, rest can automatically be removed if I can. Setup: RHEL7, Apache2.4, python3.5, Django 1.10, mod_wsgi, mySQL -
custom ordering to django model
class MemberAdmin(CustomUserAdmin, admin.ModelAdmin): redirect_model_name = 'memberaccountproxy' change_form_template = 'loginas/change_form.html' list_display = ('username', 'email', 'first_name', 'last_name','country', 'gender', 'created_at', 'profile_pic') search_fields = ('username', 'first_name', 'last_name', 'email',) add_form = AccountProfileForm list_filter = ( 'gender', 'incomplete', 'email_verified', 'suspended', 'deleted', ) # profile1 = None def get_queryset(self, objects): return Account.objects.filter(usertype=1) def country(self, obj): profile1 = Profile.objects.get(account=obj) if profile1.country: return profile1.country return '' country.admin_order_field = 'country' What I am trying to achieve is to make my country column on Member list page sortable.(currently its not) Problem is that I get the 'obj' from method country as an Account object(as defined in the get_queryset()), & later I use that obj to get another object of type Profile (which has a member variable country). But when I try to register the country method to 'admin_order_field', it can only take member variables of obj (of type Account, which doesn't have country variable in it). Is there a way to sort the country column based on the field from Profile class instead of Account. -
Django Admin Custom Form Based on Request
I am trying to make custom form for a model in the django admin area with a select field that is created on submit based on the request.user. The user would then pick from the select and it would save specific settings to the model. the model: class Thing1(models.Model): user = models.ForeignKey(User) setting_1 = models.BooleanField(default=False) setting_2 = models.BooleanField(default=False) setting_3 = models.BooleanField(default=False) But instead of having the user set the settings fields manually, I'd like to display a Select with something like: - Default Settings - Other Settings And the user would select one and the system would save the settings booleans accordingly. The actual options of the select depends on the user, so I need request.user to be able to build that select field. I don't seem to have access to request in the ModelForm. So I know that I can exclude the settings fields from the model in django admin, but how do I get the form to include the select with the correct things in the select options for the user and then have it save the correct settings in the model on save? I've read a bunch of other questions about custom django admin fields and got … -
Django auto_increment base36 pk instead of integer?
is it possible to replace the standard auto_increment integer pk with an auto_increment base36 pk or do I have to add a new column to my table? -
Django - Access to ForeignKey in template, but with a filter
i need to access to a foreignkey of a object but i can't make it work. This are my models class Product(models.Model): # Attributes - Mandatory name = models.CharField( max_length=63, unique=True, verbose_name=_('name'), ) slug = models.SlugField( max_length=63, unique=True, editable=False, verbose_name=_('slug'), ) title = models.CharField( max_length=63, editable=False, help_text=_('name to show the product in the templates'), verbose_name=_('title') ) # Precio de venta al público sell_price = models.DecimalField( max_digits=10, decimal_places=2, verbose_name=_('sell price'), ) minimal_quantity = models.SmallIntegerField( default=1, verbose_name=_('minimal quantity'), ) available = models.BooleanField( default=True, ) created = models.DateTimeField( editable=False, verbose_name=_('created'), ) modified = models.DateTimeField( editable=False, verbose_name=_('modified'), ) And i have to access to the Stock of the products class ProductStock(models.Model): # Relations product = models.ForeignKey( Product, verbose_name=_('product'), ) warehouse = models.ForeignKey( Warehouse, default = 1, verbose_name=_('warehouse'), ) # Attributes - Mandatory quantity = models.IntegerField( verbose_name=_('quantity'), ) Well the quantity of the product that i'm triying to get is the product quantity on the Warehouse with ID=1 only that. Thanks for your help! -
Find points and polygons nearest to coordinates. Big data set
Im trying to solve the following problem: I need to get the nearest point to a coordinate within a tolerance of lets say 10m. If no point is found I need to find the nearest area to the coordinates, again with a tolerance. The issue I'm facing is that I have 176000 points in one table and 5000 areas in another. It takes a good 10 seconds to find the nearest point or area. This is obviously to long and I would like to get a result in under a second if possible. Im using the following code to find the spots/areas. Its running using geodjango on a postgis database. try: lat = request.GET['lat'] lng = request.GET['lng'] pnt = Point(float(lng), float(lat), srid=4326) tol = request.GET['tol'] if 'tol' in request.GET else 10 area_to_check = pnt.buffer(tol) except (ValueError, MultiValueDictKeyError): return null try: spots = Spot.objects.filter(geom__within=area_to_check) return spots.annotate(distance=Distance('geom', pnt)).order_by('distance')[0] except (Spot.DoesNotExist, IndexError): pass try: areas = Area.objects.filter(geom__contains=pnt) return areas.annotate(distance=Distance('geom', pnt)).order_by('distance')[0] except (Area.DoesNotExist, IndexError): return null -
output text into textbox in python
Hey guys im working on python using django framework,Its basically a web application with two html textboxes and I'm struck with these questions How to take input from these text boxes(how to link python with html and take input). How to display the result in another text box. Please reply and forgive me if this is silly question Thank you!! -
Accessing form field value in Django template
I have a form which contains a CharField named "body" whose value is "test". I'm having trouble when trying to retrieve that value. If I write {{ form.body }} Django renders <input id="id_body" name="body" type="text" value="test" required> However, if I write <span>{{ form.body.value|default_if_none:"" }}</span> the result is <span></span> What am I doing wrong here? By the way, if I write <span>{{ form.fields.body.widget.attrs.value|default_if_none:"" }}</span> I get the right result: <span>test</span> However, I feel this option is quite inelegant. -
jquery destroy modal dialog on close
I have a jquery modal dialog which is created as follows in a function: function EditDialog(pk) { $.ajax({ url: "{% url 'populatereviewform' %}", method: 'GET', data: { pk: pk }, success: function(formHtml){ //place the populated form HTML in the modal body $('.modal-body').html(formHtml); $( "#dialog" ).modal({width: 500, height: 500}); }, dataType: 'html' }); return false; } How can I ensure that every time I call this function a fresh instance of the dialog is created? I wonder if somehow I can hook into the close event and ensure that the dialog is completely destroyed. I am trying to debug something and it seems that some of my variables do not get refreshed when this dialog is called a second time and I am trying to get to the bottom of it. The django template for creating the dialog is: <div id="dialog" class="modal" title="Edit" style="display:none"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span></button> <h4 class="modal-title">Review Uploaded Image</h4> </div> <div class="modal-body"> </div> </div> </div> </div> -
Django settings not working correctly
I am able to execute python manage.py migrate - it executes perfectly But when I run django-admin shell it fails giving the following errors Traceback (most recent call last): File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/core/management/base.py", line 337, in execute saved_locale = translation.get_language() File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/utils/translation/__init__.py", line 190, in get_language return _trans.get_language() File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/utils/translation/__init__.py", line 57, in __getattr__ if settings.USE_I18N: File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/conf/__init__.py", line 39, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/cj/.vtenv/officingx/bin/django-admin", line 11, in <module> sys.exit(execute_from_command_line()) File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/core/management/base.py", line 306, in run_from_argv connections.close_all() File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/db/utils.py", line 229, in close_all for alias in self: File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/db/utils.py", line 223, in __iter__ return iter(self.databases) File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/db/utils.py", line 156, in databases self._databases = settings.DATABASES File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/conf/__init__.py", line 39, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting … -
Pass Google Places lat and lng values from JavaScript on webpage to Django
I've used the Google Places API to put a map with a search box on an HTML page of my project. I want the following to happen: when someone searches a location, the coordinates (lat/lng) of the selected location are passed to the server. After this, I want to extract all entries of my Listing model (containing locations with their lat and lng) that are within a certain radius of the selected location, and pass back the lat/lng values to be displayed as markers on the map. I've pretty much copied the JavaScript from the Google example here: https://developers.google.com/maps/documentation/javascript/examples/places-searchbox, and I understand that this is the relevant section for extracting the lat/lng: // Create a marker for each place. markers.push(new google.maps.Marker({ map: map, icon: icon, title: place.name, position: place.geometry.location })); From looking at other answers on here, it seems that the way to get the lat and lng is as follows: var lat = place.geometry.location.lat(); var lng = place.geometry.location.lng(); Should I just place these variables below the above block of code? And how do I go about sending them to the server (if that is what I need to do)? Some answers to vaguely similar questions seem to suggest including … -
Return FileFile to Client. Django
I'm trying to return a uploaded file to the Client. models.py file = models.FileField(_('file'), db_index=True, null=True, blank=True, upload_to='files/') views class ContentInfoViewSet(viewsets.ModelViewSet): queryset = ContentInfo.objects.all() serializer_class = ContentInfoSerializer http_method_names = ['get'] @detail_route(methods=['get']) //this is just for testing def files(self, request, pk=None): return Response(pk, status=status.HTTP_200_OK) Here I was just trying with a "files" route. When I try to get "content-info". It works nicely: [ { "url": "http://127.0.0.1:8000/users/content-info/1/", "id": 1, "date": "2017-01-27T16:21:41.976289Z", "title": "Hey Hey", "image_url": "", "content_url": "", "file": null }, { "url": "http://127.0.0.1:8000/users/content-info/3/", "id": 3, "date": "2017-03-21T12:09:32.984119Z", "title": "NWE", "image_url": "", "content_url": "", "file": "http://127.0.0.1:8000/users/content-info/files/BIAM-51.pdf" } ] But that URL doesn't work. Even if I make a get with Authorization. So , I don't know what I'm doing wrong. -
After machine reboot "unix:/socket/uwsgi.sock failed (13: Permission denied) while connecting to upstream"
9 application integrated to nginx via uwsgi application on Centos7. It was working fine, but then i had to reboot my machine. Now i am having the follwoing issue: unix:/socket/uwsgi.sock failed (13: Permission denied) while connecting to upstream, client: 10.184.160.9, server: 10.184.2.231, request: "GET /", upstream: "uwsgi://unix:/socket/uwsgi.sock:" Any clue? My ini file: [uwsgi] chdir = /home/elastic/workspace/ES_Brevetti wsgi-file = ES_Brevetti/wsgi.py master = true processes = 5 uid = nginx gid = nginx socket = /socket/uwsgi.sock chmod-socket = 666 vacuum = true nginx.conf upstream django { server unix:/socket/uwsgi.sock; # for a file socket #server 127.0.0.1:8001; # for a web port socket (we'll use this first) } server { listen 80; server_name 10.184.2.231; error_log /var/log/nginx/error.log; access_log /var/log/nginx/access.log; charset utf-8; location /nuovopatentdb/static { alias /home/elastic/workspace/ES_Brevetti/static; } location / { include /etc/nginx/uwsgi_params; uwsgi_pass unix:/socket/uwsgi.sock; } } I dont know why i am having this issue? Further mode should i be creating the sock file anytime the machine is rebooted ? Thanx valerio -
django model manytomany filter by count
I have 2 models that have a one to many relationships. I'm trying to reflect blog by the number of likes on a blog. I tried to filter num_likes than annotate by count, but none of it reflects blogs by the number of likes. class Blog(models.Model): blog_content = models.TextField(max_length = 500) class Like(models.Model): user = models.ForeignKey(User, related_name = "likes") blog = models.ForeignKey(Blog, related_name = "likes") -
Unable to pass data inside anchor tag to views in Django
I am trying to build a document retrieval engine. On entering a query, the user gets a list of documents sorted by relevancy. But just getting the name of documents isn't very helpful. So instead of simply displaying the table, I hyperlinked the document name. Within the anchor tags is the name of the document. When a user clicks this link, I want to display the contents of this file to user using the document name. So basically, when a user clicks the link I want to pass the contents within the tags to my view function. Following are some parts of my code that are relevant. the .html page <table class = "tab_results"> <tr> <th>Project Name</th> <th>Score</th> </tr> {% for each_pair in results%} <tr> <td name = 'project_name'><a id = 'doc_name' href = "doc_viewer/?query_name={{ each_pair.0|urlencode }}">{{ each_pair.0 }}</a></td> <td>{{ each_pair.1 }}</td> </tr> {% endfor %} </table> my urls.py file from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index), url(r'^index$', views.index), url(r'^[?]query=', views.doc_scorer, name="doc_scorer"), url(r'^doc_viewer[/]', views.doc_viewer, name="doc_viewer"), ] Lastly the views.py file def doc_viewer(request): project_name = request.GET.get('project_name') context = {'doc_data': search_query.doc_data(project_name)} return render_to_response('search/doc_viewer_temp.html', context) I followed what was given here but I get the following error … -
How to automatically generate notification to user when events is added?
I have developed a website having functionality such as writing,posting ,user profiles, events & activities, offers..etc.I need to add one more functionality and i.e. Automatic push notification to the users about activities & events, offers and discounts (facebook like notification). What I want to do is to inform users in their profiles, whenever admin/staff add their events & activities and offers or if user are updating profile, then inform the user of that update. I have looked around many applications but I am still very confused about how to do it. I really need some proper tutorial or guidance on how to go about doing it. I know how to register a notification and send it on proper signal but there is no documentation on how to show these notices in a template, if this can be done. -
Django not found in remote API (but works in app!)
See source below. The app I deployed using: gcloud add deploy Django templating works fine, as seen when loading: https://myapp.appspot.com/foo.txt When connecting to the remote API, however, I get an error: C:\myapp>"C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\remote_api_shell.py" myapp App Engine remote_api shell Python 2.7.8 (default, Jun 30 2014, 16:03:49) [MSC v.1500 32 bit (Intel)] The db, ndb, users, urlfetch, and memcache modules are imported. s~myapp> from main import Foo WARNING:root:You are using the default Django version (0.96). The default Django version will change in an App Engine release in the near future. Please call use_library() to explicitly select a Django version. For more information see https://developers.google.com/appengine/docs/python/tools/libraries#Django Traceback (most recent call last): File "<console>", line 1, in <module> File "main.py", line 3, in <module> from google.appengine.ext.webapp import template File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\ext\webapp\template.py", line 63, in <module> webapp._config_handle.django_setup() File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\ext\webapp\__init__.py", line 176, in _django_setup import django ImportError: No module named django s~myapp> With Python 2.5 this issue did not exist. I could successfully connect to the remote API, import classes from main.py and populate the datastore. However, Python 2.5 is being shut down on GAE. Why does Django work for the app but not for the remote API? What needs … -
Template does not exist django
What I have done is put multiple apps into another app. I have them talking to each other though the name system. I still have to do foreign keys and all for the databases. However I have a route in my urls.py on the couresapp and a view for the same rendering and taking me to the page. When I click the catalog button on the success page it gives me an error that page cannot be found. Hoping a second pair of eyes can see and fix this. Urls.py for courses app from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name= 'index'), url(r'^user$', views.create, name='success'), url(r'^usercourses$', views.usercourses, name='usercourses') ] view for courses app part that matters def usercourses(request): context ={ "courses": User.objects.all(), } return render (request, "coursesapp/users_courses.html", context ) html for coures app part hat matters <body> <form class="" action="{% url 'courses:usercourses' %}" method="post"> <p> Test <option value="{{user.course_name}}"></option> Test Test <option value="{{user.course_name}}"></option> Test <input type="submit" name="" value="Add"> </form> {% for user in courses%} <p>{{user.course_name}} {{user.description}} {{created_at.description}}</p> {% endfor%} </body> html for the form in the success page in the login app that takes me to the couress app <form class="" action="{% url 'courses:usercourses' %}" … -
Checking the next run time for scheduled periodic tasks in Celery (with Django)
*Using celery 3.1.25 because django-celery-beat 1.0.1 has an issue with scheduling periodic tasks. Recently I encountered an issue with celerybeat whereby periodic tasks with an interval of a day or longer appear to be 'forgotten' by the scheduler. If I change the interval to every 5 seconds the task executes normally (every 5 seconds) and the last_run_at attribute gets updated. This means celerybeat is responding to the scheduler to a certain degree, but if I reset the last_run_at i.e. PeriodicTask.objects.update(last_run_at=None), none of the tasks with an interval of every day run anymore. Celerybeat crashed at one point and that may have corrupted something so I created a new virtualenv and database to see if the problem persists. I'd like to know if there is a way to retrieve the next run time so that I don't have to wait a day to know whether or not my periodic task has been executed. I have also tried using inspect <active/scheduled/reserved> but all returned empty. Is this normal for periodic tasks using djcelery's database scheduler? -
Can't host django app on Amazon EC2
I'm trying to host my Django app on Amazon EC2 instance (Ubuntu 16.04) by following these instructions. I've done everything mentioned here but in the end I get a 502 Bad gateway error when I try to access my app through it's DNS. It can be seen at 35.154.169.37. Where is it that I'm going wrong? -
how do get data from a created processor outside program without its original python object
am letting users in my django python app to call a function which in turn creates a process with the multiprocessor module, but i need to let users check for the processor progress (retrieve data inside it) and status (alive or done executing) and possibly terminate it (which i found easy to do with system commands) without having access to processor object since i can't store it somewhere. is it possible to store in database only PID of the process (or some convenient identifier) and call it later? maybe try to get informations from it and manage it. the information if i could get it directly from the process would be much reliable rather than storing it somewhere else and retrieving it there. the function that runs in the background as a process/daemon would be completely independent of the program and has its own data that changes overtime which i need to let users be able to check its progress. -
Azure Django Git deployment fails. Pip install requirements?
I have a functioning django app in development mode. I can start it on my local machine with python manage.py runserver and it works like a charm (with sqlite). @AZURE: I have created a Django paas (Publisher: PTVS) and enabled local git in deployment options. Publish to azure, using git, fails. How do i debug this? git remote add azure <url> git push azure git log: git push azure Counting objects: 3, done. Delta compression using up to 4 threads. Compressing objects: 100% (2/2), done. Writing objects: 100% (3/3), 292 bytes | 0 bytes/s, done. Total 3 (delta 1), reused 0 (delta 0) remote: Updating branch 'master'. remote: Updating submodules. remote: Preparing deployment for commit id '628143a1a3'. remote: Generating deployment script. remote: Running deployment command... remote: Handling python deployment. remote: . remote: KuduSync.NET from: 'D:\home\site\repository' to: 'D:\home\site\wwwroot' remote: Copying file: 'requirements.txt' remote: Detected requirements.txt. You can skip Python specific steps with a .skipPythonDeployment file. remote: Detecting Python runtime from runtime.txt remote: Detected python-3.4.4 remote: Found compatible virtual environment. remote: Pip install requirements. remote: An error has occurred during web site deployment. remote: remote: Error - Changes committed to remote repository but deployment to website failed. To https://vertriebstool.scm.azurewebsites.net:443/vertriebstool.git 96ae981..628143a master -> … -
Django Project display content issue
While working with Django Project the content gets hidden or show html code directly in webpage and when we reload the page everything comes back to normal. -
How to get query rows sorted by number of matched properties?
I have two models/tables A and Property. A has a many to many relationship to Property. A has one field SomeName and Property also has one field Value. Through my app, I receive a list of Values. Now, I want to retrieve the A rows who has at least one Value from the sent list but I also want to sort those rows according to the number of Properties present. For example, M, N and O are three objects of model A. M has the properties P1, P2, P3, N has the properties P2, P3, P4 and O has the properties P3. I receive a list of values P2, P4. Now, the resultant queryset I want is [<N>, <M>] Django code is preferred but SQL will also suffice. -
As a user, I want to be able to see usage in terms of the volume of data cleansed, and also to be able to see it graphically
We need to be showing The volume of data from UserActivityHistory The % of records that were dirty To the JobForm in forms.py, add The volume of data, using get_bytes() for the UserActivityHistory model for that job The total number of records, using number_records from the Job model for that job To the HistoryForm in forms.py, add The % of records cleansed, by dividing number_records by job.number_records and formatting as a percentage Add the same to the email in send_job_email in history.py The volume of data, using get_bytes() for the UserActivityHistory model for that job The total number of records, using number_records from the Job model for that job The % of records cleansed for each history record, by dividing number_records by job.number_records and formatting as a percentage This is my models: class History(models.Model): """The base model for history that are run""" date = models.DateTimeField(default=timezone.now, null=False) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) rule = models.ForeignKey("Rule", on_delete=models.SET_NULL, null=True) job = models.ForeignKey("Job", on_delete=models.SET_NULL, null=True) category = models.CharField(max_length=20, choices=HistoryCategory.choices, default=HistoryCategory.IGNORED) description = models.CharField(max_length=64, null=False, blank=True) number_records = models.IntegerField(null=True, default=0) records = models.FileField( max_length=1024, storage=job_file_storage, null=True, blank=True, upload_to=upload_path) column = models.CharField(max_length=64, null=False, blank=True) class Meta: ordering = ['-date', 'column', 'category'] class Job(models.Model): """Jobs are indviidual …