Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Multi-App Database Router not working
I'm doing a project using Django 1.10 and Python 2.7. I have read and tried to implement database routing according to this page. I have also read up on a lot of different tutorials and other stackoverflow questions. However, I can't seem to get it to work. This is the scenario that I have: I need all analytics, auth and admin apps models on the default database. Then cancellation app on a separate database, and driveractivity app on another separate database. This is the router that I'm using: from django.conf import settings class AppRouter: def db_for_read(self, model, **hints): if model._meta.app_label == 'analytics': return 'default' elif model._meta.app_label == 'cancellation': return 'cancellations_db' elif model._meta.app_label == 'driveractivity': return 'driveractivity_db' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'analytics': return 'default' elif model._meta.app_label == 'cancellation': return 'cancellations_db' elif model._meta.app_label == 'driveractivity': return 'driveractivity_db' return None def allow_migrate(self, db, app_label, model=None, **hints): if app_label == 'cancellation' and db == 'cancellations_db': return True if app_label == 'driveractivity' and db == 'driveractivity_db': return True if app_label in ('analytics', 'auth', 'admin', 'contenttypes', 'sessions', 'rest_framework') and db == 'default': return True return False My database settings are as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': 'localhost', β¦ -
Preferred Django App Architecture
I'm somewhat new to Django and am having trouble wrapping my head around when to make a model it's own App vs having an App with many models. For Example. Say I'm creating a Petition Project. A User can create a Petition, assign it a Cause and a Recipient. On the Petitions page there will be a form where someone can add a Signature. When enough Signatures are met that petition will be considered a Victory. Potential Models: User Petition Recipient Signature Cause My Question: Should these each be there own individual App, or should I just have a User app and a Petition app with Signature, Cause & Recipient being models in the Petition app? How would you approach this projects architecture? -
How to individually call a form to a html in django?
First time creating a webapp in django. please bear with me. So I have this code in my html: <h1><font color="Orange" face="Borda">{{ template_title }}</h1> <form method='POST' action=''>{% csrf_token %} <font color="Orange" face="Borda" style="background-color: transparent;">{{ form }}</font>> <input type='submit' value='SUBMIT'> </form> now inside {{ form }} is all the views and forms. now what I want to do is to specifically call it individually (with style). for example if I have: email=CharField() username=CharField() and I wanted to call them in my html as: <label class="sr-only" for="r-form-first-name">**EMAIL/USERNAME**</label> <input type="text" name="r-form-first-name" placeholder="First name..." class="r-form-first-name form-control" id="r-form-first-name"> How do I do that? I already have a bootstrap template prepared for my login but other documentation suggest I use crispy forms, which I dont want to. Please tell me how if there is other ways of calling it. -
Django: KeyError triggered in forms.py
Making a card app. User can make a deck and put cards in that deck. Decks and cards have an 'owner' field in their models to state who the user is. forms.py class CardForm(forms.ModelForm): def __init__(self, *args, **kwargs): # Pop() removes 'user' from the kwargs dictionary and populates the user variable user = kwargs.pop('owner') super(CardForm, self).__init__(*args, **kwargs) self.fields['deck'] = forms.ModelChoiceField( # modify choices on 'deck' field queryset=Deck.objects.filter(owner=user) ) class Meta: model = Card fields = ('term', 'definition', 'deck') The part triggering the KeyError is super(CardForm, self).init(*args, **kwargs) views.py def card_new(request, deck): if request.method == "POST": form = CardForm(request.POST) if form.is_valid(): card = form.save(commit=False) card.save() return redirect('card:detail', deck) else: form = CardForm(initial={'deck': deck}, owner=request.user) # this initial field sets card's deck as current deck return render(request, 'card/card_edit.html', {'form': form}) models.py class Card(models.Model): owner = models.ForeignKey(User, null=True, default=True, related_name='oc') term = models.CharField(max_length=100, default='N/A') definition = models.TextField(default='N/A') deck = models.ForeignKey(Deck, on_delete=models.CASCADE) -
error to pass value in query Django
Hi everyone I have problem with this query in Django opc_status = {'jobs_running':'running', 'jobs_pending':'pending', 'cpus_used':'cpu'} if status in opc_status.values(): key = list(opc_status.keys())[list(opc_status.values()).index(status)] + ', entry_dt' else: key='*' db = MySQLdb.connect(host='..', port=, user='..', passwd='..', db='..') try: cursor = db.cursor() cursor.execute('SELECT %s FROM proj_cpus WHERE project in %s', key, list_project]) the first params of the query must be * or something like jobs_pending, entry_dt but query return this error tuple index out of range Any idea about how to create the query correctly? -
django postgres JSONField | query to check in list(contains) of values
In django 1.9(using postgresdb), we're using JSONField(in a model) whose entries looks something like this: **Entry 1**(in a row of that table): data: { "key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4" } **Entry 2**(in a row of that table): data: { "key5": "value4", "key6": "value2", "key7": "value2", "key8": "value4" } I want to query in for values, something like data__value__contains='value4' Django has support for "keys"(has_key, has_any_keys, has_keys) related queries What would be good approach to query for above need ? -
Getting the count of a Filtered Result in a template on Django
Im trying to access a related model on the template like this: course.course_set.all.0.section_set.all.0.student_assignation.count The problem is that I would like to count all the student assignations which have an active = True property. I would like to be able to do something like this: course.course_set.all.0.section_set.all.0.student_assignation(active=True).count How can I accomplish this on the django template? -
python-social-auth updating user details more frequently than session invalidation
Is there anyway to update user details more frequently than when the session is invalidated in python-social-auth? If user profile information obtained from the provider changes, it won't update until the Django session expires, since the SOCIAL_AUTH_PIPELINE is only executed when performing authentication against our provider. Since the session is still active, no need to re-authenticate, the pipeline isn't executed, and thus I don't request user details from my auth provider. Is the only way to do this to decrease the Django SESSION_COOKIE_AGE setting? I don't want to interrupt the application flow constantly by triggering a re-authentication, but I do want to make sure I'm retrieving user details on a frequent basis. -
Plugin with dependencies in Python
I need a Plugin Framework wherein the framework not only loads the plugin but also loads/installs the plugin's dependecies/libraries. Btw, currently, I'm using the Yapsy framework. Example: Twitter Plugin (twits.py), that make use of Tweepy library. I need a way to load tweepy library when twits.py's loaded. Any tips? Thank you in advance. -
Filtering plain models on their relation to a subclass of a django polymorphic model?
I have a plain Django model that has a ForeignKey relation to a django-polymorphic model. Let's call the first PlainModel that has a content ForeignKey field to a polymorphic Content model with subtypes Video and Audio (simplified example). Now I want to query for all PlainModel instances that refer to a Video. Problem is all the docs I find are about filtering directly via the polymorphic model itself. So in this example something like Content.objects.instance_of(Video). But I need PlainModel's, so it would need to look something like PlainModel.objects.filter(content__instance_of=Video). I tried a bunch of variations but I cannot find anything that works. In the docs they use Q(instance_of=ModelB), but this doesn't work on the relation as Q(content__instance_of=ModelB). It gives an error like 'Cannot query "x": Must be "y" instance.' even with the translation call, I guess because the PlainModel is not polymorphic aware. I have a temporary hack that directly filters on the polymorphic_ctype field, but this doesn't handle subclasses (eg: ExtendedVideo would not be found when looking for Video, because it would have a different ContentType). -
Href passing page options
My current URL is something like this: http://127.0.0.1:8000/browse/?name=&status=any On it I have a paginator which allows me to browse by page number. How would I set the href so it goes to the next page, while passing in the name and status options? So for example the href for page2 should be: http://127.0.0.1:8000/browse/?name=&status=any&page=2 But if I set <a href="?page={{ paginator.previous_page_number }}"> Then the URL is http://127.0.0.1:8000/browse/?page=2 Does anyone know how I can get this done? -
Django app pointing to purged table on postgres
I am working on Django application migration from oracle to Postgres. Before migration On oracle a new table was created and one existing table got deleted. Model was updated and Django app was able to recognize the change and has been working fine on oracle without any issue. I have created a new VM and copied over the django application and updated the database connection from Oracle to Postgres. Connection is successfully established and everything looks good from the app side except one thing ; When i delete action from Admin site Django complains that it is unable to find the reference in the table that got deleted and doesn't exist anymore. I am clueless why Django is looking for the deleted table and not the new table however it works fine on oracle. ProgrammingError: relation "model_actionreference" does not exist LINE 1: ...model_actionreference"."category" FROM "model_... Any help would be much appreciated. -
Run django migrate in docker
I am building a Python+Django development environment using docker. I defined Dockerfile files and docker-compose.yml for my nginx and postgres containers and a container that will run our app using uwsgi. Since this is a dev environment, I am mounting the the app code from the host system, so I can easily edit it in my IDE. The question I have is where/how to run migrate command. In case you don't know Django, migrate command creates the database structure and later changes it as needed by the project. I have seen people run migrate as part of the compose command directive command:python manage.py migrate && uwsgi --ini app.ini`, but I do not want migrations to run on every container restart. I only want it to run once when I create the containers never run again unless I rebuild. Where/how would I do that? -
Get celery beat trigger time on task
I'm trying to find a way to get time time condition that triggered celery beat to fire a task. Getting datetime.now() often deviates from the time at which the task was queued by celery beat due to all celery workers being busy. For example: I set the task to be executed at 12:30 everyday but due to all workers being busy at the time the task start running at 12:31. I need to know which time condition triggered to task regardless of the time the task was executed. -
Reorder Fields of FeinCMS Content Type in Page Admin
I let a content type inherit from RichTextContent and add a few fields, like a title. class SimpleTextContent(RichTextContent): title = models.CharField() ... Unfortunately, in the Page Admin the text field will appear on top of the corresponding inline admin. But it would be nicer to have the title appear first. How can I change the order of the fields in a content type's inline admin? -
How to make post request in Django TastyPie using ApiKeyAuthentication
I have resource like this: class EntryResource(ModelResource): class Meta: queryset = Entry.objects.all() resource_name = 'entry' allowed_methods = ['post'] authentication = ApiKeyAuthentication() authorization = Authorization() And try to make request to this resource according to documentation: requests.post('http://localhost/api/entry/', json={"key1": "value1", "key2": "value2"}, headers={"content-type": "application/json", "Authorization": "ApiKey", "<username>": "<api_key>"}) But get 401. -
Django - How to send a success message using a UpdateView CBV
(first of all sorry for my bad english) I'm trying to show a message in a UpdateView when the users save the changes! This is my view class NeedUpdateView(UpdateView): model = Need template_name = 'purchases/needs_update_form.html' pk_url_kwarg = 'need_id' success_message = 'List successfully saved!!!!' fields = [ 'detail', ] When you save the app loads the same template! but i like to show a bootstrap alert if save the object! This is code in the template to show the message {% if messages %} <div class="alert alert-success"> {% for m in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ m }}</li> {% endfor %} </div> {% endif %} and in the settings i add this MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage' But the i can't show the messages! The changes in the object are saving fine only need to show the message! -
Templates render properly on deployment server but TemplateDoesNotExist error on runserver
I have a project structure like this mainproject βββ manage.py βββ mainproject β βββ settings.py β βββ templates β β βββ mainproject β β βββ index.html β βββ urls.py β βββ views.py β βββ wsgi.py βββ app βββ admin.py βββ apps.py βββ forms.py βββ models.py βββ templates β βββ app β βββ index.html β βββ abc.html βββ urls.py βββ views.py Now in my settings.py I have TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['mainproject/templates', 'app/templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] When I use this on main domain on my deployment server, (deployed using nginx and uwsgi), it works all well. I am able to access mainproject's index at domain.com and app's index at domain.com/app But when using runserver, only domain.com:8000/app works and domain.com:8000 gives error TemplateDoesNotExist at /. Why so and how this could be fixed? Template loader postmortem: Using engine django: django.template.loaders.filesystem.Loader: /home/mohit/mainproject/templates/mainproject/index.html (Source does not exist) django.template.loaders.filesystem.Loader: /home/mohit/app/templates/mainproject/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/mohit/Env/mainproject/lib/python2.7/site-packages/django/contrib/admin/templates/mainproject/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/mohit/Env/mainproject/lib/python2.7/site-packages/django/contrib/auth/templates/mainproject/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/mohit/mainproject/app/templates/mainproject/index.html (Source does not exist) If I change DIRS line in TEMPLATES in settings.py and make it 'DIRS': ['mainproject/mainproject/templates', 'uber/templates'], Then it works on β¦ -
Haystack with Whoosh not returning any results despite Index being OK
I've installed Django-Haystack and Whoosh and set it all up following the haystack documentation, but no matter what I search for I always get "No results found." on the search page, despite the index apparently being OK. When running "manage.py rebuild_index" it correctly states: Indexing 12 assets indexed 1 - 12 of 12 (worker PID: 1234). And when running this in a Django shell: from whoosh.index import open_dir ix = open_dir('mysite/whoosh_index') from pprint import pprint pprint(list(ix.searcher().documents())) It correctly returns all details of the 12 indexed assets, so it looks like the index is fine, but no matter what I search for I cannot get any results only "No results found."! I have followed the advice in every other similar question on StackOverflow (and everywhere else that popped up on Google) to no avail. Does anyone have any suggestions? Files used (edited for brevity): settings.py INSTALLED_APPS = [ .... 'haystack', 'assetregister', .... ] HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine', 'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'), }, } models.py class Asset(models.Model): asset_id = models.AutoField(primary_key=True) asset_description = models.CharField(max_length=200) asset_details = models.TextField(blank=True) search_indexes.py from haystack import indexes from .models import Asset class AssetIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) asset_description = indexes.CharField(model_attr='asset_description') def get_model(self): return Asset def β¦ -
Referencing relation's relations in Django Serializer
Let's say I have some models: class A(models.Model): ... class B(models.Model): my_reference_to_a = models.ForeignKey(A) b_field_1 = ... b_field_2 = ... class C(models.Model): my_reference_to_b = models.ForeignKey(B) c_field_1 = ... ... In my serializer for C, I want to include all of the fields in C, all the fields in B, as well as the reference to A in B (but not the reference to B in C), so the JSON API output would be something like this: { "data": [{ "type": "C", "id": "1", "attributes": { "b_field_1": "...", "b_field_2": "...", "c_field_1": "..." }, "relationships": { "a": { "data": { "type": "A", "id": "1" } } } }], ... } How would I go about this? I've already tried doing something like this inside my serializer for C: A = ASerializer(source='my_reference_to_b.my_reference_to_a') But that doesn't work, as DRF doesn't seem to support dotted paths for sources. I've also tried supplying a method that returns the proper model (the model is valid inside the method) as the source, but that outputs the reference in the JSON as: "a": { "data": null } On my A model, I also have a reference to another model, D, that is not explicitly stated in A, but is β¦ -
how to do list view at front end in django
I am new to Django and would like to create a sortable ListView/cerateview/deleteview/updateview in fronted using mysql database.not using admin (similer to django Admin) . add complate programming ex.(view,model,html). -
Django abstract models - how to implement specific access in abstract view method?
Let's say I have an abstract model in Django, with two models extending off that. Inside a Django Rest Framework generic view, how can I control creation of one of the two implementing models? My solution is below: from enum import Enum from rest_framework.views import APIView class BazType(Enum): FOO = 1 BAR = 2 class AbstractView(APIView): def __init__self(): #Init code here def _internal_method(self, django_model, this_type = BazType.FOO): if this_type == BazType.FOO: record, created = ConcreteModelOne.objects.get_or_create(some_field = django_model) elif this.type == BazType.BAR: record, created = ConcreteModelTwo.objects.get_or_create(some_field = django_model) It works, but is there a way to get rid of the if/else block? In other words, is there a way, from a subclass of AbstractView, to pass in some identifier for which model is required for the get_or_create method call? -
How to access input value in a form CreateView using Django?
Let's say I have a form to create an animal(name, color ...), how to access the input value and display it (after the form has been submitted) in the same form page. I tried : class AnimalCreate(CreateView): model = Animal form_class = AnimalForm success_url = 'main_site/success.html' def get_context_data(self, **kwargs): color = ?? # how to get the value of the color input ? context = super(AnimalCreate, self).get_context_data(**kwargs) context['color'] = color return context -
You're accessing the development server over HTTPS, but it only supports HTTP when using Docker
I am fairly new to docker and I am trying to make a container for Django + nginx + mysql. When i run my docker-compose.yml with docker-compose up everything works, but when I visit the website i get You're accessing the development server over HTTPS, but it only supports HTTP . The part for the nginx in my docker-compose file looks like this: -nginx: - image: nginx - ports: - - "80:80" - - "443:443" - volumes: - - .:/code - links: - - web What am I doing wrong? -
Response mess up when curl Django url
@csrf_exempt def add_node(request, uid=None): resp = { 'status': 0 } return JsonResponse(resp) Then I use curl to test it, which messed my terminal. .