Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django1.9 after installation is not recognised by the command prompt
PROBLEM Even after installation of django, typing the command django-admin --version shows up the message failed to create the process. what I've done I have installed python version3.6.1 ,pip version 9.0.1 ,easy_install version28.0.1 and then installed django version 1.9 using easy_install. In the Environment variables of mycomputer I've set the PATH both to python folder and the scripts folder. -
Getting list of many to many objects
class Team(models.Model): team_name = models.CharField(max_length=50, null=False) def __str__(self): return self.team_name class Tournament(models.Model): types = ( ('Round', 'Round'), ('Knockout', 'Knockout'), ) teams = models.ManyToManyField(Team, related_name='tournament_teams') tournament_name = models.CharField(max_length=50, null=False) tournament_type = models.CharField(choices=types, max_length=40, null=False) def __str__(self): return self.tournament_name class MatchRound(models.Model): team_a_id = models.ForeignKey(Team, related_name="team_a") team_b_id = models.ForeignKey(Team) date = models.DateTimeField(null=True) team_a_score = models.IntegerField(null=True) team_b_score = models.IntegerField(null=True) tournament_id = models.ForeignKey(Tournament, on_delete=models.CASCADE, null=True) @receiver(post_save, sender=Tournament) def create_match_round(sender, **kwargs): type = kwargs.get('instance').tournament_type if type == 'Round' and kwargs.get('created', False): teams = kwargs.get('instance').teams.all() schedule = create_schedule(teams) for round in schedule: for match in round: team_a_id = match[0] team_b_id = match[1] tournament_id = kwargs.get('instance') game = MatchRound.objects.create(team_a_id=team_a_id, team_b_id=team_b_id, tournament_id=tournament_id) I am trying to create a schedule for a tournament. So, I set up a trigger on MatchRound model and I am trying to get the teams of the tournament when it's created. However, the following line teams = kwargs.get('instance').teams.all() returns to an empty query set. I couldn't figure it out the problem. -
Problems to serialize property (getter and setter) from a model using Django Rest Framework
I want to use a property (including setter) from my model in a Serializer, but apparently, the setter is never called. models.py class Awesome(models.Model): _value = models.TextField() def set_value(self, value): self._value = value def get_value(self): return self._value value = property(get_value, set_value) serializers.py class AwesomeSerializer(serializers.ModelSerializer): class Meta: model = Awesome fields = ('value',) views.py class AwesometViewSet(viewsets.ModelViewSet): queryset = Awesome.objects.all() serializer_class = AwesomeSerializer On this scenario suggested above, when I make a GET the getter work fine, but when I make a POST the serializer doesn't call the setter. What wrong I made?! I am using following versions: python == 3.6.1 Django == 1.11.2 djangorestframework == 3.6.3 -
Docker+Django psycopg2.OperationalError: could not connect to server: Connection refused
I'm trying to setup docker-compose with django and postgres my docker-compose is version: '2' services: nginx: image: nginx:latest container_name: ng01 ports: - "8000:8000" volumes: - .:/code - ./misc/nginx:/etc/nginx/conf.d - ./app/static:/static depends_on: - web db: restart: always image: postgres:latest environment: - POSTGRES_DB=dbuser - POSTGRES_PASSWORD=dbpassword - POSTGRES_USER=dbroot volumes: - /var/lib/postgresql/data expose: - '5432' web: build: . command: bash -c "python manage.py collectstatic --noinput && python manage.py migrate && cd ../code && gunicorn project.wsgi -b 0.0.0.0:8000" volumes: - .:/code expose: - "8000" depends_on: - db and my web service throws the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? How to fix it? Postgresql is running on my local machine and I can launch project with manage.py runserver without docker -
How to keep the previous version live while doing a scheduled publishing in wagtail?
In wagtail if I have a page that's already live, and I edit this page and do a scheduled publishing in a later time it seems that this page will go down until the scheduled time comes. I wonder if it's possible in wagtail to keep the page live while do a schedule publishing? -
Wagtail, how to reverse urls?
I have a Django site which contains a blog. To get it up and running quickly I just added some static blog posts using Django's TemplateView. I have now added Wagtail and set up a blog platform using that. The problem I now have is linking to blog posts from elsewhere in the site. Is there a way to reverse the urls for teh blog posts created in Wagtail (using the slug)? -
Django Forms: How to add icons instead or in addition to the form fields
Given that we live in the emjoi era, you may want to have a form to ask for user input using icons. Say for example, you want to find out which sport the user prefers. Instead of or in addition to the text, you may want to display the icon for the choice (e.g. showing a basketball for basketball choice). How do you go about this in Django in an automated way. I understand that I can manually render each field and add HTML to it, but that's more hacking your way through. What if I want to render so many fields in a formset with so many choices for each field of each form using a for loop in the template and do not look forward to manually going through the fields and add the icon for each field of each form. -
Python Django cache vs store in model field? Which is more efficient?
My view displays a table of data (specific to a customer who may have many users) and this table takes up a lot of computational resource to populate. A customers data changes 4/5 times a week, usually on the same day. Caching is an obvious solution to this but I was wondering if Django's cache framework is significantly more efficient than creating a Textfield at the customer level and storing the data there instead? I feel it's easier to implement (and clear the Textfield when the data changes) but what are the drawbacks and is there anything else I need to look out for? (problems if the dataset gets too big? additional fields in the model etc etc???) Any help would be much appreciated! -
Django - NoReverseMatch. What am I overlooking?
My app name is 'canyonero'. I'm using Django 1.11 on Pypy 5.6.0. The app is enabled in settings.py: INSTALLED_APPS = [ ... 'canyonero.apps.CanyoneroConfig', ... ] There is a route to the app in my project-level urls.py: urlpatterns = [ ... url(r'^product/canyonero/', include('canyonero.urls', namespace='canyonero')), ... ] There is a namespaced URL to be resolved in my app-level urls.py: app_name = 'canyonero' urlpatterns = [ ... url(r'^events/(?P<pk>\d)/$', EventDetail.as_view(), name='event'), ... ] And then this template tag gives me no end of grief: {% extends 'common/content.html' %} {% load static %} <a href="{% url 'canyonero:event' pk=obj.event_id %}"></a> The error I'm getting is: NoReverseMatch: Reverse for 'event' with keyword arguments '{u'pk': 532742}' not found. 1 pattern(s) tried: [u'product/canyonero/events/(?P<pk>\\d)/$'] 532742 is a valid primary key for a valid record (confirmed with Event.objects.get() in the shell), so it's not that. Is there anything obvious that I'm overlooking? -
ValueError('Prefetch querysets cannot use values().')
I'm using Django 1.11 and django-model-utils 3.0.0's InheritanceQuerySet. I'm getting the following error ValueError('Prefetch querysets cannot use values().') which is surprising given this fix. However, I noticed that the exception is thrown after the following if statement: if queryset is not None and not issubclass(queryset._iterable_class, ModelIterable): raise ValueError('Prefetch querysets cannot use values().') The Queryset class is iterable so i'm not sure what's going on. Here's the full traceback: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/.virtualenvs/tcj/lib/python2.7/site- packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/.virtualenvs/tcj/lib/python2.7/site- packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/.virtualenvs/tcj/lib/python2.7/site- packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/.virtualenvs/tcj/lib/python2.7/site- packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Projects/tcj/mainsite/management/commands/cron_hook.py", line 412, in handle getattr(CronFunctions, task_name)(*args) File "/Projects/tcj/mainsite/management/commands/cron_hook.py", line 119, in elasticsearch_reindex tcj_elasticsearch.reindex_listings(start_id=start_id, end_id=end_id) File "/Projects/tcj/TCJ/services/one_offs.py", line 452, in do_func return func(*args, **kwargs) File "/Projects/tcj/TCJ/tcj_elasticsearch.py", line 1602, in reindex_listings listings = BaseListing.listings.with_prefetches().using(db).indexable()\ File "/Projects/tcj/business/models/listings.py", line 419, in with_prefetches ), to_attr='active_student_responses_prefetched'), File "/.virtualenvs/tcj/lib/python2.7/site- packages/django/db/models/query.py", line 1312, in __init__ raise ValueError('Prefetch querysets cannot use values().') ValueError: Prefetch querysets cannot use values(). -
Deploy Django SECRET_KEY
I need some help. settings.py: SECRET_KEY = 'fpod51u&htaw-99=vl6c8vdqlt$yydvlr)p&aob5f9pd2t9p+8' but returns the error: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. whats happens? -
Can't access csrf cookie sent by server via Set-Cookie (Django + Angular2)
I'm experimenting with an app running on Angular 2 in the frontend and Django as API and I can't access the CSRF cookie sent from Django. As you can see, I am getting back the cookie from the server but I cannot access it from the browser (document.cookie) or Angular 2 (using the ng2-cookies module). Everything was working while testing on localhost, now client and server are running on different hosts and this might be the reason of the problem. Client running on https://django-angular2-movies.firebaseapp.com/ Server running on https://glacial-shore-18891.herokuapp.com This is part of the settings I'm using on Django: settings.py CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = False CSRF_TRUSTED_ORIGINS = ['django-angular2-movies.firebaseapp.com'] ALLOWED_HOSTS = ['*'] Other things that I have tried, but didn't help: Removing the CSRF_TRUSTED_ORIGINS setting Adding CSRF_COOKIE_DOMAIN = 'django-angular2-movies.firebaseapp.com' Using { withCredentials: true } in the request sent from the client Using the @ensure_csrf_cookie decorator on Django views What am I doing wrong? Thanks -
create custom registeration form
i have extende the user model now i want to make registeration form to be extended to include my approach my method dont create either user or user profile here is my models.py class UserProfile(models.Model): s=(('m','Male'),('f','Female')) user=models.OneToOneField(settings.AUTH_USER_MODEL ) Country= models.CharField(max_length= 25, default= "NOT_PROVIDED") date_of_birth=models.DateField(blank=True,null=True) gender=models.CharField(max_length=1,choices=s) def __str__(self): return self.user.username class Meta: db_table = '' managed = True verbose_name = 'UserProfile' verbose_name_plural = 'UserProfiles' def create_Profile(sender,**Kwargs): if Kwargs['created']: user_profile=UserProfile.objects.create(user=Kwargs['instance']) post_save.connect(create_Profile,sender=User) my forms.py class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' ) def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user class UserProfileForm(forms.ModelForm): date_of_birth=forms.DateField(widget=forms.SelectDateWidget(empty_label=("Choose Year", "Choose Month", "Choose Day"),years=[x for x in range(1930,2018)]),) class Meta: model=UserProfile fields=('date_of_birth','Country','gender') my views.py def register(request): if request.method =='POST': user_form = RegistrationForm(request.POST) profile_form=UserProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): return redirect("/") else : return render(request, 'accounts/reg_form.html', {'user_form': user_form, 'profile_form':profile_form}) else: user_form = RegistrationForm() profile_form=UserProfileForm() args = {'user_form': user_form, 'profile_form':profile_form} return render(request, 'accounts/reg_form.html', args) when i save my form it does not create user or user profile i can't figure what should i do thanks in advance -
How to do auto login in django-allauth
How to call django-allauth login function in my custom function, so that I need to auto login the user with credentials provided. -
Simple way to implement current month in Django template?
I am looking for a simple way to implement the current month in my template, in the spelled out format, e.g. "June". So this: "The current month is:" {{ code here }} should produce The current month is: June" I could create my own filters however I wanted to know if there was something akin to {% now "Y" %} - which works for the current year. -
How to write in Django a custom management command which takes a URL as a parameter?
I am learning to write custom management commands in Django. I would like to write a command which would take a given URL as a parameter. Something like: python manage.py command http://example.com I've read a documentation, but it is not clear to me how to do this. But I can write a command saying 'Hello World!';) -
django classbased view not accepting view_args and view_kwargs
I am using django 1.8. I am using django.views.generic.View class in one of my View. class CommonView(View): http_method_names = ["get", "post"] def get(self, request, *args, **kwargs): return render(request, 'template.html', {}) in urls.py i added url(r'^common/$',CommonView.as_view()), I have written a middleware where i am doing some work with view response and overridden process_view method class CommonMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): response = view_func(request, *view_args, **view_kwargs) """ Do something""" return response but in this line response = view_func(request, *view_args, **view_kwargs) I am getting error __init__() takes exactly 1 argument (3 given) Request Method: POST Request URL: http://127.0.0.1:8000/common/ Django Version: 1.8 Exception Type: TypeError Exception Value: __init__() takes exactly 1 argument (3 given) -
django admin model for non superuser missing
I have a django (1.11.1) project with different apps and models. myproject app1 models.py admin.py app2 models.py admin.py In the django admin this is resolved correctly when logged in as superuser Authentifizierung und Autorisierung Benutzer (User) Gruppen (Groups) App1 App1_model1 App1_model2 App2 App2_model1 App2_model2 Now I created a group1 and I wanted to grant permissons to app1 for user1 in that group. But even if I grant all availible permissions to group1, when user1 is logged in to the admin he only sees Authentifizierung und Autorisierung Benutzer (User) Gruppen (Groups) App2 App2_model1 App2_model2 but App1 is missing. I also noticed that in the permissions, all permissions start with app2: app2|permission1_app2, app2|permission2_app2, app2|permission1_app1, app2|permission2_app1, ... in App1 models.py, I import models from App2 that are foreign key fields models.py from django.db import models from app2.models import App2_model1, ... class App1Model1(models.Model): app2_model1 = models.ForeignKey(App2_model1, ... Any ideas how to fix this? -
Trying to implement an ajax pagination
I am trying to implement pagination into my project but for some reasons beyond my comprehension, when i scroll down to the bottom, it does not load more content. Im thinking the issue could be in the javascript attached to the list.html below but I still dont know where exactly to fix. Kindly point me to right direction My code: def user_list(request): users = User.objects.filter(is_active=True) paginator = Paginator(users, 10) page = request.GET.get('page') try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: if request.is_ajax(): return HttpResponse('') users = paginator.page(paginator.num_pages) if request.is_ajax(): return render(request, 'account/user/list_ajax', {'section': 'people', 'users': users} ) return render(request, 'account/user/list.html', {'section': 'people', 'users': users}) list_ajax.html {% load thumbnail %} {% for user in users %} <div class="people"> <a href="{{ user.get_absolute_url }}"> {% thumbnail user.profile.photo "180x180" crop="100%" as im %} <a href="{{ user.get_absolute_url }}"> <img src="{{ im.url }}"> </a> {% endthumbnail %} </a> <div class="info"> <a href="{{ user.get_absolute_url }}" class="title"> {{ user.username }} </a> </div> </div> {% endfor %} list.html {% block content %} <h1>People</h1> <div id="user-list"> {% include "account/user/list_ajax.html" %} </div> {% endblock %} {% block domready %} var page = 1; var empty_page = false; var block_request = false; $(window).scroll(function() { var margin = $(document).height() - … -
Django pinax app changes in urls.py
I am trying to change a pinax app. After installing pinax-user-account app I have two directories, mysite and mysiteenv. Once I change the urls.py in the mysiteenv I cannot see the changes applied. I guess I need to recompile the app as the main urls.py in mysite respond well after changes. How can I do that? I am receiving a NoReverseMatch at search_profile, but I added url(r"^search/$", ProfileSearchView.as_view(), name="search_profile"), into account/urls.py of mysiteenv -
Display the hyphen
Actually, when I translate with ugettext_lazy, in my django.po file, I have #: models.py:532 msgid "Reference 2 fullname" msgstr "Référence 2 - Nom complet" However the words in french are not correctly displayed. In fact, the hyphen is never showed up, i.e. it displayed Référence 2 Nom complet. How could I modify those line so that it will display correctly Référence 2 - Nom complet? -
Query a many to many field of referenced table using ORM
My models are as follows: class AppUser(models.Model): id = models.AutoField(primary_key=True) user = models.OneToOneField(User) states = models.ManyToManyField(State) class ABC(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) email = models.EmailField() app_user = models.ForeignKey(AppUser, null=True, blank=True) I want to query my database for list of objects present in ABC model and I want to filter it according to the list of States. I am trying something like this: ABC.objects.filter(app_user__states__in = state_list).values('id','name') But this is not working. Can I even access a many to many field like this or do I need to create a custom through table. -
Django ChoiceField is automatically adding a text box..?
My Django form is automatically adding a text input field as well as a drop down menu. I want a drop down menu to filter the results. Here is my code: forms.py from haystack.forms import FacetedSearchForm from django import forms class FacetedProductSearchForm(FacetedSearchForm): desc = forms.ChoiceField(choices=[('n', 'Ascending'), ('y', 'Descending')], label='', initial='y') def __init__(self, *args, **kwargs): data = dict(kwargs.get("data", [])) self.retailer = data.get('retailer', []) self.location = data.get('location', []) super(FacetedProductSearchForm, self).__init__(*args, **kwargs) def search(self): sqs = super(FacetedProductSearchForm, self).search() if self.cleaned_data['desc'] == 'y': query = None sqs = sqs.order_by('-retailer') else: sqs = sqs.order_by('retailer') return sqs results.html <div class="tab-filter"> <form id="searchformsort" action="" method="get" > <select id=sort class="selectpicker" data-style="btn-select"/> <option>Sort by</option> <option> {{ form }} </option> </select> </form> </div> -
Django - fabric on server
I would like to call "python manage.py installtasks" on my serwer but it doesn't work. On my local computer it works fine: @receiver(config_updated) def constance_updated(sender, key, old_value, new_value, **kwargs): local('python3 manage.py installtasks') On my server (this is a part of my admin.py file by the way): env.hosts = ['my_host'] run('python manage.py installtasks') I tried also: run('/usr/home/my_user/.virtualenvs/app/bin/python /usr/home/my_user/domains/host/public_python/manage.py installtasks') I get only "waiting for [host]" on bottom of my browser and nothing happens. Is there any way to see what is going on (any output)?. How should I configure fabric? -
My form in Python Django is not submitting
I'm making a form involving making a schedule using Django, but for some reason the form is not submitting. I checked using SQLite DB Browser and nothing seems to be submitting. # choices.py COURSE_NAME_CHOICES = (('a-plus', 'A+ PC Technician'), ('advance java', 'Advance Java/J2EE/Weblogic/Websphere'), ('a-s master', 'Agile-Scrum Master'), ('android mobile', 'Android Mobile Development'), ('autocad', 'AutoCAD'), ('bio-info', 'Bio-info Database Training course'), ('ba', 'Business Analyst (BA'), ('c-sharp', 'C# .Net'), ('ccna', 'CCNA Voice'), ('ceh', 'Certified Ethical Hacking'), ('checkpoint', 'Checkpoint Security Firewall Course'), ('ccie', 'Cisco CCIE IP Telephony')) LOCATION_CHOICES = (('south_plainfield', 'South Plainfield'), ('hackensack', 'Hackensack'), ('fairfield', 'Fairfield'), ('eatontown', 'Eatentown')) ROOM_CHOICES = (('A', 'South Plainfield A: CNA/MCSE'), ('B', 'South Plainfield B: SAS/.Net'), ('C', 'South Plainfield C: Cisco'), ('D', 'South Plainfield D: QA/.Net/Java'), ('E', 'South Plainfield E: Weblogic/Java/MCSE'), ('F', 'South Plainfield F: Unix/Linux'), ('G', 'South Plainfield G: Oracle/Clinic/Datawarehouse')) START_TIME_CHOICES = (('eight-thirty am', '8:30 AM'), ('nine am', '9:00 AM')) END_TIME_CHOICES = (('eight-thirty am', '8:30 AM'), ('nine am', '9:00 AM')) INSTRUCTOR_CHOICES = (('adewale', 'Adewale Akinokun'), ('ajay', 'Ajay Kumar')) TOTAL_HOURS_CHOICES = (('six', 6), ('ten', 10)) HOURS_PER_CLASS_CHOICES = (('two_and_half', 2.5), ('three', 3)) FREQUENCY_CHOICES = (('sunday', 'Sunday'), ('monday', 'Monday'), ('tuesday', 'Tuesday'), ('wednesday', 'Wednesday'), ('thursday', 'Thursday'), ('friday', 'Friday'), ('saturday', 'Saturday')) STATUS_CHOICES = (('active', 'Active'), ('inactive', 'Inactive'), ('expired', 'Expired'), ('pending', 'Pending')) INTERVAL_CHOICES = (('one_day', …