Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access mongo db data in django project?
I have two db in my django project. Default db mysql and secondary db mongodb. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'xyz', 'USER': 'root', 'PASSWORD':'1234', 'HOST':'127.0.0.1', 'PORT':'3306', }, 'mongo_db': { 'ENGINE' : 'django_mongodb_engine', 'NAME' : 'pets_info' } } how to get data from mongo db in django views. def get_pets(request): mongo_cursor = connections['mongo_db'].cursor() return HttpResponse("hi") -
Django/HTML: Send information through a button click?
On my page, I have a modal that pops up asking for a purchase confirmation. This modal can be triggered by 10 different button presses corresponding to each item in my "shop". If possible, I would like to make it such that the price of the item, {{ item.price }} is visible within the modal window. How would I send this information alongside the button press? Would I have to define 10 different modals? <!DOCTYPE html> {% extends 'base.html' %} {% load staticfiles %} {% block content %} <div class="row centre-v"> <div class="card shop-card"> <div class="card-block shop-clock"> <h3><span class="shop-tag">Shop</span></h3> {% if items %} {% for item in items %} <div class="alert alert-shop" role="alert"> <span class="shop-title">{{ item.perk }}</span> <span class="shop-cost"><button type="button" class="btn btn-primary btn-shop" data-toggle="modal" data-target="#shopModal">Buy:&nbsp;{{ item.price }}<img class="coin-img shop-coin" src="{% static 'assets/coin.png' %}" height="20px" width="auto"></button></span> <div style="clear: right;"></div> </div> {% endfor %} {% endif %} </div> </div> </div> <div class="modal fade" id="shopModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Purchase confirmation:</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> This will cost you {{ item.price }} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> … -
How add class to class to p elements which generated by linebreaks?
I user next line in my template: {{ description|linebreaks }} How to add the same class to all <p> elements which will be generate? -
How create a django model to filter by a foreign key field
I have two models which are connected by a foreign key. Book isbn - this is a unique value Order book_isbn - this should refer to Book's isbn above. How to introduce Order model the isbn of the Book as a foreign key. I want to query orders which have given isbn (i.e. filter Order objects where book_isbn = given_isbn ? -
Django Rest Framework - If condition Ignored
I created a end-point that returns a PDF. I have an condition to check if the asset exists, but that condition is always ignored. If the condition doesn't exist the end-point returns 500 not 404 as I want urls: url(r'^report/asset/(?P<pk>[0-9]+)$', api.DemoPDFView.as_view()), views.py from easy_pdf.views import PDFTemplateResponseMixin, PDFTemplateView class DemoPDFView(PDFTemplateView): template_name = 'reports/asset.html' pdf_filename = 'asset.pdf' def get_context_data(self, **kwargs): pk = kwargs['pk'] if not Asset.objects.filter(id=pk).exists(): Response(status=status.HTTP_404_NOT_FOUND) else: asset = Asset.objects.get(id=pk) project = asset.project.name id = asset.id name = asset.title return super(DemoPDFView, self).get_context_data( pagesize='A4', title='Asset', project=project, name=name, id=id, **kwargs ) the plugin is Available: http://django-easy-pdf.readthedocs.io/en/v0.2.0-dev1/ -
Django: use content_type of parent model for GenericTabularInline
In Django 1.8, I have a parent class and a child class, which are not abstract: class Parent(models.Model): ... class Child(Parent): ... and I have another model, which has a GenericForeignKey: class Tags(models.Model): ... content_type = ... object_id = ... content_object = GenericForeignKey(...) ... Now I want to build ParentModelAdmin and ChildModelAdmin such that both show the same list of tags as an inline (TagsGenericTabularInline). How can I achieve that? -
Running Celery as Daemon with Supervisor and Django on Elastic Beanstalk
I am attempting to get Celery to run on an EB environment with Django and I have gotten super close to getting it all running. I have this config file for supervisor #!/usr/bin/env bash # Get django environment variables celeryenv=`cat /opt/python/current/env | tr '\n' ',' | sed 's/export //g' | sed 's/$PATH/%(ENV_PATH)s/g' | sed 's/$PYTHONPATH//g' | sed 's/$LD_LIBRARY_PATH//g'` celeryenv=${celeryenv%?} # Create celery configuraiton script celeryconf="[program:celeryd-worker] ; Set full path to celery program if using virtualenv command=/opt/python/run/venv/bin/celery worker -A unite --loglevel=INFO directory=/opt/python/current/app user=ec2-user numprocs=1 stdout_logfile=/var/log/celery-worker.log stderr_logfile=/var/log/celery-worker.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 600 ; When resorting to send SIGKILL to the program to terminate it ; send SIGKILL to its whole process group instead, ; taking care of its children as well. killasgroup=true ; if rabbitmq is supervised, set its priority higher ; so it starts first priority=998 environment=$celeryenv,USER="ec2-user" [program:celeryd-beat] ; Set full path to celery program if using virtualenv command=/opt/python/run/venv/bin/celery beat -A unite --loglevel=INFO --workdir=/tmp -S django directory=/opt/python/current/app user=nobody numprocs=1 stdout_logfile=/var/log/celery-beat.log stderr_logfile=/var/log/celery-beat.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase … -
Django CMS - DIVIO LogEntry add instance / Latest files added to the CMS
I need to show at my Homepage a list with all the files added/changed as Bootstrap Filer plugin to my Django CMS project. I was using the LogEntry model, but it doesn't save Add actions to LogEntry instances. What I need is something like that: Latest Changes: May 30, 2017 - Test.pdf May 28, 2017 - Application Form.pdf May 26, 2017 - Brooker.pdf My problem is that the Add's actions are not saved at LogEntry model... Every time I add, for example, Bootstrap Filer Plugin and add a PDF it doesn't save a new Entry instance of it, only when I delete it. How do I change the default behavior to save Plugin's Add Actions (specially Bootstrap Filer File) at LogEntry Models? The website is a platform to help insurance brokers to sell. The prices of different companies changes on monthly basis. And every time a new Price table change I need to show in a Latest changes / updates section. My models.py poll = list(LogEntry.objects.all()) def __unicode__(self): return unicode(self.poll) My template: <ul> {% for poll in instance.poll %} {% if poll.content_type_id == 54 %} <!-- Bootstrap Files Plugin Content Type --> <li> {{poll.action_time.date }} - {{ poll.object_repr }} - … -
Django updating a model with a many-to-many field
I am trying to make a post editor for my website. When I trigger the post model I receive the error "Cannot update model field (only non-relations and foreign keys permitted)." when updating. How do I update this model? def post(self, request, pk): if (not request.user.is_superuser): return HttpResponseForbidden() post = Post.objects.get(id=pk) if (post is None): return HttpResponseNotFound() form = self.form_class(request.POST, instance=post) if (form.is_valid()): title = form.cleaned_data['title'] content_type = form.cleaned_data['content_type'] screenshot = form.cleaned_data['screenshot'] tags = form.cleaned_data['tags'] body = form.cleaned_data['body'] nsfw = form.cleaned_data['nsfw'] allow_comments = form.cleaned_data['allow_comments'] files = form.cleaned_data['files'] date_edited = datetime.now() Post.objects.filter(id=pk).update(title=title, content_type=content_type, screenshot=screenshot, tags=tags, body=body, nsfw=nsfw, allow_comments=allow_comments, files=files, date_edited=date_edited) return redirect('/posts/' + str(post.id)) else: return HttpResponseNotFound() return HttpResponseNotFound() -
Django 1.11 built-in and custom widget template locations
I am trying to write a custom widget the "new way" with Django 1.11's new form/widget rendering functionality, and am very confused due to the lack of examples and well, subpar documentation: From the Django docs: Each widget has a template_name attribute with a value such as input.html. Built-in widget templates are stored in the django/forms/widgets path. You can provide a custom template for input.html by defining django/forms/widgets/input.html, for example. I am unclear on the location it is referring to. Does this mean in my venv/lib/python2.7/site-packages/django/forms/ directory, I'm supposed to create a new directory called widgets/ and put my templates there? Because that makes no sense. Or am I supposed to create the django/forms/widgets/ directory under my project directory and put my new templates there? -
Django Celery task.state PENDING even when it stated
I am having my Celery settings in my settings.py. I have set CELERY_TRACK_STARTED to True. I have added time.sleep(20) to my task to check whether AsyncResult.state would return STARTED. That is not the case, it always returns PENDING. What did I do wrong? When task is finished it returns SUCCESS as intended. Any help appreciated. -
Linking Authorisation Server and Client Application in Django with OAuth2
I have made two independent projects in Django one which works as an Authorization & Resource server(ie OAuth2 provider) and another one is a client application with simple register and login.I am trying to link these two applications but I am unable to do that. These two work fine independently. I can fetch access token from Auth server and then use it to access data.While login app also works fine. I don't know what packages to be imported to settings.py of the client application to link with my own Auth server. And how to generate links for authorization. I have made OAuth server with help of this tutorial but I am unable to link it with simple login application. I am using Django 1.11 -
Deploying Django app to Heroku via CircleCI: How to migrate database?
How can I run python manage.py makemigrations and python manage.py migrate automatically when deploying a Django app to Heroku via CircleCI. It seems all commands run local to CircleCI, but not on the deployed application in production. Is there a way? -
"Django, Pyramid, TurboGears, Flask" finally what and why? [on hold]
I still have no definite idea to choose between Django and Pyramid!!! or even other frameworks such as Flask, TurboGears2 and etc. in my opinion using python web frameworks is not very popular as PHP or other commercial ones yet, so why not focusing on one of them in order to have a very huge community of these web frameworks and easier to find developers in them. if the question seems stupid please ignore it but someone makes me clear their real pros and cons! -
How to utilize python script in DJANGO
Good day, I have built a python parser that lets the user enter certain search parameters and then searches through a set of syslogs looking for specific information. When there is a match it writes the lines to a separate text document so that the user can review/save the output. All works great, but as of now its all done via CLI on a local PC. The next step in my project I want to be able to host a web server whereby users can upload their syslogs from their PC to a front end website, and have my python parser do a search based on their search parameters and then print the result to the webpage. Is this possible? I have been playing with DJANGO a bit, but its becoming clear that this might not be the best route to go. Any advice welcome. Thank you in advance. -
Django: correctly serialize custom authentication backend
I have a custom authentication backend in Django 1.10. If I login, I get TypeError: <class 'CustomAuthBackend'> is not JSON serializable. I can make the entire process work by putting SESSION_SERIALIZER='django.contrib.sessions.serializers.PickleSerializer' in settings.py, but, as pointed out in many old questions, PickleSerializer is unsafe and I need a better method. How do I write a correct serializer for my authentication backend? I tried using some code from https://github.com/caffeinehit/django-oauth2-provider/pull/56/files (adding serialize() and deserialize() to my authentication backend class and having serialize_instance() and deserialize_instance as separate functions). I cannot get this approach to work, any advice? -
Django Migrations: Forgetful memory on models
I have deleted all migrations in my django_migrations relating to an app 'straightred' and removed the 'migrations' folder within the app to. Now, when I run 'python manage.py makemigrations straightred' everything goes as planned. Because I know all the tables are in the database I then run 'python manage.py migrate --fake straightred' and get the following: (str8RED-virtualenv) tingeyal@str8RED:/usr/share/str8RED$ python manage.py migrate --fake straightred System check identified some issues: WARNINGS: ?: (1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 and the TEMPLATES dictionary takes precedence. You must put the values of the following settings into your default TEMPLATES dict: TEMPLATE_CONTEXT_PROCESSORS. Operations to perform: Apply all migrations: straightred Running migrations: Rendering model states... DONE Applying straightred.0001_initial... FAKED (str8RED-virtualenv) tingeyal@str8RED:/usr/share/str8RED$ So far everything has gone as planned. Now, if I was to try to change the name of a field within one of the tables and then run 'python manage.py makemigrations straightred' again all I ever get is: (str8RED-virtualenv) tingeyal@str8RED:/usr/share/str8RED$ python manage.py makemigrations straightred System check identified some issues: WARNINGS: ?: (1_8.W001) The standalone TEMPLATE_* settings were deprecated in Django 1.8 and the TEMPLATES dictionary takes precedence. You must put the values of the following settings into your default TEMPLATES dict: … -
How to pass parameter values in Django?
My goal is to have the user enter their username and password which is then checked in a database to see if it is correct or not to allow them to login or be denied access. Currently, I have it setup so that they are asked for their information in an html page that then calls the url of the user authentication page which then goes to the views file where it then checks the database for a match. I have some code written up, but I keep running into errors and I can't seem to figure out how to fix it. Is this even the right setup for checking user information even the correct way to go about it in the first place or is there another way that is more effective in doing so? Here's my code as of now. HTML Page: function getUserInfo() { username = document.getElementById("username").value; password = document.getElementById("password").value; "{% url 'user_authentication' %}" } urls.py: urlpatterns = [ url(r'^user_authentication/$', views.user_authentication, name='user_authentication'), ] views.py: def user_authentication(request): username = request.GET.get('username') password = request.GET.get('password') if (username == "Stack" and password == "Overflow"): return render(request, 'next url goes here') I tried to use GET, but that doesn't work. I don't … -
DJANGO 1.1 dynamic url on static javascript
Context I am adding a static javascript file to my ModelForm on this way forms.py class SomeForm(forms.ModelForm): class Media: js = ('some-javascript.js',) Problem On this javascript i need send a GET request to a rest endpoint using jquery but i need the Server domain or a function to construct my url some-javascript.js, django.jQuery.get('{% url "validate_username" %}') expect behavior If I could create my url with django I could send the request without problems, Thanks in advance -
python fun function not called [on hold]
I am not new to python django. Today I encountered a strange performance of a forms.py and can not figure out why. My code structure is simple as below: def method1(): .... print var1 def method2(): ... print var2 class FormaA(forms.Form): ... I plan to test method1, but when I accidentally run the script before adding if __name__ == '__main__', and then the method2 seems executed. I got the var2 value printed out. This is strange and I have no idea how to check what is happening. Any one has any idea? -
Filter on distinct queryset pulls values ommited by 'distinct on' query - PostgreSQL
I have a large inventory of vehicles that I retrieve distinctly by their model number. Users can filter the vehicles by condition (New or Used). However in the backend, something strange happens. The distinct queryset's count is 683, and there are only two possible values for the condition, new and used. When filtering used vehicles though, I get 186, and when filtering new vehicles I get 521, 707 in total. I thought "Why is the number of new, and used together equal more than the original count". After further debugging, I found that even after doing a 'distinct on model_no', the new filter is pulling vehicles with a model number that should have been omitted in the distinct on query. Is the new filter somehow messing up the 'distinct on' View def search_listings(request): # Start searching all_listings = Inventory.objects.all().distinct('model_no') # This is what I did to find out there were extra model numbers coming in master_test_list = [] master_model_no = [] new_list = [] new_listings = all_listings.filter(condition='N') used_listings = all_listings.filter(condition='U') for item in all_listings: if item.id not in master_test_list: master_test_list.append(item.id) master_model_no.append(item.model_no) for item in new_listings: if item.id not in master_test_list: new_list.append(item) for item in used_listings: if item.id not in master_test_list: … -
Django - How can i limit the number of objects that a user can create?
(first of all sorry for my bad english) I need to know if i can limit the number of objects that a user can create in a specific model, taking the number of object admited to create from the user profile. I go to try to explain this. i have this model class StoreBranchOffice(models.Model): store = models.ForeignKey( Store, verbose_name=_('store') ) name = models.CharField( max_length=30, verbose_name=_('name'), ) email = models.EmailField( blank=True, verbose_name=_('email'), ) phone = models.CharField( max_length=15, verbose_name=_('phone'), ) address = models.CharField( max_length=100, verbose_name=_('address'), ) Well, in the userprofile, i have a field that have the number of branch office admited for the user... Well i need to check if the user try to create a brach office if have admited create brach office or if the user already have the maximum of branch offices admited! Thanks very much!!! -
Django settings are not loaded when running tests
I have different settings for different environments for my application, such as local, dev, stage, production. So, when I run my apps, say, locally, I pass the settings as the parameter to manage.py, e.g. python3 manage.py runserver 0.0.0.0:8080 --settings=myapp.settings.local, and indeed all my settings are correctly initialised, e.g. DEBUG is True as it is set in my settings file, and not False as it is in defaultsettings.py. However, when I try to run tests with python3 manage.py test --settings=myapp.settings.local, the value of DEBUG is set to false, that is it is loaded from defaultsettings.py. Why does that happen and how can I fix this? -
Django `update_last_login` always providing lastest time. not last login time
I have logged into my site 1 days ago but today when I log into my site, it is showing today date in user.last_login, user.last_login should have yesterday date. code location. https://github.com/django/django/blob/a3ba2662cdaa36183fdfb8a26dfa157e26fca76a/django/contrib/auth/models.py#L20 I have also reported to Django(https://code.djangoproject.com/ticket/28256) -
Django registration of tag library not working
I try to register my custom template tag library in django, but unfortunately it isnt working! I want to create a custom include-tag and followed the instruction at: https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/#howto-custom-template-tags-inclusion-tags I have created an app called 'tag_lib' to put my template tags in and registered it in settings.py. In the app folder is a dictionary called 'templatetags' containing an empty __init__.py and my my_tags.py. my_tags.py contains: from django import template register = template.Library() @register.inclusion_tag(filename='navbar.html', takes_context=True) def navbar_context(context): return { 'some_var': context['some_var'], } When I restart my devserver and try to load the library with {% load my_tags %} ` in a template, I'm getting the error:` TemplateSyntaxError at / 'my_tag' is not a registered tag library. Must be one of: admin_list admin_modify admin_static admin_urls cache i18n l10n log static staticfiles tz Any idea where I made a mistake? Thanks.