Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create POST by ID in Django
I wonder how can I create object POST using users ID. Let's assume that I would like to have such URL /users/{id}/object and I would like to create object for user with defined ID, for example user with ID equals 1. In views I would have something like this - url(r'^users/(?P<myID>[0-9]+)/object/$', views.UserObject) Furthermore my object looks in this way { "id": 2, "id_users": 1, "sth": 123 } My GET: @api_view(['GET', 'POST']) def UserObject(request, myID=None): try: object = Object.objects.get(id=myID) except Object.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = ObjectSerializer(object) return Response(serializer.data) -
AppRegistryNotReady: Apps aren't loaded yet
The old app works fine and I want to deploy a new one. I want them working seperately in its own virtualenv. The new one is just a empty project just been created [[15~[Mon May 22 23:28:33.243554 2017] [:error] [pid 11944:tid 140222385792768] [client 106.185.52.15:27772] mod_wsgi (pid=11944): Exception occurred processing WSGI script '/home/zzm/mysite/mysite/wsgi.py'. [Mon May 22 23:28:33.243786 2017] [:error] [pid 11944:tid 140222385792768] [client 106.185.52.15:27772] Traceback (most recent call last): [Mon May 22 23:28:33.243893 2017] [:error] [pid 11944:tid 140222385792768] [client 106.185.52.15:27772] File "/var/www/.virtualenvs/test/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 158, in __call__ [Mon May 22 23:28:33.244008 2017] [:error] [pid 11944:tid 140222385792768] [client 106.185.52.15:27772] self.load_middleware() [Mon May 22 23:28:33.244092 2017] [:error] [pid 11944:tid 140222385792768] [client 106.185.52.15:27772] File "/var/www/.virtualenvs/test/lib/python2.7/site-packages/django/core/handlers/base.py", line 51, in load_middleware [Mon May 22 23:28:33.244182 2017] [:error] [pid 11944:tid 140222385792768] [client 106.185.52.15:27772] mw_class = import_string(middleware_path) [Mon May 22 23:28:33.244270 2017] [:error] [pid 11944:tid 140222385792768] [client 106.185.52.15:27772] File "/var/www/.virtualenvs/test/lib/python2.7/site-packages/django/utils/module_loading.py", line 20, in import_string [Mon May 22 23:28:33.244351 2017] [:error] [pid 11944:tid 140222385792768] [client 106.185.52.15:27772] module = import_module(module_path) [Mon May 22 23:28:33.244430 2017] [:error] [pid 11944:tid 140222385792768] [client 106.185.52.15:27772] File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module [Mon May 22 23:28:33.244523 2017] [:error] [pid 11944:tid 140222385792768] [client 106.185.52.15:27772] __import__(name) [Mon May 22 23:28:33.244601 2017] [:error] [pid 11944:tid 140222385792768] [client 106.185.52.15:27772] File … -
convert Mysql query to Django ORM
I'm using Mysql view and then I want to use mysql view query at Django. but I don't know how to convert query to django orm.. select H.eqp_id AS eqp_id, H.eqp_ip AS eqp_ip, (case when (H.server_time > (now() - interval 1 minute)) then '1' else '0' end) AS isAlive, H.eqp_time AS eqp_time, H.server_time AS server_time, (case when (H.ftp_status = 'true') then 'OK' else 'NOT OK' end) AS ftp_status, H.config AS config from (collect_manager.heartbeat_history H join (select collect_manager.heartbeat_history.eqp_id AS eqp_id, max(collect_manager.heartbeat_history.index) AS max_index from collect_manager.heartbeat_history group by collect_manager.heartbeat_history.eqp_id) H2 on((H.index = H2.max_index))) thanks.. -
How to display rows of csv file in django?
I have a django app, which allows the user to upload a csv file, say a csv file of rankings of universities. I'd have to process the data that has been uploaded. For example, grey out any column which has string values and calculate the mean and std. deviation of all the values of a column. For this, I am using Pandas and converting the csv file to a pandas dataframe. How do I display the dataset from the csv file using django? The column names cannot be hard coded because the user may upload any csv file. I checked django-tables2 and did the following csvfile = request.FILES['csv_file'] data = pd.read_csv(csvfile.name) context = {'loaded_data': data} return render(request, "dataflow/table.html", context) but I get the error ValueError: Expected table or queryset, not DataFrame -
Django Validation: skip a field validation given a specific value
I have a form that has several unique fields that become readonly during edit. There are no problems during creation. Unfortunately the ModelForm.is_valid() method catches these and still validates during edit. My model is a simple Django object with its form: from django import forms from .models import Sample class SampleForm(forms.ModelForm): class Meta: model = Sample fields = "__all__" The view method is just a simple save() if is_valid() is true otherwise show the error messages. I manually setup the form in the view file/I do not use the auto-generated form structure by ModelForm. In node.js, I just have this simple validation to catch these (the field slug for example): isSlugUnique(slug, operation) { return new Promise((resolve, reject) => { Sample.findOne({ slug: slug }, (err, sample) => { if(err) throw err; if(sample === null) { resolve(); } else if(slug === sample.slug && operation === 'edit') { resolve(); } else { reject(); } }) }) }, It has a catch to skip the validation if the slug attribute is not unique and the form operation is editing. I tried catching it alongside my is_valid() method (the error message for existing fields is of the pattern "[Model] with this [Field] already exists." so … -
Trouble loading Django App after testing other Django App for several days? Always redirects to requested URL that doesn't exist?
Over the weekend I attended a hackathon, at which I created a Django app that ran on 127.0.0.1:8000/myapp/list on my local machine with python manage.py runserver Today, I tried to launch another Django app that I had made in the past for bug fixes and things, but when I ran manage.py runserver it keeps redirecting me to 127.0.0.1:8000/myapp/list, even though it's a totally separate app. Anyone know how to resolve this issue? urls.py for Django app that I'm trying to run: from django.conf.urls import url from TweeTest import views urlpatterns = [ url(r'^$', views.view_home, name='home'), url(r'^about/$', views.AboutPageView.as_view()), url(r'^contact/$', views.ContactPageView.as_view()), url(r'^result/$', views.view_tweet, name = 'result'), ] urls.py for Django app I made over the weekend: from django.conf.urls import include, url from django.conf import settings from django.conf.urls.static import static from django.views.generic import RedirectView from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^myapp/', include('myproject.myapp.urls')), url(r'^$', RedirectView.as_view(url='/myapp/list/', permanent=True)), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Is it something to do with the RedirectView line in the second urls.py? I'm not sure why a totally different Django app is trying to connect to the same URL as the other one... seems strange. If someone knows the answer to this, that would be greatly appreciated! Thanks! UPDATE: When … -
I need help building a web app with python code
I'm trying to build an app that run python code and outputs JSON files with data. My need is that the python code is always running and updating the output, just don't know how to do it. Now, with that done, I want to have a website that displays my data and only I can access it. With login and password is the correct way to build it? It needs to be hosted online, it can't be local. I've research and found out that I should use Django to create my app, but don't really see the purpose of it. I want to host it somewhere, maybe in Amazon AWS. I want to know the best way to do this and the technologies that are most appropriate for it. If you could help me out on this. What do you think of it? How would you do it? -
Allow access to page with Recaptcha on Django website
What would be the code approach to allow access to only human beings to see the page with Recaptcha? After loading the page only Recaptcha validator would appear, after successful validation, the user can see that page. I can use this package https://github.com/ImaginaryLandscape/django-nocaptcha-recaptcha, but if you know better for this example, would be great. There is also new approach with invisible Recaptcha, not sure which approach is the best and how to implement it. https://developers.google.com/recaptcha/docs/invisible All example approaches are done with forms, logins etc, not sure how to do it that you can see the page only when you validate the recaptcha Have sample HTML page <html> <body> <h1>Sample Page</h1> #... more html code </body> <!-- Scripts --> <script src="https://www.google.com/recaptcha/api.js" async defer></script> </html> views.py def sample_page(request): return render(request, 'sample_page.html', {}) urls.py urlpatterns = [ url(r'^sample-page/', app_vies.sample_page, name='sample'), ] -
Using a variable while defining another variable for a model in django
Basically what I want to do is this: class A(models.Model): a_number = models.FloatField() class B(models.Model): a = models.ForeignKey(A) b = models.FloatField(default=self.a.a_number) I understand I can't use self while defining the variables, but is there a workaround for this? What if 'a_number' was a method instead of a variable? I know i could make a method like this in B: def b(self): return self.a.a_number But I need to get the value of 'a_number' right as I create the object in B so this wouldn't work. -
Is it possible to create multiples forms with one view
I would like to create a comment form for each attribute of my model. Usually, I would have a view and one form for each model attribute. The thing is that for 30 attributes I don't want to create 30 forms and 30 views. Is there a way to create one view and one form for all attributes then have a comment form for each attribute? My model is: class Project(models.Model): attribut1 = models.IntegerField(choices=PROJECT_STATUS,default=1) attribut2 = models.IntegerField(choices=PROJECT_STATUS,default=1) attribut3 = models.IntegerField(choices=PROJECT_STATUS,default=1) attribut4 = models.IntegerField(choices=PROJECT_STATUS,default=1) attribut5 = models.IntegerField(choices=PROJECT_STATUS,default=1) attribut6 = models.IntegerField(choices=PROJECT_STATUS,default=1) attribut7 = models.IntegerField(choices=PROJECT_STATUS,default=1) My form is: class ScopeForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ScopeForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].required = False class Meta: model = Project fields = ['project_scope',] -
python manage.py runserver not working on powershell
Whenever I am running python manage.py runserver on powershell, it shows python : [23/May/2017 02:16:02] "GET / HTTP/1.1" 200 1716 At line:1 char:1 + python manage.py runserver + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: ([23/May/2017 02...P/1.1" 200 1716:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError Not Found: /favicon.ico [23/May/2017 02:16:02] "GET /favicon.ico HTTP/1.1" 404 1963 Can you tell me what's the error? -
How to create related object in the update page of the object
Kindly help me with the tips how to implement the following: I have simple Post model and a Tag model which is many-to-many field for Post. Nothing special, all as usual. But what I need to implement is to have an ability to create another Tag on CreatePost and UpdatePost pages without lost any Post data which I might enter in PostForm. Also without any frontend Ajax patterns. For better understanding here is the picture So again: Here is the form. I've entered title, body and chosen the Tag from the existed list. I've realized that I don't have the needed Tag for my Post so I'm putting the new one in the corresponding field, pressing submit. After that, I'm receiving the same page with the same Post data that I've already entered. I'm choosing the new Tag from the list and press save. The difficulties are that forms for Post and Tag creation are separate and therefore they correspond to different model views and so on. Does anyone know the simple and clean solution? Thanks. -
Django 1.10 Upgrade Issue
I have the following which worked in Django 1.9.6: # Get Django to serve media files in debug mode. if settings.DEBUG: urlpatterns += [url(r'^resources/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT})] if not settings.DEBUG: urlpatterns += [ url(r'^resources/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), ] Having a good look round suggest that In 1.10, you can no longer pass import paths to url(), you need to pass the actual view function. However, in this instance I am unsure how to progress this as I get the error: view must be a callable or a list/tuple in the case of include(). Any help is always appreciated. -
Django: Upgrading to python3.6 with Amazon S3
I was running Django 1.11 with Python 3.5 and I decided to upgrade to Python 3.6. Most things worked well, but I am having issues connection to AWS S3. I know that they have a new boto version boto3 and that django-storages is a little outdated, so now there is django-storages-redux. I've been trying multiple combinations of boto/boto3 and django-storages-redux/django-storages to see if it works. But I'm getting a lot of erros, from SSL connection failing to the whole website being offline due to server errors. The newest is my website throwing a 400 Bad Request to all urls. My app does run on Python 3.5, so I'm confident that the issue is around collectstatic and S3. Is there anybody here who made a similar update work and tell me what configuration was used? Thanks a lot! -
How to add a scss file to a django template tag?
I have the following template tag inside templatetags: from django import template register = template.Library() @register.inclusion_tag('pledges/dismissible_message.html') def dismissible_message(bold_text, normal_text, success=True): return {'bold_text': bold_text, 'normal_text': normal_text} and the HTML file that I pass in the method inclusion_tag() is: <div role="alert" class="alert alert-dismissible pledge-error"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true" style="color: white">×</span> </button> <i id="exclamation-mark" class="fa fa-exclamation-circle" aria-hidden="true"></i> <p style="display: inline;vertical-align: middle"><strong>{{ bold_text }}</strong> {{ normal_text }}</p> </div> I need to apply some styles to this HTML, but I don't want to put the styles in the same file than the file where the template tag is called, so my question is how can I associate a CSS or SCSS file such as dismissible_message.css/dismissible_message.scss to this template tag? -
Django file upload with Non-ASCII chars dropped
I am uploading a file to my Django model with unicode characters in the filename, however when the name is shown, they are dropped or changed to the closest ascii character. I checked the upload path function, and at this point it is still correctly encoded. -> return u'proposal_documents/{0}/{1}'.format(instance.proposal.pk, filename) (Pdb) x = u'proposal_documents/{0}/{1}'.format(instance.proposal.pk, filename) (Pdb) x u'proposal_documents/22872/\xa9\u02da\u2206\u222b\u02dau\u0308\u2122\xa2.png' I also have checked the file's cleaned data, and the file is correctly represented there as well. -> for file_ in pdform.cleaned_data['files']: (Pdb) pdform.cleaned_data['files'] [<InMemoryUploadedFile: ©˚∆∫˚ü™¢.png (image/png)>] However, inspecting the model, the non-ascii characters have been changed. (Pdb) models.ProposalDocument.objects.order_by('-created_at') <QuerySet [<ProposalDocument: u.png>, ... this is reiterated in the model instance's file path (Pdb) models.ProposalDocument.objects.order_by('-created_at').first().file.name u'proposal_documents/22872/u.png' Below is the model (with import pdb; pdb.set_trace() removed) def proposal_doc_upload_path(instance, filename): return u'proposal_documents/{0}/{1}'.format(instance.proposal.pk, filename) class ProposalDocument(models.Model): proposal = models.ForeignKey(Proposal, on_delete=models.CASCADE, related_name='documents') file = models.FileField(upload_to=proposal_doc_upload_path, max_length=500, blank=True) created_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(Employee, on_delete=models.CASCADE) def __str__(self): return self.file.name.rsplit('/')[-1].encode('utf-8') How do I alter my code so that unicode characters are kept unchanged? I am using Django 1.10 and Python 2.7 -
modify unique_together constraint to save new object and delete old
I have a model with a unique_together constraint on four fields. Instead of raising the normal Validation Error, however, I want to delete the old object and replace it with the newer one (or maybe update the old one? would also work). I'm a little at a loss as to how to go about doing this, or if there's maybe a better way to go about achieving this behavior. -
When are django update view model fields set?
In my views, I have subclassed the generic UpdateView, and there I have overridden the form_valid method. If I check the self.object 's field values in the form_valid method, they appear to be the new ones, although self.object = form.save() hasn't been executed. So, what am I missing, if the field values don't change in the form.save() part, when do they? Here is my code: def form_valid(self, form): print(self.object.title) return self.render_to_response(self.get_context_data(form=form)) -
How do you test a method in django that delegates tasks within itself?
Say I have 2 celery tasks: @app.task(name='process_one_line') def process_one_line(line): do_alot(line) @app.task(name='process_one_file') def process_one_file(file_id): for line in get_file_by_id(file_id): process_one_line.delay(line) and say I have a TestCase that looks like this: def test_processing_a_file(self): process_one_file(self.file_id) This will run fine, but the delegated process_one_line methods actually get pushed off to my other celery instance outside of the test cases. In short, my redis server running on port 6379 receives the tasks, and then pushes them off to the "main" workers. So whatever changes do_alot makes, they get reflected in the actual database instead of the test database created when you run django tests. I can test things by having it test process_one_line by itself, but it would be nice if I could test the whole thing altogether. -
Django & Apache Internal Server Erro
I have updated to Django 1.11.1 and now nothing on my site seems to be working. I have checked the logs which shows: [Mon May 22 21:04:21.055295 2017] [wsgi:error] [pid 3394:tid 140458274965248] [remote 88.106.125.154:9733] mod_wsgi (pid=3394): Target WSGI script '/usr/share/str8RED/dwad/wsgi.py' cannot be loaded as Python module. [Mon May 22 21:04:21.055358 2017] [wsgi:error] [pid 3394:tid 140458274965248] [remote 88.106.125.154:9733] mod_wsgi (pid=3394): Exception occurred processing WSGI script '/usr/share/str8RED/dwad/wsgi.py'. [Mon May 22 21:04:21.055385 2017] [wsgi:error] [pid 3394:tid 140458274965248] [remote 88.106.125.154:9733] Traceback (most recent call last): [Mon May 22 21:04:21.055415 2017] [wsgi:error] [pid 3394:tid 140458274965248] [remote 88.106.125.154:9733] File "/usr/share/str8RED/dwad/wsgi.py", line 9, in <module> [Mon May 22 21:04:21.055485 2017] [wsgi:error] [pid 3394:tid 140458274965248] [remote 88.106.125.154:9733] application = get_wsgi_application() [Mon May 22 21:04:21.055499 2017] [wsgi:error] [pid 3394:tid 140458274965248] [remote 88.106.125.154:9733] File "/usr/share/str8RED-virtualenv/lib/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application [Mon May 22 21:04:21.055640 2017] [wsgi:error] [pid 3394:tid 140458274965248] [remote 88.106.125.154:9733] django.setup(set_prefix=False) [Mon May 22 21:04:21.055657 2017] [wsgi:error] [pid 3394:tid 140458274965248] [remote 88.106.125.154:9733] File "/usr/share/str8RED-virtualenv/lib/python2.7/site-packages/django/__init__.py", line 27, in setup [Mon May 22 21:04:21.055985 2017] [wsgi:error] [pid 3394:tid 140458274965248] [remote 88.106.125.154:9733] apps.populate(settings.INSTALLED_APPS) [Mon May 22 21:04:21.056001 2017] [wsgi:error] [pid 3394:tid 140458274965248] [remote 88.106.125.154:9733] File "/usr/share/str8RED-virtualenv/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate [Mon May 22 21:04:21.056445 2017] [wsgi:error] [pid 3394:tid 140458274965248] [remote 88.106.125.154:9733] app_config.import_models() [Mon … -
The best model to function call into db
I have some sort of a Tasks in my project. Task and its parameters later will be constructed into a function call. Now my Task model looks like: class Task(TimeStampedModel): ACTIVE = 1 COMPLETED = 0 FAILED = -1 STATUS_CHOICES = ( (ACTIVE, 'Active'), (COMPLETED, 'Completed'), (FAILED, 'Failed'), ) ACTION1 = 1 ACTION2 = 2 ACTION3 = 3 ACTION_CHOICES = ( (ACTION1, 'Action1'), (ACTION2, 'Action2'), (ACTION3, 'Action3'), ) status = models.SmallIntegerField(choices=STATUS_CHOICES, default=ACTIVE) action = models.SmallIntegerField(choices=ACTION_CHOICES, default=ACTION1) date_completed = models.DateTimeField(null=True, blank=True) Later I will create Task object and depending on its action call a particular function. For example, if task.action == 1 I will call some_module.action1(). I am curious on how I can store arguments that can be passed to a function (some_module.action1(arg1, arg2)) if I am not sure what they will be in the future. So, if it is possible to say so, I want store some sort of a dictionary on function kwargs as my field. What's the best way to archive what I want? -
Chrome Web Notification Push Unauthorized Registration exception
I am implementing push notifications from my server to the users who are subscribed to my server. Right now sending the push notifications to Firefox users works like a charm. However, on Chrome I get an Unauthorized Registration error. I am using Django as a backend. In this image are the relevant parts of the error and my code (email edited), aswell as the subscription. If any more information is needed please let me know. Does anyone know why I can't send push notifications on Chrome? And I am using this library. -
Django-notification set up issue
I'm quite new to django and i've just installed django-notifications into my project. Now I've set it up, installed it and added this signal notify.send(request.user.profile, recipient=pending_like, verb='Sent you a friend request', action_object=request.user.profile) this works perfectly when some likes another user, so i then have a look in /inbox/notifications/ and i see the notification " tomsmith Sent You a Friend Request 1 minute ago None " So it works perfectly, however how do i make it so that tomsmith is clickable and the person viewing it can click on the name to go to his profile? Is this the action object? also what does the None stand for? sorry if this is confusing but i cant get my head around it. I have a profile app under under the name profiles with this model, class Profile(models.Model): user = models.OneToOneField(User) location = models.CharField(max_length=120, choices=ERASMUS_LOCATIONS,null=True, blank=True) picture = models.ImageField(upload_to=upload_location, null=True, blank=True) Thank you in advance for any help. -
Can not install pyaudio
I am trying to install PyAudio inside my webfactionserver. It gives me the following error. I got the same error while installing it locally but I read the solution and the sudo command solves it. The problem is webfaction does not allow the sudo command. What I have tried is that I copied my pyaudio local installation from site-packages folder to my online production server. If i do pip freeze it shows me that it is installed. I tried running my function which uses PyAudio but it gives me the error " Could not find PyAudio.Check installation" -
Delete some data from column on based of table values in database Django
I am developing a scenario in which I get some data in form of tables. Like 30 maps data. Now I have make a field in database in this table like this my_map = models.BooleanField(Default=False) So all values are initially False. Now When I will perform a hide function in django template on button. Value of this field will become true and that specific Id carrying map will hide. I am confuse how I will make view.py which will check every time if value changed to true and will hide it ?