Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
mock.patch queryset in mongoengine
In my django unittest, i want to mock out a Document Class in model.py for specifing custom their return_value of objects.all() and objects.all().first() of the Document. Like, there is a TestDocument Class in models.py and a caller function named test_doc_mock in test_mock.py. test_mock.py: def test_doc_mock(): all_set = TestDocument.objects.all() first_one = all_set.first() return all_set,first_one in testcase, i want to know how to write successful test for the func above,thus it can returns my specific value. -
exposing data with django form get request
I'm building a small form on which I'm displaying some data in the table, addition to that I have two dropdown, with which you can select current data or year for the data you want to see in the table. My question is how can I populate dropdown with current month and year, using django form get request, I'm little confused how to process this in my view, note that I'm using CBV FormView. I've tried something like this form.py from django import forms import datetime class StatisticsForm(forms.Form): """TODO: Simple form with two field, one for year other for month, so user can list Statistics for current month and year. :returns: TODO""" invoice_month = forms.CharField(label="month", max_length=225) invoice_year = forms.CharField(label="year", max_length=225) def get_initial(self): initial = super(StatisticsForm, self).get_initial() initial["invoice_month"] = datetime.date.today() initial["invoice_year"] = datetime.date.today() return initial and in my view I'm displaying table and I need to do the rest to. view.py from django.views.generic.edit import FormView from .models import Rate from statistics.forms import StatisticsForm from statistics.services import StatisticsCalculation class StatisticsView(FormView): """ TODO: We need to handle Total Invoice - no matter how old, basically all of them Current month Total Invoice """ template_name = "statistics/invoice_statistics.html" form_class = StatisticsForm def get_context_data(self, **kwargs): context … -
Upload image into gravatar using python django
Is there any way to upload gravatar image in https://secure.gravatar.com/ using python django ? I am new to python and I got this link as documentation https://en.gravatar.com/site/implement/xmlrpc/. But I was not able to find how the process will work in python and what type of keys are needed for the implementation. Any help will be appreciated. -
getting all view functions in form choice field django
I am wishing to get all the names of view functions inside a form choice field. I found an article of doing that in console but it is not working in forms. The link to article is here I changed the code slightly to fill my needs. I created a file named get_views_list.py and tried to import all_views_list from M2.settings import ROOT_URLCONF from django.core.urlresolvers import RegexURLPattern, RegexURLResolver all_urlpatterns = __import__(ROOT_URLCONF).urls.urlpatterns detail_views_list = [] def get_all_view_names(urlpatterns): for pattern in urlpatterns: if isinstance(pattern, RegexURLResolver): get_all_view_names(pattern.url_patterns) elif isinstance(pattern, RegexURLPattern): detail_views_list.append(pattern.callback.__name__) get_all_view_names(all_urlpatterns) all_views_list = [] # remove redundant entries and specific ones we don't care about for each in detail_views_list: if each not in "serve add_view change_view changelist_view history_view delete_view RedirectView": if each not in all_views_list: all_views_list.append(each) but this shows error Unhandled exception in thread started by <function wrapper at 0x7f93f019cb90> Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File … -
importerror: no module named 'models' python anywhere
Trying to deploy local Django project on Python Anywhere, but receiving an ImportError: No module named 'models' when running "python manage.py createsuperuser" File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/Ananthu/MCQ-app-mutile-choice-question-app-/myvenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/Ananthu/MCQ-app-mutile-choice-question-app-/myvenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in File "/home/Ananthu/MCQ-app-mutile-choice-question-app-/myvenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/home/Ananthu/MCQ-app-mutile-choice-question-app-/myvenv/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/Ananthu/MCQ-app-mutile-choice-question-app-/myvenv/lib/python3.5/site-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/home/Ananthu/MCQ-app-mutile-choice-question-app-/myvenv/lib/python3.5/site-packages/django/contrib/admin/apps.py", line 23, in ready self.module.autodiscover() File "/home/Ananthu/MCQ-app-mutile-choice-question-app-/myvenv/lib/python3.5/site-packages/django/contrib/admin/__init__.py", line 26, in au todiscover autodiscover_modules('admin', register_to=site) File "/home/Ananthu/MCQ-app-mutile-choice-question-app-/myvenv/lib/python3.5/site-packages/django/utils/module_loading.py", line 50, in auto discover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/home/Ananthu/MCQ-app-mutile-choice-question-app-/myvenv/lib/python3.5/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 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/Ananthu/MCQ-app-mutile-choice-question-app-/quiz/admin.py", line 2, in <module> from models import Question,Result ImportError: No module named 'models' How can I solve this? Thankyou -
How to manage url on scrolling with Django EL(Endless)pagination
I have followed the documentation Django EL(Endless) pagination. Its working proper but small mistake here. If i scrolling down side then pagination working and change url, but once again i scrolling up side then not change url. So how to manage url on scrolling. This is my view. def category_page(request, slug=None, template='pages/shop.html', page_template='pages/category_products.html'): context = { 'entry_list': product_list, 'page_template': page_template, } if request.is_ajax(): template = page_template return render(request, template, context, context_dict) The template. <div class="row"> <div id="entries" class="page_template"> {% include page_template %} </ul> </div> </div> The page template. {% load el_pagination_tags %} {% paginate 6 entry_list %} {% for detail in entry_list %} <li class="span3"> . . . <!-- each item html --> </li> {% endfor %} <div style="text-align: center"> {% show_more %} </div> And I put inside script tags on the main.js. $(document).ready(function(){ $.endlessPaginate({ paginateOnScroll: true, paginateOnScrollMargin: 550, onCompleted: function(context, fragment) { window.history.pushState(null, null, context.url); } }); }); -
Can not access django server with the local ip address
I have run my django server and could access it with localhost or 127.0.0.1:port But want to access it via the local network using my ipv4 address like 192.168.250 when i try from different machine on the same lan it did not let me access. I am using windows 10 -
Django Test mocked FileField prevent image from being uploaded
I am working on a TestCase for my project, involving some Image and FileFields. Some objects are loaded with fixtures, some objects are created during the tests. I Mocked my image with a InMemoryUploadedFile. When creating a new test object, the mocked image is being uploaded to the MEDIA_ROOT directory, in the correct location defined in the upload_to method. These mocked images are actually being stored locally during the tests. There is quite some information about how to mock an image. But I could not really find some good information about cleaning up these uploads after tests. Question: Is there a frequent used method to prevent these files from actually being uploaded? or Should these files being uploaded in favor of the tests, and cleaned afterwards during the tearDown? (if so, why?) or Is there any other approach you would suggest? Some code of the current situation I'm working with, cropped to the size to fit the question. Thank you for your time in advance. Cropped model: def project_image_upload_location(instance, filename): return 'uploads/projects/images/%s' % \ services.unique_filename(filename) class ProjectImage(models.Model): project = models.ForeignKey( 'projects.Project') name = models.CharField( _("Image name"), max_length=35) image = models.ImageField( _("Project image"), upload_to=project_image_upload_location, width_field='image_width', height_field='image_height') image_width = models.IntegerField( default=0) image_height … -
Implementing State Machine for e-Commerce (Django)
I'm thinking of implementing a State Machine for an eCommerce project - specifically for the workflow from an empty cart to the state where payment is made. In addition, the Cart is stored in session using Django's session framework. I can't wrap my head around whether the state machine should be part of the Cart implementation or standalone, but is 'connected' to the Cart via API. Just a disclaimer, I'm really new to State Machines so I'm not too familiar with the theoretical concepts but from my own research it seems like something really useful for my project. My thought process is as such: state_machine.py class StateMachine(object): states = ['empty', 'filled', 'prepayment', 'payment_auth', 'order_placed'] ... # methods that trigger state changes and in the cart.py, each action might trigger a change in state: state_machine = StateMachine() class Cart(object): ... def add_item(self): ... # add item to cart # then trigger state change state_machine.fill_cart() --> triggers a state change from 'empty' to 'filled' The session should store something like this: request.session[some_session_key] = { 'state': 'filled', 'cart': { # cart stuff goes here }, ... } I'm not sure if what I'm doing is redundant, that perhaps I should implement the State … -
prevent de-serialized object from save or update django
Is there any way to prevent save or update on de-serialized object ? I have removed id from de-serialized object to prevent it from save or update, so = serializers.serialize('python', [t, ]) do = [_.object for _ in serializers.deserialize('python', so)][0] delattr(do, 'id') # deletes id from do object to prevent save or update do.save() # won't work Is there is any another way to achieve this ? -
Django and RDS change of models
How do I change database models and maintain the data already in an RDS instance? Right now I only know how to "change/migrate" models by connecting to an entirely new RDS instance and destroying the old one. Django: 1.10.5 Python: 3.4 Deployment: Ansible playbooks, Upstart, Nginx RDS: PostgreSQL 9.5.4 -
ImportError: No module named 'multiprocessing.forking'
I'm running Python 3.5 and trying to run some code from this django app in the command line and this has been happening: C:\Users\username\Envs\mysite> python service.py --startup=auto install Traceback (most recent call last): File "service.py", line 14, in <module> from django_windows_tools.service import DjangoService,test_commands File "C:\Users\username\AppData\Local\Programs\Python\Python35\lib\site-packages\django_windows_tools\service.py", line 39, in <module> import multiprocessing.forking ImportError: No module named 'multiprocessing.forking' I'm not really sure what could be causing this. -
Star rating in email [on hold]
I want to implement star rating in email. Means we will send an email to users and users can select stars and then stars colors should change based on selected rating and also it should be saved to our database. I know that I can keep links to each star to record rating to db. But I also want to show the selected star in the same email. Is that possible ? -
Django : MultiValueDictKeyError at /app/logout/ when using HttpResponseRedirect
I've been trying to redirect user to main when user logout using django built logout method. However it keep sending me error message like this. Which part is wrong? error message MultiValueDictKeyError at /blog/logout/ "'path'" views.py from django.contrib.auth import authenticate, login, logout @login_required def logout(request): logout(request) return HttpResponseRedirect('blog/login.html') urls.py url(r'^login/$', views.login, name='login'), url(r'^logout/$', views.logout, name='logout'), -
How to use a web API with Django
There is this web api for weather: http://openweathermap.org/current Everytime I try to research how to use web APIs with Django, I get redirected to REST - isn't that for building an API? I don't want to do that. If I simply want to learn about using APIs with Django, where should I go? I'm not sure how to set it up within the view. I tried: from urllib2 import Request and then r = Request('http://samples.openweathermap.org/data/2.5/weather?zip={0},us&appid=0b7f3cd153bc12d3accb83f9682bccbb'.format(zipcode)) json_object = r.read() That didn't seem to work though. -
How do I upload names from csv file and media file (mp4) from my machine to Django database?
I have csv file which has list of ids & names. I have multiple media file in different directories/folders (for example: queue_1, queue_2...) on my machine. These directories/folders has mp4, 3gp files in it. I need to get mp4 media file from these folders and upload it to Django database model. In the file queue_1: 1 is the ID that matches the ID of the csv file. How can I do this ? I can get ID and Names using python csv but I don't know how to get mp4 files from the folders. -
django reverse lookup foreignkey not working
I want to get a specific Video object and then find all of the Rating objects that are associated with it using ForeignKey reverse lookup as described in the docs. I have models: class Video(models.Model): ... rating_int = models.IntegerField(default=1, choices=CHOICES, name='rating_int') def __str__(self): return self.title class Rating(models.Model): video = models.ForeignKey('Video', related_name='video', null=True) and views: def video_ratings(request): vid_rate = Video.objects.get(pk=1) ratings_of_video = vid_rate.rating_set.all() context = { 'vid_rate': vid_rate, 'ratings_video': ratings_of_video } return HttpResponse(template.render(context, request)) When I try to run this I get an error 'Video' object has no attribute 'rating_set' But when i read the django docs it tells me when you do a reverse lookup you need to use this _set.all() command. I am not sure what is missing here. -
How to make it safer my restful API using Django + OAuth2?
I am developing an application both android and ios and also I'm using Django rest framework. this app do not have a login page. There is online facebook login page. I did search a lot and I found these two library for this pip install python-social-auth ( actually it has new name which is social-auth-app-django) pip install django-oauth-toolkit However, somebody told me that you don't have to use these library. Facebook login has oauth already. This is the problem, How can I do this ? How can I use facebook Login to make powerfull API. -
Failed building wheel for cryptography ubuntu 16.04
Im trying to deploy django application on my development server.. Im installing requirements.txt. But I get this error In file included from /usr/include/openssl/asn1.h:65:0, from build/temp.linux-x86_64-2.7/_openssl.c:413: /usr/include/openssl/bio.h:692:6: note: previous declaration of ‘BIO_new_mem_buf’ was here BIO *BIO_new_mem_buf(const void *buf, int len); ^ error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 and also when I run my django application it gives me an error. Im still using python 2.7 and django 1.8.. Anyone can help me with this?. thanks -
Celery update_state() not working
I'm making progress bar but "current_task.update_state()" not working!! This is the simple example of my "task.py" definition. from celery import shared_task, current_task @shared_task def mytask(a): list_A = [1, 2, 3] result = [] for i in list_A: m = a * i result.append(m) process_percent = int(100 * len(result) / len(list_A)) current_task.update_state(state='PROGRESS', meta={'process_percent':process_percent}) return result When I use 'process_percent' with ajax, It is always 'undefined'. And status always return "PENDING", but return the 'result' at celery console ("celery -A myapp worker --loglevel=info --pool=solo") So, I can see the task result. But, I don't know why 'process_percent' is not updated.... I think "current_task.update_state" not working... And this is my celery setting. import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') app = Celery('myapp', broker='amqp://guest@127.0.0.1:5672//', backend='amqp') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) -
Django : Fail to redirecting main page after deleting object
I was trying to make deleting comments function, when user clicks button then it deletes relevant item and redirects to main page. However I got this error message and I'm spending time to fix this. Please review my code and if there is something wrong. error message UnboundLocalError at /blog/detail/18/ local variable 'context' referenced before assignment views.py @login_required def delete_comment(request, comment_no): comment = Comment.objects.get(pk=comment_no).delete() return redirect('blog/home.html') urls.py url(r'^delete_comment/(?P<comment_no>[0-9]+)/$', views.delete_comment, name='delete_comment'), templates <form action="{% url 'blog:delete_comment' %}" method="post"> {% csrf_token %} <input type="hidden" name="comment_no" value="{{ comments.comment_no }}" /> <button type="submit">delete</button> </form> -
Use Wagtail CMS Snippets but Hide in Admin Panel
I am building custom AdminModels based on Wagtail Snippets and have a custom menu in the AdminPanel for my models. How do I hide/remove the Snippet selection from AdminPanel without disabling? Thank you. -
Where to put static files in Django apps or project
Django supports adding static files at both the application and project level. Where you add them sort of depends on how tied to your specific assembly of apps they are. That is, are they reusable for anyone using your app, or are they specific to your particular deployment? My question is do you simply create a static directory at project directory in the case of a project level, and how do you create static directories for specific vs general deployment? -
Django Rest Framework Custom URL in Nested Serializer
I'm triying to create a Custom URL in a nested serializer. This is my serializer.py -> class SerieSerializer(serializers.HyperlinkedModelSerializer): created_by = serializers.ReadOnlyField(source='created_by.username') picture = serializers.ImageField() class Meta: model = Serie fields = ('url', 'name', 'genre', 'director', 'release', 'seasons', 'review', 'picture', 'actors', 'created_by') and this is the result: [ { "url": "http://localhost:8000/series/1/", "name": "Mr. Robot", "genre": "DRAMA", "director": "Sam Esmail", "release": "2015-06-24", "seasons": 2, "review": "Mr. Robot es una serie de televisión estadounidense creada por Sam Esmail. Se estrenó el 24 de junio de 2015 en la cadena USA Network. El mismo día la serie se renovó para una segunda temporada, estrenada el 13 de julio de 2016. El 16 de agosto del mismo año Mr. Robot fue renovado para una tercera temporada a estrenarse en 2017.", "picture": "http://res.cloudinary.com/dqohbm9y4/image/upload/v1487190362/uasfb8maqzh9urp4bvrd.png", "actors": [ "http://localhost:8000/actors/3/", "http://localhost:8000/actors/4/" ], "created_by": "mosthated" } ] But I need something like this: [ { "url": "http://localhost:8000/series/1/", "name": "Mr. Robot", "genre": "DRAMA", "director": "Sam Esmail", "release": "2015-06-24", "seasons": 2, "review": "Mr. Robot es una serie de televisión estadounidense creada por Sam Esmail. Se estrenó el 24 de junio de 2015 en la cadena USA Network. El mismo día la serie se renovó para una segunda temporada, estrenada el 13 de julio … -
Why is the initial Django FormSet data not getting saved?
I have the following form and views whose purpose is to manage a Parent Model (Allergy) and the associated Child Models (Allergen and Medication). What I want to do is always create a new record, even when the "update page" is opened on an existing Allergy record. I'm using the django-extra-views package, which is where things like CreateWithInlinesView are coming from. Almost all of this code works. I can create a brand new Allergy record with AllergyPlanForm, and the FormSets are correctly processed on Create. However, when I try to "update" an Allergy (which is really just opening a CreateWithInlinesView page with the corresponding Allergy+Medication+Allergen data provided as the initial dataset), the initial data that was provided to the child models (not Allergy, only the child models and FormSets) are not saved in the new record. For example, say I create an Allergy with MedicationRecordA. When I go to update that record, I add MedicationRecordB but I also keep MedicationRecordA. When I save the form, only MedicationRecordB would be saved under the new Allergy record. I've looked around at those who've had similar issues with this, and they've suggested overriding the has_changed() method. As you can see below, I've tried …