Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement an edit approval queue in Django
I am attempting to make it so a user can edit displayed info stored in an object but that edit is not displayed publicly until an admin approves the edit. These edits are stored in a queue that an admin can sort through. For example: class examplemodel(models.Model): text = models.CharField() This charfield is displayed on a template somewhere where a user can click a link, letting the text become a form containing the same info which when the form is submitted, sends the info not back into the database but to a queue to be approved on the admin page. The only way I can think to do this right now is to make a editRequest object that lets me have the form create a different object and then have some approval function that updates the old object if approved. In which case, how would I tie this to the admin page? -
how to get a bank feed for website
does anybody know how to get a bank feed to a website, I am currently designing an web app. I need the user to be able to cross reference transactions from their bank statement. I know I have the option so they can download the statement and upload to my web app but I would rather be able to miss this step out if i can. Any ideas? -
Django's redirects app doesn't work with URL parameters
I recently installed Django's default redirects app on my site using the exact instructions specified: Ensured django.contrib.sites framework is installed. Added 'django.contrib.redirects' to INSTALLED_APPS. Added 'django.contrib.redirects.middleware.RedirectFallbackMiddleware' to MIDDLEWARE. Migrated database using manage.py migrate. The app works great when my URL is clean, like so: Redirect setting: /page/ to /redirect/ When I visit https://www.example.com/page/ => redirects to https://www.example.com/redirect/ However, the redirects don't work when URL parameters are appended to the end of my URL, like so: Redirect setting: /page/ to /redirect/ When I visit https://www.example.com/page/?url_parameter=true => throws Http404 error (page not found) Ideally, I'd like my redirects to preserve URL parameters, like so: Redirect setting: /page/ to /redirect/ When I visit https://www.example.com/page/?url_parameter=true => redirects to https://www.example.com/redirect/?url_parameter=true Is there a way to force the redirects app to preserve URL parameters per the above? -
Using javascript variable in python(flask/Django) dictionary html
I am trying to use a javascript variable in a python dictionary in html, is this possible? Any help would be great. e.g if i had a dictionary - current_data var num_key = "4"; alert( {{ current_data[num_key] }} ); If i do the following it works perfertly, alert( {{ current_data["4"] }} ); but with the javascript variable it wont work. Thanks again. -
How to deploy django application on Ubantu host IP?
i have created a Django web application on my windows platform . Now i have been asked to deploy it on one the ubantu host IP. As i am new to Django so i am not aware of this procedure. Please can some help me here or can provide me some link which i can refer. Thanks in advance -
Sending file through django form using ajax and djangorestframework 403 error
I am attempting to send pdf file from django template form using ajax and djangorestframwork. Works with usual data, but in this case I get 403 error forms.py class TicketForm(forms.ModelForm): class Meta: model = Ticket fields = ('upload',) widgets = { 'upload': forms.FileInput( attrs={'id': 'fileinput', 'required': True, 'placeholder': 'Say something...'} ), } template and jQuery/js: <form method="post" enctype="multipart/form-data" class="pdf_form"> {% csrf_token %} {{ form.as_p }} <input type="submit" class="">Save</input> </form> <script type="text/javascript"> $(function() { function upload() { alert($('#fileinput').val()) $.ajax({ url: '/upload_ticket/', type : "POST", // http method dataType: 'json', data : { 'file' : $('#fileinput').val() }, // data sent with the post request // handle a successful response success : function() { alert('succes'); }, // handle a non-successful response error : function() { alert('error'); } }); }; $('.pdf_form').on('submit', function(e){ e.preventDefault(); alert('it works!'); console.log("form submitted!") // sanity check upload(); }); }); </script> urls.py: url(r'^upload_ticket/$', views.upload_ticket), views.py: @api_view(['POST', ]) def upload_ticket(request): return Response(request.data) I'v been debugging for hours, but can't find error. What is wrong with my implementation? POST /upload_ticket/ HTTP/1.1" 403 58 -
Use Django with multiple large time series
I’m trying to develop a Django app to visualize data ordered in time series, collected from multiple dataloggers (DL). Since I have to display each DL separately, I wanted to create a model which would store metadata about the DL, create a dedicated SQL table (via direct SQL instructions when post_save signal is received). This solution would allow me to add new / delete dataloggers through admin interface if needed. Data looks like this: Timestamp;Temperature;Meas1;Meas2 2017-01-01 01:00:00;8;15;16 2017-01-01 02:00:00;7.4;14;16 ... My first draft is like this: class Datalogger(models.Model): dl_name = models.CharField(max_length=100) table_name = models.CharField(max_length=50) # Contains the DB table name, which would be created at instantiation. @receiver(post_save, sender=Datalogger) # Stuff to create DB table But I wonder if there is a more efficient way to do this. Is it better to store data in a single table, like a "long-format table" like this in the following example? class Datalogger(models.Model): dl_name = models.CharField(max_length=150) class Variable(models.Model): dl = models.ForeignKey(Datalogger) class Record(models.Model): variable = models.ForeignKey(Variable) value = models.IntegerField() My app may collect data from multiple DL (maybe up to 30), each DL collecting data from 1 to 10 sensors, 1 measure per hour, on time periods that may vary from 1 month to … -
why doesn't django have model save automatic validation built in?
so I have been running this issue a lot during development: i have a object of some model class, and i want to be automatically validated as a whole when it saves(save(), update(), bulk_create()). I know full_clean() will get called when you try to save a object via modelForm, but why there isn't way to trigger validation in all situation? My guess is Django think model shouldn't be validated on a database level? I am opening and looking forward to anybody's comments and answers. Thanks -
DJango won't find virtual env
I am a n00b trying to get django working with apache on a new installation. the test server on port 8000 works fine but apache does not. It appears as though apache cannot read the virtual environment error in logs: [Mon Apr 03 17:14:32.560566 2017] [wsgi:error] [pid 10799] [client 72.178.8.113:37774] mod_wsgi (pid=10799): Target WSGI script '/home/palace/palace/palace/wsgi.py' cannot be loaded as Python module. [Mon Apr 03 17:14:32.560944 2017] [wsgi:error] [pid 10799] [client 72.178.8.113:37774] mod_wsgi (pid=10799): Exception occurred processing WSGI script '/home/palace/palace/palace/wsgi.py'. [Mon Apr 03 17:14:32.561249 2017] [wsgi:error] [pid 10799] [client 72.178.8.113:37774] Traceback (most recent call last): [Mon Apr 03 17:14:32.561338 2017] [wsgi:error] [pid 10799] [client 72.178.8.113:37774] File "/home/palace/palace/palace/wsgi.py", line 12, in <module> [Mon Apr 03 17:14:32.561386 2017] [wsgi:error] [pid 10799] [client 72.178.8.113:37774] from django.core.wsgi import get_wsgi_application [Mon Apr 03 17:14:32.561470 2017] [wsgi:error] [pid 10799] [client 72.178.8.113:37774] ImportError: No module named 'django' apache config: <VirtualHost *:80> ServerName www.persiaspalace.us ServerAdmin webmaster@localhost DocumentRoot /home/palace/ WSGIDaemonProcess myproject python-home=/home/palace/palace/:/home/palace/vpalace/bin:/home/palace/vpalace/lib/python3.5/site-packages/ #WSGIDaemonProcess myproject python-home=/home/palace/vpalace/lib/python3.5/site-packages/ python-path=/home/palace/palace/ WSGIScriptAlias / /home/palace/palace/palace/wsgi.py #WSGIPythonHome /home/palace/vpalace/ #WSGIPythonPath /home/palace/palace/ #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/palace/ <Directory /home/palace/> <Files wsgi.py> Require all granted </Files> </Directory> #Include conf-available/serve-cgi-bin.conf </VirtualHost> django is installed in virtual environment: (vpalace) root@pieceofshiot:/home/palace# pip install django Requirement already … -
How to sum two columns in query on Django
I have the following model on my postgresql database: class UrlXML(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True) url = models.TextField() is_active = models.BooleanField(default=True, db_index=True) run_last_time = models.DateTimeField(blank=True, null=True) run_frequency = models.IntegerField(default=24) Every hour I need to get from database url that need to be downloaded based when on my current time and if the last time it ran was higher then the frequency. I manage to create the raw query, but I can't manage to create it in Django Queryset. Here is the following query: select (run_last_time + INTERVAL '1 hours' * run_frequency), run_frequency, NOW(), run_last_time from urlxml where is_active=True and (run_last_time + INTERVAL '1 hours' * run_frequency) <= NOW(); -
Concatenate two model fields
in my model named XBlockState i have multiple fields, among them there are scenario and scenarioID defined like this scenario = models.CharField( max_length=255, blank=True, null=True, db_index=True, ) scenarioID = models.CharField( max_length=255, blank=True, null=True, db_index=True, ) i need to set a value to scenarioID in the following format scenario.0 -
Django create app error
I want to create the app in django 1.8.12 and I type python manage.py startapp myapp and the traceback: File "C:\Users\User\Anaconda3\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked ImportError: No module named 'fb_weatherbot' What part I missed? I have added the app in INSTALLED_APPS in the settings.py thank you. -
The generation algorithm of letters from the Latin alphabet?
Can someone help me to create algorithm. I have model "Function" with field "symbol". When user create new function object system need to create automatically value of "symbol" field from letters of the English alphabet. Right now I did only from A to Z and without repeating record field value. For example: A B - Z AA AB - AZ BA BB - ZZ AAA etc. models.py: class Function(models.Model): id= models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=250) symbol = models.TextField () def __str__(self): return self.name views.py: if form.is_valid(): for i in string.ascii_uppercase: # (A-Z) if not Function.objects.filter(symbol=i, project=project_code).exists(): function = form.save(commit=False) function.symbol = i function.save() break -
Angular 2 error 403 when trying to POST login information on Django backend
For a project we are developing a web application, the frontend we make use of Angular 2 and Django for the backend. For the communication between front- and backend we use the Django REST framework. I am trying to set up the communication between Angular 2 and Django to authenticate a user. In the profile.service.ts I have the following code: loginUser(email, password){ let url = 'https://backend-development.student-dp8.test.atlantis.ugent.be/user/login/'; // DEBUG let headers = new Headers({ 'Accept': 'application/json', 'Content-Type': 'application/json', }); let options = new RequestOptions({ headers: headers }); return this._http.post(url, JSON.stringify({username: email, password: password}), options) .map(res => res) }; In our app.module.ts file I added the following lines: providers: [ { provide: XSRFStrategy, useValue: new CookieXSRFStrategy('csrftoken', 'X-CSRFToken') } ], When I try to test if I can login a user I get a 403 error (Forbidden: CSRF cookie not set). I've already tried some things I found online, but nothing seems to work. Does anyone knows how to solve this problem? Thanks. -
URL based database routing
I set up URL based database routing inspired by this answer in order to use the same app for different projects/databases. The projects do not need to share any data, access control is managed by every project on its own and I need an admin site for every project. As in the original post I use a database router and a middleware which determines which database to be used from the request path, e.g. /test/process/1 will be routed to database test and /default/process/2 to database default. import threading from django.conf import settings request_cfg = threading.local() class RouterMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): path = request.path.lstrip('/').split('/') if path[0] in settings.DATABASES: request_cfg.db = path[0] def process_response(self, request, response): if hasattr(request_cfg, 'db'): del request_cfg.db return response class DatabaseRouter(object): def _default_db(self): if hasattr(request_cfg, 'db') and request_cfg.db in settings.DATABASES: return request_cfg.db else: return 'default' def db_for_read(self, model, **hints): return self._default_db() def db_for_write(self, model, **hints): return self._default_db() The url patterns then need to be extended to include the subpath which refers to a specific database. I did this by hardcoding the urls in the project level urls.py like this: urlpatterns = [ url(r'^default/admin/', include(admin.site.urls)), # does not work url(r'^test/admin/', include(admin.site.urls)), # does not work url(r'^default/', … -
Django cant migrate due to an error regarding psycopg2
I have searched and still came up empty and this error has been holding me back for a while now hopefully someone can help. I made a database/models and migrated, everything worked fine until i made some changes to the models and wanted to remigrate to save the changes, however django wont migrate successfully and gives me this error: ValueError: Cannot quote parameter value of type class 'psycopg2._json.Json i do have the latest versions of pyscopg2 installed. What could be causing this and what additional info is needed to figure this out? -
Dynamic picklist items to avoid empty filtered queries (django-filter)
I've started using django-filter and it works absolutely great; i have this Filter that's going: I'm filtering through my Worldfood Object, and picking through related fields with dropdown picklists. The problem : i'd like to update the second picklist depending on what has been picked in the first. For example say i have a Worldfood object, I have very general country attribute French, Italian, USA, Mexican... etc. Then a sub family that is country-specific like say per city; linked to the first with a foreign key. Finally the food is city specific, (so linked to a country through something like city__country) With Django-filter i have two picklists, the first being the country, the second being the city. What is the best way to have the options from the city picklist depend on the selected one from the country ? Because for now its possible to choose USA / Shanghai which gives obviously no results. class WorldfoodFilter(django_filters.FilterSet): class Meta: model = Worldfood fields = ['city__country, 'city'] Thanks ! PS: there are similar posts about this, but i havent found one specific to the django_filter add-on -
How to update the file in the filefield in a django project
I have a model which has a filefield in a django project. The file is saved on Amazon S3 drive. I'm able to read the file without any problem. Now I need to read the updated file every night. The file is updated on S3 every night by another process, but django can't read the updated file. It's still showing the old file I uploaded. It seems django read the file from cache? How do I force django always read the file from S3 so I can get the updated file? class MyFile(models.Model): # fields my_file = models.FileField(null=True, blank=True, max_length=300, upload_to=file_path, storage=S3BotoStorage(location='files', acl='private'), help_text='link to a file') ... -
How can I upload a default file to django forms.FileFiled with a button
I am able to change the initial content of a forms.Charfield vie a button by applying the following code: forms: class fasta_file_handle_form(forms.Form): file_text = forms.CharField(widget=forms.Textarea(attrs = {'cols': '100', 'rows': '15'}), required = False, initial = '') file = forms.FileField(label='Select a file', required = False) view: def index (request, load_example = False): if request.method == 'POST': form = fasta_file_handle_form(request.POST, request.FILES) if form.is_valid(): #do something else: form = fasta_file_handle_form() if load_example == str(1): #can be triggered by calling the view from a button content = 'example text' form.fields['file_text'].initial = content return render_to_response('index.html', {'form':form}, context_instance=RequestContext(request)) Now, I would like to know, if there is a way to load an example file to the FileFiled as well, or if there can be an alternative approach to this matter. I could not find a way to implement a default input to FileField so far. -
Django queryset returns incorrect model instances but iteration works
I have a model that represents a rubric, and each rubric has multiple rows. For some reason, I run the query below, and I receive an incomplete queryset. The variable semesterrubric is a queryset of rubrics that has already been evaluated in the code and returns the correct rubric models. """ semesterrubric pulls both Rubric 1 and Rubric 2 Rubric 1: Row: 2 Row:4 Rubric 2: Row: 1 Row : 1 """ Row.objects.filter(rubric=semesterrubric) <QuerySet [<Row: 2>, <Row: 4>]> I know it's incomplete because when I iterate over the semesterrubric queryset object and pull the rows from each individual rubric, I receive two querysets with the rows that I need. [rubric.row_set.all() for rubric in semesterrubric] [<QuerySet [<Row: 2>, <Row: 4>]>, <QuerySet [<Row: 1>, <Row: 1>]>] I would like to have a single query that returns all of the rows. What am I missing? I've read (most of) the documentation on querysets, but it is possible I missed something. models.py class Rubric(models.Model): name = models.TextField(default="Basic Rubric", unique=True) template = models.BooleanField(default=True) def __str__(self): return self.name class Row(models.Model): CHOICES = ( ('0', 'Your string for display'), ('4','Exemplary'), ('3','Proficient'), ('2','Partially Proficient'), ('1','Incomplete'), ) name = models.CharField(default="None", max_length=100) rubric = models.ForeignKey(Rubric) row_choice = models.CharField(max_length=20,choices=CHOICES, default="0") excellenttext … -
Using reverse ParentalManyToManyField in ModelAdmin
Similar to my previous question, I'm trying to use the related model within ModelAdmin. This time, however I am using the new ParentalManyToManyField which seem to mess things up. I wrote the following structure: class B(Model): # or Orderable ... edit_handler = TabbedInterface([ ObjectList([ FieldPanel('aes', widget=CheckboxSelectMultiple), ], heading=_('Aes'), ), ]) class A(ClusterableModel): ... bees = ParentalManyToManyField( B, related_name='aes', blank=True, ) ... When trying to reach the page I receive a Field Error: Unknown field(s) (aes) specified for B Is what I'm trying to do not possible yet or did I forget a step? -
How to catch exceptions that happened in a python threading.Thread execution?
Basically I would like to receive an email using the Django mail_admins when a not handled exception happen inside a Thread. Currently, I have a view that handles post requests and it looks like that: import threading # ... def post(self, request, *args, **kwargs): # Some stuff... for message in entry['messaging']: t = threading.Thread( target=self.local_handler, args=(message, page_id) ) t.setDaemon(True) t.start() # Some more stuff Right now, when any Exception happens and it's not handled, it will be shown in the server log. Something like this: Exception in thread Thread-2: Traceback (most recent call last): ... Is there a way to receive those tracebacks by email? I was receiving emails before I started using threads, but now it's doesn't work anymore. -
Posting Json fails
Before all, this may not be a Django, PHP or ASP related problem. It seems to be related solely on Json, but they could help. I am trying to post json to a url. I tried Postman and Advanced Rest Client on Chrome with the following configs, both of them posted the data correctly. header: Content-Type = application/x-www-form-urlencoded body: username: 'myuser' password: 'sdas' . . . . The response is 200 OK, and the server returns a predefined code: 0, meaning success but when I change the content-type to something else, it returns error 24 meaning Illegal Access (it is different from invalid username/password). The same behavior happens on other clients on Firefox. When I use Rest Easy client on firefox, the server return 200 OK but it doesn't return 0, it returns error 24, no matter what the content-type is. This also happens when I try the following code in Django: url = "http://www.smsUrl.ir/api" data = {'username': 'user', 'password': 'pass', 'number': '100098', 'recipient': '0912345678', 'message': 'Hello', 'flash': 0, 'port': 0} # headers = {'content-type': 'application/x-www-form-urlencoded'} headers = {'content-type': 'application/x-www-form-urlencoded', 'Accept': 'text/plain'} r = requests.post(url, data=json.dumps(data), headers=headers) print data logger.error(r.text) # > this returns 24 Illegal Access It should give … -
Import error on python package inside django project
I am new to python and i have this django project, which actually has to communicate with a python package that my colleague has built. Let's say, the structure is as follows -Mydjangoproject -myapp -views.py -models.py -Mydjangoproject -settings.py -urls.py -manage.py -db.sqlite3 -colleagues_python_package -package1 -script1.py -script2.py -package2 -info1.py -info2.py When I try to run my colleague's script1.py which has the following code to import, from colleagues_python_package.package2 import info1 it throws me the error ImportError: No Module named colleagues_python_package.package2 If run in my colleague's system, this works. Is it because this package is not set in PYTHONPATH. How do I resolve this and explanation? ( and this package has to be inside django project) -
Django rest: AJAX Post is not working, 400 response
I am newbie to DRF and Ajax, my serializer code class CartItem(models.Model): cart_id = models.CharField('Cart ID', max_length=50) shop = models.ForeignKey(Shop) date_added = models.DateTimeField('Added on', auto_now_add=True) quantity = models.IntegerField('Quantity', default=1) product = models.ForeignKey(Products,) bylist = models.CharField('Item', max_length=150, null=True, blank=True) image = models.ImageField('Photo', upload_to='order/%Y',null=True, blank=True) image_thumb = ImageSpecField(source='image', processors=[Transpose(),ResizeToFill(200, 200)], format='JPEG', options={'quality': 95}) comment = models.CharField('Comment', max_length=150, null=True, blank=True) class ShopSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Shop fields = "__all__" class ProductsSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Products fields = "__all__" class CartItemSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = CartItem exclude = ('cart_id',) Trying to test the POST call with below json, but getting 400 - Bad request. Tried many different ways but couldn't solve. Please help function create_post(shop, pd) { jQuery.ajax({ type: "POST", beforeSend: function (request) { request.setRequestHeader("X-CSRF-TOKEN", "${_csrf.token}"); }, url: "/api/cart/", data: JSON.stringify({"shop":"http://127.0.0.1:8000/api/shop/1/","product":"http://127.0.0.1:8000/pd/10/",}), //console.log(data); success : function(result) { console.log("Success!"); } }); } Also Tried with json: var json = '{"shop":'+1+',"product":'+2+',"quantity": null,"bylist": "","image": null,"comment": "",}'