Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Object manipulation in django/python
I have an object questions from the class QnChoice. questions = QnChoice() I am creating it on my test view and I want to have the same object instance over this view on any number of http requests. (i.e) I don't want it to get initialised on every http request on the test view. Is it possible? if how to achieve this ? thanks -
Is There A Built-in Way to Filter with Given Function in Django?
I especially wonder if I can use map, filter and reduce functions with Django model instances. If I cannot, is there a built-in way to pass a function to filter querying in Django? Let me demonstrate my real problem for better understanding. I use PostgreSQL to use ArrayField and I have similiar model as below: class Route(models.Model): stops_forwards = ArrayField( ArrayField( models.PositiveIntegerField(), size=2 ), default=[], verbose_name="Stops Forwards (Ordered)" ) stops_backwards = ArrayField( ArrayField( models.PositiveIntegerField(), size=2 ), default=[], verbose_name="Stops Backwards (Ordered)" ) As you can see above, I have embedded ArrayFields inside stops_forwards and stops_backwards. I use embedded ones so as to keep it in order. An example data is shown as below: [ [1, 35], [2, 40], [3, 180], [4, 285] # ... and it goes ] What I want to do is to check if a particular stop id (like 285) is in embedded ArrayField. Assuming that I have a function called has_route_stop that I do not know how it works but I call it as below: filter(lambda: has_route_stop(285), instances) Or, is there a built-in way in Django API to do this? Environment Python 3.5.1 Django 1.9.9 PostgreSQL 9.5.4 psycopg2 2.6.2 -
How to filter out identical double requests on server
I've noticed that my Django application from time to time makes double database queries, instead of just one. The log file shows two similar requests at (almost) the exact same time. I know the users are using iPads at locations where the internet connection may be unstable. Example: [pid: 749|app: 0|req: 892/2837] x.x.x.x () {44 vars in 896 bytes} [Fri Sep 9 12:00:55 2016] GET /clinic_profile/61 => generated 0 bytes in 1 msecs (HTTP/1.1 301) 3 headers in 134 bytes (1 switches on core 0) [pid: 750|app: 0|req: 659/2838] x.x.x.x () {44 vars in 898 bytes} [Fri Sep 9 12:00:55 2016] GET /clinic_profile/61/ => generated 84989 bytes in 374 msecs (HTTP/1.1 200) 3 headers in 102 bytes (1 switches on core 0) This is a critical flaw in my system and I need to fix it asap. Question: How can I filter out double requests? Im using Django, Nginx and Ubuntu 14.04 -
Django - Follow a backward ForeignKey and then a ForeignKey (query)
I use Django 1.9 and Python 2.7. My app has four models. Each "trip" is made of several "steps" chosen by the visitor, which relate to "places", which may have several related "Picture". class Trip(models.Model): title = models.CharField(max_length=140, blank=True) class Step(models.Model): theplace = models.ForeignKey(ThePlace) trip = models.ForeignKey(Trip) class ThePlace(models.Model): name = models.CharField(max_length=200) class Picture(models.Model): file = models.ImageField(upload_to="pictures") slug = models.SlugField(max_length=100, blank=True) theplace = models.ForeignKey(ThePlace, null=True, blank=True) I would like to retrieve all "Picture" objects which are related to a specific Trip, using an existing "selectedtrip" queryset: selectedtrip = Trip.objects.filter(author=request.user)[0] pictures = selectedtrip.step_set.all().theplace.picture_set.all() Django displays the following error: "AttributeError: 'QuerySet' object has no attribute 'theplace'" Any idea why ? -
Easy django database flush for functional testing?
As in question, is there a better way to clean up (tearDown) databse on django development server in functional test suite? So far I've come up with this: def tearDown(self): subprocess.call(['bash', FLUSH_DATABASE_SCRIPT], stdout=subprocess.PIPE) And here is the bash script itself: #!/bin/bash project_name="name" server_root_dir="$HOME/.virtualenvs/djangoproject" manage="$server_root_dir/$project_name/manage.py" source "$server_root_dir/bin/activate" echo 'yes' | python $manage flush echo "from django.contrib.auth.models import User; User.objects.create_superuser('admin', 'admin@example.com', 'adminadmin')" | python $manage shell > /dev/null deactivate Now this is messy and generates massive unwanted output in stdout. -
Django Pyhton Render Counter Collections Sort Order
I can't figure out how to display a collections.Counter in the right order in Django: When i use Counter().most_common(5) it should give me the 5 most common keys in order. But it does not. I've got this: users_cities = dict(Counter(User.objects.all().values_list('city', flat=True)).most_common(5)) return render(request,'admin/stats/stats.html', { 'users_cities': users_cities, } But when i loop through them in the template, they arent sorted: {% for label , counter in users_cities.items %} {% if label %} <tr> <th>{{ label }}</th><td> {{ counter }}</td> </tr> {% endif %} {% endfor %} So where is my mistake? -
iteration performance javascript vs python
In my website, there is a signup with email address.I need to check weather its a spam email.Here is a list of possible spam email domains. Spam list Spam list2 What i am doing is make a list of spam domains and iterate it to check with signup email.Something like this. for i in ['spam1','spam2',..etc]: if usermail==i: print "It is a spam mail" Either do this in the django python side or in the client side itself (using javascript).But i have no idea which is d better option.Please have suggestions. -
Yet again regarding multiple forms on same page
I'm a total newbie in Django and i'm aware that my question was asked here many times (i've read most of answers). Unfortunately, i didn't found solution that is suffice for my case. The task is to create app for CRUDing groups of students. Here's the code: urls.py urlpatterns = [ url(r'(?P<pk>\w+)', views.class_display, name='display'), url(r'', views.class_form, name='class_form'), url(r'', views.classes, name='classes'), ] views.py def class_form(request): class_form = ClassForm(request.POST) if request.method == 'POST' and 'add_class_btn' in request.POST: if class_form.is_valid(): created_class = class_form.save(commit=False) created_class.order = class_form.cleaned_data['order'] created_class.class_name = class_form.cleaned_data['class_name'] created_class.monitor = class_form.cleaned_data['monitor'] created_class.students = class_form.cleaned_data['students'] class_form.save() else: class_form = ClassForm() return render(request, 'classes/class_list.html', {'class_form': class_form}) def classes(request): classes = Class.objects.all() must_be_deleted = [] if request.method == 'POST' and 'delete_btn' in request.POST: must_be_deleted = request.POST.getlist('to_delete') for item in must_be_deleted: classes.filter(class_name=item).delete() return render(request, 'classes/class_list.html', {'classes': classes}) class_list.html <h1>List of groups</h1> <table> <tr> <th>Group name</th> <th>Amount of students</th> <th>Monitor</th> <th>Delete?</th> </tr> <form action="{% url 'students.views.classes' %}" method="post"> {% csrf_token %} {% for class in classes %} <tr> <td><a href="{% url 'students:display' pk=class.pk %}">{{ class.class_name }}</a></td> <td>{{ class.students.all.count }}</td> <td>{{ class.monitor }}</td> <td><input type="checkbox" name="to_delete" value="{{ class.class_name }}"></td> </tr> {% endfor %} <tr> <td colspan="3"></td> <td><input type="submit" value="Delete" name="delete_btn"></td> </tr> </form> </table> <h1>Add group</h1> <form action="{% url … -
Providing 'default' User when not logged in instead of AnonymousUser
Is there a way to globally provide a custom instance of User class instead of AnonymousUser? It is not possible to assign AnonymousUser instances when User is expected (for example in forms, there is need to check for authentication and so on), and therefore having an ordinary User class with name 'anonymous' (so that we could search for it in the DB) would be globally returned when a non-authenticated user visits the page. Somehow implementing a custom authentication mechanism would do the trick? And I also want to ask if such an idea is a standard approach before diving into this. -
Make POST / PUT parameters optional
In my app, I get a set of teachers IDs in .json and then I get object related to those IDs like so: for n in ['subject_1', 'subject_2', 'subject_3', 'subject_4', 'subject_5', 'subject_6']: if not context[n] is None: context[n] = Teacher.objects.get(id=context[n]).name But it looks ugly for me. Is there a way to make it more elegant? -
how to set up credentials for app google login and login to gmail
My (Django) app requires users to login using Google account. A feature of the app is also to send emails through Gmail API. So far I have set up a credential of type Web application which works for login (last line). The sending of email does not work with this ('Web app') credential because the step halts at 2016-09-09 05:30:53,535 :Starting new HTTPS connection (1): accounts.google.com 2016-09-09 05:30:53,779 :Starting new HTTPS connection (1): www.googleapis.com The above message makes me suspect that I have incorrect credentials. My question is: Do I need to set two sets of credentials (and thus have two client_secret.json files) in google console, one for login and one for sending email through Gmail API? Or, do I peg login and Gmail-API authentication to one credential, by some mysterious magical chanting? Any info much appreciated. -
ValueError: invalid literal for int() with base 10: 'abc'
models.py class answers(models.Model): username = models.ForeignKey(settings.AUTH_USER_MODEL) title = models.ForeignKey(Task) answer = models.URLField() ANSWER_CHOICES = ( ('F', 'Declined'), ('T', 'Accepted'), ) accept_answer = models.CharField(max_length=1, choices=ANSWER_CHOICES, default='f') def __str__(self): return self.answer def __unicode__(self): return self.answer views.py def full_task(request, id): task = Task.objects.get(id = id) instance = get_object_or_404(answers, title=task.title) form = AnswerForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.save() context = { 'form':form, 'task': task, } TRACEBACK Traceback: File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\rohit\Desktop\asad\website\user_profile\views.py" in full_task 75. instance = get_object_or_404(answers, title=task.title) File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\shortcuts.py" in get_object_or_404 85. return queryset.get(*args, **kwargs) File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\db\models\query.py" in get 376. clone = self.filter(*args, **kwargs) File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\db\models\query.py" in filter 796. return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\db\models\query.py" in _filter_or_exclude 814. clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\db\models\sql\query.py" in add_q 1227. clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\db\models\sql\query.py" in _add_q 1253. allow_joins=allow_joins, split_subq=split_subq, File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\db\models\sql\query.py" in build_filter 1183. condition = lookup_class(lhs, value) File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\db\models\lookups.py" in __init__ 19. self.rhs = self.get_prep_lookup() File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\db\models\fields\related_lookups.py" in get_prep_lookup 100. self.rhs = target_field.get_prep_value(self.rhs) File "C:\Users\rohit\Desktop\asad\lib\site-packages\django\db\models\fields\__init__.py" in get_prep_value 946. return int(value) Exception Type: ValueError at /tasks/1/ Exception Value: invalid literal for int() with base 10: 'abc' i … -
readonly_fields returns empty value in django inlined models
i am new in django framework, in my current try, i have two models (Client and Facture). Facture is displayed as a TabularInline in client change view. i want display a link for each inlined facture object to download the file. so i added a custom view that download the facture file, but dont know how to link to it class Client(models.Model): ... class Facture(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) numero = models.IntegerField(unique=True, default=rand_code) ... and in the admin.py: class FactureInline(admin.TabularInline): model = Facture extra = 0 readonly_fields = ('numero', 'dl_link') def DLFacture(self, request, obj): ... response.write(pdf) return response def get_urls(self): urls = super(FactureAdmin, self).get_urls() from django.conf.urls import url download_url = [ url(r'^(?P<pk>\d+)/download/$', self.admin_site.admin_view(self.DLFacture), name="download"), ] return download_url + urls def dl_link(self, obj): from django.core.urlresolvers import reverse return reverse("admin:clients_facture_download", args=[obj.pk]) admin.site.register(Facture, FactureAdmin) class ClientAdmin(admin.ModelAdmin): inlines = [ FactureInline, ] admin.site.register(Client, ClientAdmin) i get the following error: Reverse for 'clients_facture_download' with arguments '(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] all works fine when i change the reverse url to reverse("admin:clients_facture_change", args=[obj.pk]) so any one could help me know how to reverse the download view and if i am doing thinks right ? thanks for any help -
autoenv printing "will run" /path/to/.env everytime I cd
My specific problem is not the fact that source /venv/bin/activate is being executed everytime I change to a sub folder. The problem is everytime I do it prints "will run" /path/to/.env I installed autoenv through homebrew in version 0.2.0. This is my .env file: if [ -z "$VIRTUAL_ENV" ]; then CUR_DIR=$(pwd) # search for the next .env while [[ "$PWD" != "/" && "$PWD" != "$home" ]]; do env_file="$PWD/.env" if [[ -f "$env_file" ]]; then BASE_DIR=$(dirname $env_file) break fi builtin cd .. done if [ ! -z "$BASE_DIR" ]; then echo "Activating that virtualenv" source ${BASE_DIR}/venv/bin/activate fi cd $CUR_DIR fi The output in the terminal is something like: MacBook-Pro:~ llamasramirez$ cd Desktop/oficios/ Will run /Users/llamas/Desktop/oficios/.env Activating that virtualenv Will run /Users/llamas/Desktop/oficios/.env (venv) MacBook-Pro:oficios llamasramirez$ cd django_sites/polls/ Will run /Users/llamas/Desktop/oficios/.env (venv) MacBook-Pro:polls llamasramirez$ -
How to use factory.SelfAttribute with factory.Sequence?
I have model like so: class ItemGroup(models.Model): group_id = models.AutoField(primary_key=True) category = models.CharField(max_length=200, blank=True, null=True) name = models.CharField(max_length=45, blank=True, null=True) def __str__(self): return self.name Now I am trying to build a factory: class ItemGroupFactory(DjangoModelFactory): class Meta: model = ItemGroup category = FuzzyChoice(['category1', 'category2']) name = Sequence(lambda n: "%s%d" % (SelfAttribute("category"), n)) The problem is, this does not work, while testing I get: django.db.utils.DatabaseError: Data too long for column 'name' at row 1 So how to use SelfAttribute with Sequence? I am using: Django 1.8.14 djangorestframework 3.4.6 fake-factory 0.5.3 mysql-connector-python 2.1.3 factory-boy 2.7.0 -
Django i18n setlang view
I have set up internationalisation with django 1.9.7 Everything works well with url like mydomain.com/en, but when I use configuration with non root url (mydomain.com/prefix/en) it does not work well. Translation works when I change manually the language into url, but when I use the i18n setlang view, it seems translate_url (django.core.urlresolvers) does not work, it can't resolve the url. Anybody have already got this issue? -
Does Django run in single thread by default?
by reading the code,I found it seems that Django run in single thread by default. However, when I use sleep(15) in my view function and open two web to request my function. They return the response almost at the same time! so, I do not know why does it happened…… my django version is 1.9 -
Django: no module named http_utils
I created a new utils package and an http_utils file with some decorators and HTTP utility functions in there. I imported them wherever I am using them and the IDE reports no errors, and I also added the utils module to the INSTALLED_APPS list. However, when launching the server I am getting an import error: ImportError: No module named http_utils What am I missing? What else do I need to do to register a new module? -
PDF generation with report lab issue
I am using reportlab package for PDF generation in my webapp. I have defined the story and appended the flowables accordingly. At end, I was endup with an below issue. [ERROR] [2016-09-09 18:12:20,540] [documents.py|257]: "Traceback (most recent call last): File "/var/www/sites/dev_mymebook/mymebook/mymebook/../mymebook/mebook/pdf_classes/documents.py", line 252, in render_mebook _render_mebook(mebook_info, *args, **kwargs) File "/var/www/sites/dev_mymebook/mymebook/mymebook/../mymebook/mebook/pdf_classes/documents.py", line 1064, in _render_mebook doc.build(story)File "/var/www/sites/dev_mymebook/mymebook/mymebook/../mymebook/mebook/pdf_classes/documents.py", line 195, in build self.handle_flowable(flowables) File "/var/www/sites/dev_mymebook/live_env/local/lib/python2.7/site-packages/reportlab/platypus/doctemplate.py", line 743, in handle_flowable self.handle_keepWithNext(flowables) File "/var/www/sites/dev_mymebook/live_env/local/lib/python2.7/site-packages/reportlab/platypus/doctemplate.py", line 710, in handle_keepWithNext while i I am unsure where I am missing...? Any help would be greatly appreciated? -
Django template pattern for long javascript variables
I have a python array with 8 x 100.000 numbers that will be used to create a web graph in canvas. Right now, I'm including the array in the view render's context and rendering it in page template, into a <script> tag right at the end of the html page. Something like this <script> my_var = {{ long_list|safe }} //... do the job to paint the graph </script> This long list is also saved at user session, because the user can change some parameters and request a reprocess of the data. So I kept it in session so as not to keep sending it back and forth, as the data itself won't be changed, just used to generate some interpretation. The thing is, I'm profiling the page in Chrome, and there's a "Parse html/Compile Script" taking around 1 second, and I'm thinking this is due to the long array being written right there at the html code. So, an alternative would be to not include this long list right at the view context, and after the page is loaded, make an ajax request to grab this long list from user session (into another view, or whatever). So, the thing is: … -
Django queryset Hashed data look up
I have a model say, class MyModel(models.Model): name = models.CharField(max_length=50) hashed_value = models.TextField() When I create the data I hash the name return the hashed data to the front end. Now when I fetch the data, I get the hashed data from the front end. I need to look if that data is available. For that currently I have a new field hashed_value and check if the data presents in db. values = MyModel.objects.filter(hashed_value=request.POST.get('hashed_name')) Is there any way I can depend on only one field name and get the desired result (That is avoid hashed_value and use only name) . I have researched about F and aggregate to check if it fits here. I cant find a solution. Is there any other way to do it? Saving code: import hashlib h = hashlib.md5() my_model = MyModel() my_model.name = request.POST.get('name') h.update(request.POST.get('name')) my_model.hashed_value = h.hexdigest() my_model.save() Hope some one can find an alternative solution. Feel free to ask If my question is not clear. -
How do I pass the context from one class based view to another view in django?
My Index View: class IndexView(generic.ListView): template_name = 'pybb/index.html' context_object_name = 'categories' def get_context_data(self, **kwargs): ctx = super(IndexView, self).get_context_data(**kwargs) categories = ctx['categories'] for category in categories: category.forums_accessed = perms.filter_forums(self.request.user, category.forums.filter(parent=None)) ctx['categories'] = categories return ctx My category view: class CategoryView(RedirectToLoginMixin, generic.DetailView): template_name = 'pybb/index.html' context_object_name = 'category' def get_login_redirect_url(self): # returns super.get_object as there is a conflict with the perms in CategoryView.get_object # Would raise a PermissionDenied and never redirect return super(CategoryView, self).get_object().get_absolute_url() def get_queryset(self): return Category.objects.all() def get_object(self, queryset=None): obj = super(CategoryView, self).get_object(queryset) if not perms.may_view_category(self.request.user, obj): raise PermissionDenied return obj def get_context_data(self, **kwargs): ctx = super(CategoryView, self).get_context_data(**kwargs) ctx['category'].forums_accessed = perms.filter_forums(self.request.user, ctx['category'].forums.filter(parent=None)) ctx['categories'] = [ctx['category']] return ctx def get(self, *args, **kwargs): if defaults.PYBB_NICE_URL and (('id' in kwargs) or ('pk' in kwargs)): return redirect(super(CategoryView, self).get_object(), permanent=defaults.PYBB_NICE_URL_PERMANENT_REDIRECT) return super(CategoryView, self).get(*args, **kwargs) My forum View: class ForumView(RedirectToLoginMixin, PaginatorMixin, generic.ListView): paginate_by = defaults.PYBB_FORUM_PAGE_SIZE context_object_name = 'topic_list' template_name = 'pybb/forum.html' def dispatch(self, request, *args, **kwargs): self.forum = self.get_forum(**kwargs) return super(ForumView, self).dispatch(request, *args, **kwargs) def get_login_redirect_url(self): return self.forum.get_absolute_url() def get_context_data(self, **kwargs): ctx = super(ForumView, self).get_context_data(**kwargs) ctx['forum'] = self.forum ctx['forum'].forums_accessed = perms.filter_forums(self.request.user, self.forum.child_forums.all()) return ctx def get_queryset(self): if not perms.may_view_forum(self.request.user, self.forum): raise PermissionDenied qs = self.forum.topics.order_by('-sticky', '-updated', '-id').select_related() qs = perms.filter_topics(self.request.user, qs) return qs def get_forum(self, **kwargs): … -
How to override Django Admin
I have two models Restaurant and Details. The superuser assigns each restaurant a user.When that user logs into admin i want only those Details associated with that user's Restaurant to be shown,and he should be able to edit them as well. I tried to override admin's queryset function but to no success.Any help would be appreciated. This is what i did so far I am just a beginner in Django. class RestaurantAdmin(admin.ModelAdmin): model = Details def save_model(self, request, obj, form, change): obj.user = request.user super(RestaurantAdmin, self).save_model(request, obj, form, change) def queryset(self, request): print(request.user) qs = super(ResaturantAdmin, self).queryset(request) # If super-user, show all comments if request.user.is_superuser: return qs return qs.filter(owner=request.user) admin.site.register(Restaurant) admin.site.register(Details,RestaurantAdmin) -
Redirect Django logs to Sentry handler
I've successfully set up sentry for my django project for exception handling. Now I also want to redirect all django logs to the sentry handler. I've tried to overwrite the django logger in several ways but it doesn't seem to work. My current config is this (I've set the sentry handler to DEBUG only for testing): LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s ' '%(process)d %(thread)d %(message)s' }, }, 'handlers': { 'sentry': { 'level': 'DEBUG', # To capture more than ERROR, change to WARNING, INFO, etc. 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler', 'tags': {'custom-tag': 'x'}, }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' } }, 'loggers': { 'root': { 'level': 'DEBUG', 'handlers': ['sentry', 'console'], }, 'django.db.backends': { 'level': 'ERROR', 'handlers': ['console'], 'propagate': False, }, 'raven': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False, }, 'sentry.errors': { 'level': 'DEBUG', 'handlers': ['console'], 'propagate': False, }, 'app': { 'level': 'WARNING', 'handlers': ['sentry'], 'propagate': True, }, 'django': { 'level': 'DEBUG', 'handlers': ['sentry', 'console'], 'propagate': True, }, }, } But I've also tried it with 'disable_existing_loggers': True, And I've also tried to set LOGGING_CONFIG = None and then logging.config.dictConfig(LOGGING) My goal is it to send everything that is getting logged to … -
How to connect to redis?
CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } I am trying to connect to redis to save my object in it, but it gives me this error when i try to connect Error 10061 connecting to 127.0.0.1:6379. No connection could be made because the target machine actively refused it How does it work, what should i give in location and i am on a proxy from my company. Need some detailed explanation on location.