Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form populated by content of an object is not refreshing
I am new to Django and probably made a mistake. I created forms.py containing: from django import forms class CustForm(forms.Form): OPTIONS = ([(account.id, account) for account in Account.objects.filter(active=True)]) CustId = forms.ChoiceField(widget=forms.Select, choices=OPTIONS) In views.py: from .forms import CustForm def listcust(request): if request.method == 'POST': form = CustForm(request.POST) if form.is_valid(): customer = form.cleaned_data.get('CustId') applist = Appliance.objects.filter(cslic=customer) customer = Account.objects.get(id=customer) return render(request, 'addapp/listapp.html', {'customer' : customer, 'applist' : applist }) else: form = CustForm() return render(request, 'addapp/listcust.html', {'form':form }) This works but if I change the "active" attribute of an Account, the content of the drop down menu does not change until I restart/reload Apache. Could you point me in the right direction? -
Import error for google api client in django project
I am running django version 1.10.3 and I installed google api client with pip like so: pip install --upgrade google-api-python-client When I try to use it with PyCharm/Terminal outside of a django project it works just fine. However, when I try to import it in my django project it throws this error: ImportError: No module named googleapiclient For this import statement: from googleapiclient import discovery I don't use any virtual env and nothing. Does anybody know why this error occurs? Thanks in advance! -
Django: prevent ManyToManyField duplicates into admin items listing
I have troubles in making the equivalent of a group by/select distinct operation in an admin listing view. Simplifying, I have these two models: class Nations(models.Model): label = models.CharField(max_length=200) iso2 = models.CharField(max_length=2, unique=True) class Company(models.Model): countries = models.ManyToManyField(Nations, blank=False) title = models.CharField(max_length=200, blank=False, verbose_name='Title') Every company can have multiple nations associated (I just pick them from company add/edit view) and It's all working fine except the fact that in my company admin listing views I have one duplicate for each nation associated with a singole company. In my model I have also declared a function concatenating all nation names associated to a single company and it works correctly def get_nation_names(self): return " / ".join([s.label for s in self.nations.all()]) get_band_names.short_description = 'Nations' I call this function in my admin.py class CompanyAdmin(admin.ModelAdmin): list_display = ( 'id', 'get_nation_names', 'title' ) ordering = ('title',) search_fields = ['title', 'nation__label'] form = CompanyFormAdmin admin.site.register(Company, CompanyAdmin) The issue I have is a record duplication. I can understand why it happens but I don't know how to prevent it. Basically I need to apply a select distinct on company.pk value in order to avoid this situation: ID company nation_names 1 Company 1 Germany/Ireland/Switzerland 1 Company 1 Germany/Ireland/Switzerland 2 … -
Django - List of all attribute values as strings from query
I am trying to return a list of strings for every possible attribute value as a list of strings. So lets say I have a model with attributes author and isbn. How do I get a list of all the isbns used in all the rows in the database table. So far my progress looks like this: test2 = list(set(Textbook.objects.all().values_list('longschool', flat=True))) test3 = [] for a in test2: test3.append(str(a)) return test3, I have tried a wide combination of using list(), set(), and converting everything to strings. I use the set() just to remove duplicates. Some of my results have a u for unicode as well like: u'isbnnumber' I want to get rid of that as well. I'm trying to use this list as a choices_list for a choice form. Thanks. -
userena-django: Extra fields of the registration form are not shown
I'm using django-userena for a project, I need to add extra fields to the registration form. When you add the fields, they are not displayed on the form. Create a new file named forms.py and use the example given in the documentation: forms.py from django import forms from django.utils.translation import ugettext_lazy as _ from userena.forms import SignupForm class SignupFormExtra(SignupForm): """ A form to demonstrate how to add extra fields to the signup form, in this case adding the first and last name. """ first_name = forms.CharField(label=_(u'First name'), max_length=30, required=False) last_name = forms.CharField(label=_(u'Last name'), max_length=30, required=False) def __init__(self, *args, **kw): """ A bit of hackery to get the first name and last name at the top of the form instead at the end. """ super(SignupFormExtra, self).__init__(*args, **kw) # Put the first and last name at the top new_order = self.fields.keyOrder[:-2] new_order.insert(0, 'first_name') new_order.insert(1, 'last_name') self.fields.keyOrder = new_order def save(self): """ Override the save method to save the first and last name to the user field. """ # First save the parent form and get the user. new_user = super(SignupFormExtra, self).save() # Get the profile, the `save` method above creates a profile for each # user because it calls the manager method … -
Django management command to delete old objects
I'm trying to schedule a delete method so cron can execute it, but I'm coming up with CommandError: error job not completed I stuffed up some where just don't know where :( from datetime import datetime from django.core.management.base import BaseCommand, CommandError from jobs.models import Job class Command(BaseCommand): help = 'Deletes the old jobs past 30days' def handle(self, *args, **options): try: jobs = Job.objects.filter(has_paid=True) for job in jobs: today = datetime.today() pub_date = job.date_published.date() diff = today - pub_date if diff.days >= 30: job.delete() except: # error message raise CommandError('error job not completed') # success message self.stdout.write('Successfully removed all old jobs') -
How can I configure Django setup to not need sudo?
I have pip, virtualenv, and django installed globally. Using py3, default is set using alias line in ~./bash_profile - so py2 packaged with Mac still there. In new virtualenv, activated, but when I try to do anything with django get following error: $ python manage.py migrate Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ImportError: No module named 'django' If I run with sudo (i.e. sudo python manage.py migrate) command works. I know problem is likely how I installed pip, but anyway to fix this without re-installing everything? -
Django GenericRelationship Breaks with Shared Foreign Key
I'm having a bit of an issue with Django's GenericForeignKey and GenericRelation entities; basically, I have several models in my app that need to be capable of attaching to any other model. class GenericEntity(models.Model): some_field = models.CharField(max_length=128) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Meta: unique_together = ('some_field', 'content_type', 'object_id') class TargetEntity(models.Model): generic_entities = GenericRelation(GenericEntity, related_query_name='target_entities') This works quite well; I can query in both directions with the following: my_generic_entity.target_entities.all() my_target_entity.generic_entities.all() However, things get a bit muddled when I have a model that has a OneToOneField that provides its primary key and a GenericRelation to another model: class GenericEntity(models.Model): # ... # same fields as above class ParentEntity(models.Model): some_field = models.CharField(max_length=128) class ChildEntity(models.Model): parent_entity = models.OneToOneField(ParentEntity, primary_key=True, on_delete=models.CASCADE, related_name='child_entity') generic_entities = GenericRelation(GenericEntity, related_query_name='child_entities') So, with this configuration I can only query in one direction: my_parent_entity.child_entity.generic_entities.all() # works my_child_entity.generic_entities.all() # works my_generic_entity.child_entities.all() # does not work The final line doesn't work; I get the following error: *** AttributeError: 'GenericEntity' object has no attribute 'parent_entity_id' So, I suppose the GenericEntity instance is trying to query by the object_id that was set to parent_entity_id (which is automatically generated by the OneToOneField). I would imagine this would work; in … -
Django - Protecting Media files served with Apache with custom login_required decorator
I deployed a Django app using Apache, and I check for authentication in most views using a decorator. @custom_decorator def myView(request): bla bla bla... It's not the @login_required decorator that comes with Django, but it's almost the same thing, except that allows access only to users from certain groups. This works as intended. Also, I'm serving media (user uploaded) files with Apache, like this: Alias /media /path/to/media <Directory /path/to/media> Require all granted </Directory I can access the media files just fine, but the problem is that I can access them even if I'm not logged in, simply by typing the url manually, like: mySite/media/myFile.png Is there a way to limit access to the media files, hopefully using the custom decorator? I stumbled across a similar question: How do you Require Login for Media Files in Django, but unfortunately the answer went way over my head. Thanks in advance! -
Error when trying to retrieve the registered users
I am trying, through a CustomUser model and its serializer to register new users and to display them. Here is my model: class CustomUser(models.Model): user = models.OneToOneField(User) additional_field = models.CharField(max_length=30, default='', blank=True) My serializer (from Django REST Framework Creating custom user): class CustomUserSerializer(serializers.ModelSerializer): additional_field = serializers.CharField(source='customuser.additional_field') class Meta: model = User fields = ('id', 'username', 'password', 'first_name', 'last_name', 'email', 'additional_field') def create(self, validated_data): profile_data = validated_data.pop('customuser', None) user = super(CustomUserSerializer, self).create(validated_data) self.create_or_update_profile(user, profile_data) return user def update(self, instance, validated_data): profile_data = validated_data.pop('customuser', None) self.create_or_update_profile(instance, profile_data) return super(CustomUserSerializer, self).update(instance, validated_data) def create_or_update_profile(self, user, profile_data): profile, created = CustomUser.objects.get_or_create(user=user, defaults=profile_data) if not created and profile_data is not None: super(CustomUserSerializer, self).update(profile, profile_data) An my views, respectively to display and register a user: def get_all_users(request): all_friends = CustomUser.objects.all() serial = CustomUserSerializer(all_friends, many=True) json_data = JSONRenderer().render(serial.data) return HttpResponse(json_data, content_type='application/json') @api_view(['POST']) def register_new_user(request): if request.method == 'POST': print('POST request !') print(request.data) serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(): serializer.save() print('save friend!') return HttpResponse(status.HTTP_201_CREATED) else: print(serializer.errors) return HttpResponse(status.HTTP_403_FORBIDDEN) While I am able to register a user with the following piece of code: import requests import json json_data = {'username': 'mylogin99', 'password': 'mypassword', 'email': 'mymail99@wanadoo.fr', 'additional_field' : 'myaddfield'} r = requests.post('http://127.0.0.1:8000/register_new_user', json=json_data) I am unable to display the registered users, … -
Django Rest Framework Validation Layer
I've worked with Django for several years and have been following the various conventions for handling model, form, and REST API endpoint validation. I've tried a lot of variations for ensuring overall data integrity, but I've hit a bit of a stumbling block recently. Here is a brief list of what I've tried after looking through many articles, SO posts, and tickets: Validation at the model level; namely, ensuring all of my custom constraints are matched before calling myModel.save() by overriding myModel.clean() (as well as field-specific and unique together methods). To do this, I ensured myModel.full_clean() was called in myForm.clean() (for forms -- and the admin panel actually already does this) and mySerializer.validate() (for DRF serializers) methods. Validation at the form and serializer level, calling a shared method for maintainable, DRY code. Validation at the form and serializer level, with a distinct method for each to ensure maximum flexibility (i.e. for when forms and endpoints have different constraints). Method one seems the most intuitive to me for when forms and serializers have identical constraints, but is a bit messy in practice; first, data is automatically cleaned and validated by the form or serializer, then the model entity is instantiated, and … -
What is the best way to keep persistent user state across different browsers in Django
In my app in Django, I have two user states namely - 0 and 1 which are stored in a database. When a user logs in, his state becomes 1. He can change this state 0 from browser. Now if he logs in again from a different browser, his state will be picked up from database and shown as it is in the browser. If he changes state in one of the browser (user session) now, how to make it reflect it in the different browser without it polling from the server. What is the way - websockets, channels in Django, Redis or is there any better way to achieve it? -
Djinja can't find location
I am workin on a django app source: https://github.com/martin-varbanov96/fmi-fall-2016/tree/master/django/click_bait/miranda/home and I have a template which works perfectly fine on its own. I want to load a side template using this code: home/templates/home/blog.html: {% block content %} {% endblock %} Which should load this file home/templates/home/single_post.html: {% extends "home/blog.html" %} {% block content %} <li> <img src="images/blog-image1.png" alt=""> <div> <h1>PREPARING FOR A MARATHON</h1> <p>Our website templates are created with inspiration, checked for quality and originality and meticulously sliced and coded. What’s more, they’re absolutely free! You can do a lot with them. You can modify them...</p> <a href="blogsinglepost.html" class="more">keep Reading</a> </div> </li> {% endblock %} But for some reason it can't quite get the path. Any solutions? -
Why django collectstatic doesnt work correctly?
When i make collectstatic. It doesnt work, and create static folder and collect into D:\static\ What's problem? My settings work uncorrect! my settings: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), 'D:\DjangoProjects\mysite'] STATIC_ROOT = '/static/' -
Configuring VirtualHost to run a second website, issue with <VirtualHost *:8080>, error with `Listen`
I am trying to figure out how to host a second Django website from my VM and I am wondering if somebody could see where I have made any obvious mistakes. Currently whichever site is set to <VirtualHost *:80> works. I learned from this answer that I should specify the second website to <VirtualHost *:8080>. However when I try to use Listen I get the below error when I try to reload apache Job for apache2.service failed. See 'systemctl status apache2.service' and 'journalctl -xn' for details. Does anyone understand what might be going wrong? Why does <VirtualHost *:80> but not <VirtualHost *:8080>? And why do I get the error when I specify Listen? I am using Debian 8.5, Apache 2.4.10 and mod-wsgi 4.3.0-1. Listen 80 <VirtualHost *:80> ServerName myserver.scss.tcd.ie/bias_experiment/ Alias /bias_experiment/static/ /var/www/bias_experiment/static/ <Directory /var/www/bias_experiment/static> Order deny,allow Allow from all </Directory> WSGIScriptAlias /bias_experiment /var/www/bias_experiment/src/bias_experiment/index.wsgi <Directory /var/www/bias_experiment/src/bias_experiment> <Files index.wsgi> Order deny,allow Allow from all </Files> </Directory> </VirtualHost> Listen 8080 <VirtualHost *:8080> ServerName myserver.scss.tcd.ie/bias_experiment_two/ Alias /bias_experiment_two/static/ /var/www/bias_experiment_two/static/ <Directory /var/www/bias_experiment_two/static> Order deny,allow Allow from all </Directory> WSGIScriptAlias /bias_experiment_two /var/www/bias_experiment_two/src/bias_experiment/index.wsgi <Directory /var/www/bias_experiment_two/src/bias_experiment> <Files index.wsgi> Order deny,allow Allow from all </Files> </Directory> </VirtualHost> Any help is as always, much appreciated. -
How to convert tree data into a list to used in choice_list?
I'm using treelib to generate trees, now I need convert to list, so I want to use them into choice_list in my category. For example: from treelib import Tree, Node def create_family_tree(): tree = Tree() tree.create_node("Harry", "harry") # root node tree.create_node("Jane", "jane", parent="harry") tree.create_node("Bill", "bill", parent="harry") tree.create_node("Diane", "diane", parent="jane") tree.create_node("Mary", "mary", parent="diane") tree.create_node("Mark", "mark", parent="jane") return tree def example(desp): sep = "-"*20 + '\n' print(sep + desp) if __name__ == '__main__': tree = create_family_tree() example("Tree of the whole family:") tree.show(key=lambda x: x.tag, reverse=True, line_type='ascii-em') print(tree.all_nodes()) I have tried with tree.all_nodes(). but gave me Result: [, ...] -
Rendering user submitted text with markdown in Django template
I'm not able to get markdown to render correctly in the Django template. I have some body of text submitted by a user which I am rendering as markdown within models.py - in the recommended way class Review(models.Model): user = models.ForeignKey(User) body = models.TextField() def rendered_text(self): html = bleach.clean(markdown.markdown(self.body)) return html Then in my template, I try and display it with {{ review.rendered_text|safe }} However, this displays the html <p> tags. input: test # no space after word test # two space after word test # no space test output <p>test test<br/> test</p> <p>test</p> bonus question Is there way to get markdown to only render empty lines as a break and not double spaces? -
How to move nested routing into separate urls.py?
I was wondering if I could get your help on this. I have a urls.py which contains the following: router = routers.SimpleRouter() # AccountViewSet in accounts app router.register(r'accounts', AccountViewSet) # ProjectViewSet in projects app router.register(r'projects', ProjectViewSet) accounts_router = routers.NestedSimpleRouter(router, r'accounts', lookup='account') # AccountProjectsViewSet in projects app accounts_router.register(r'projects', AccountProjectsViewSet) As you can see, accounts and projects are quite closely connected due to nested routing. I'd like to move the accounts routing logic into accounts/urls.py, and the projects routing logic into projects/urls.py. My attempts at this so far cause the following error: RuntimeError: parent registered resource not found Is it even possible to separate this logic, or does it need to be together? Thanks for your advice. -
Django: declare key aliases into objects.filter function
I have a labelling problem that should be pretty easy but strangely I cannot find a way out to do that. I have this filtering function def search(cls, query): return cls.objects.filter(label__icontains=query) And my model is just made up by a key and a label field. What I obtain looks like this [{"id": 20, "label": "Title 1"}, {"id": 22, "label": "Title 2"}] But I want just in my output use "name" instead of "label" and "key" instead of "id" alias, like this: [{"key": 20, "name": "Title 1"}, {"key": 22, "name": "Title 2"}] How can I declare these aliases directly into my filtering function witouth coding that elsewhere? -
How to get separate total amount of records for given list of ids in django
I am working with a question answer forum. What I am trying to do this is pretty straightforward. In questions list page, I want to show total number of answers a question have. I know how to get all answers amount from a question record - answer_records = Answer.objects.filter(question = question_record).count() But, I want a single query which generates separate answer records amount for all given question records. So far I have tried - answer_records = Answer.objects.filter(question__in = question_records).count() It only generates single count of all question records. Here is my model - class Question(models.Model): question_text = models.CharField(max_length = 500) pub_date = models.DateTimeField('date published') views = models.BigIntegerField(default = 0) status = models.BooleanField(default = True) def __str__(self): return self.question_text class Answer(models.Model): question = models.ForeignKey(Question, on_delete = models.CASCADE, blank = True, null = True) answer_text = models.TextField(default = '') pub_date = models.DateTimeField(default = timezone.now) def __str__(self): return self.answer_text How can I do that? Thanks for your help! -
How do I compare the real time and a variable that has a time in Django?
I'm getting an error like this but I don't know why TypeError at /posts/sadako/ can't compare offset-naive and offset-aware datetimes -
Django add a footer script container into Media class
What I need to do is to declare a list of .js files into Main class that must be printed on the footer and not in the head section of the page by extrahead block. I'll call my new tuple footerjs and this is how my Media class declaration should look like: class MyWidget(forms.TextInput): class Media: css = { "all": ("css/my_css_1.css",) } js = ( "my/path/file1.js", "my/path/file2.js" ) footerjs = ( "my/path/file3.js" ) I guess my footerjs block should look like this, so I can place it at the very end of my base.html template. {% block footerjs %}{{ block.super }} {{ media.footerjs }} {% endblock %} My question is: how can I teach django that Media class can also contain a footerjs tuple that can be printed into blocks? -
Filter objects if all its foreignkeys are in a dictionary
what i need is to allow users to access list of Parent objects by filtering their related objects `Kid' We have a dictionary that has a 100 kid. and parents that have about 5 kids in average. if the kids in 1 parent object are all in the dictionary I want them to be listed. But not all 100 kid have to be related to the parent object. e.g if the parent have 4 kids who are in the dictionary and 1 that is not. Then do not include them. I have the code below models.py : class Parent(models.Model): title = models.CharField(max_length=250) class Kid(models.Model): cities = ( ('city1', city1), ('city2', city2) ) family = models.ForeignKey(Parent) title = models.CharField(max_length=250) age = models.CharField(max_length=250) city = models.CharField(choices=cities) Views.py : def index(request): my_pattern = ( (name=samy, age_lt=15, city=paris), ) filter_ids = Kid.objects.filter(my_pattern).values_list('parents_id', flat=True).distinct() exclude_ids = Kid.objects.exclude(my_pattern).values_list('parents_id', flat=True).distinct() parents = Parent.objects.filter(id__in=filter_ids).exclude(id__in=exclude_ids) template = 'index.html' context = {'parents': parents} return render(request, template, context) so with my current view function shown above. all the kids have to be in 1 parent!!! help please! -
django rest not sending verification email
I am using django rest auth default register form like following; after I post this form, on login page it says confirmation e-mail sent to "releated_email_adress" However, the mail is not coming. I am running this rest framework on my localhost. Maybe that's the reason for this issue. However, I couldn't find out the solution. -
Iterating through a list twice in django template
In my django template I'm creating two tabs - 'All events' and 'Your events'. In the first tab I want to list all of the events and in the second tab I want to have a filtered list of events (events that user is attending). To do this I'm looping twice over the same list. The first iteration is all good, but the second doesn't give any output. How can I fix it? Posting my html template below. {% block content%} <ul class="nav nav-tabs" style="padding-top: 60px"> <li class="active"><a data-toggle="tab" href="#allevents">All events</a></li> <li class=""><a data-toggle="tab" href="#yourevents">Your events</a></li> </ul> <div class="container-fluid"> <h1>Event list</h1> </div> <div class="tab-content"> <div id="allevents" class="tab-pane fade in active"> {% for event, is_att in event_zip %} <p> {{ event.name }} </p> DISPLAY ALL EVENTS HERE - displays correctly {% endfor %} </div> <div id="yourevents" class="tab-pane fade"> {% for event, is_att in event_zip %} <!-- {% if is_att %} --> <p> {{ event.name }} </p> DISPLAY FILTERED EVENTS HERE - doesn't give any output Does not work even with 'if' statement commented out. <!-- {% endif %} --> {% endfor %} </div> </div> {% endblock %}