Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to deploy a Django app in AWS EC2?
I have an app API build using django rest framework. Now I use manage.py runserver to run it. What is the best way to deploy this app in my ec2 server? -
django project urls.py syntax error
I have downloaded a django project and run ./manage.py runserver. And the code generate following error url(f'{API_PREFIX}/', include('rest_framework.urls', namespace='api')), ^ SyntaxError: invalid syntax urls.py is like this. API_PREFIX = r'^v(?P<version>[0-9]+\.[0-9]+)' urlpatterns = [ ... url(f'{API_PREFIX}/', include('rest_framework.urls', namespace='api')), ... ] I am new to django and please help me how to fix it. -
Order of Django Data Migrations
I am using the sites application (django.contrib.sites) in my application. I have created a data migration which sets the values of the current site when the database is created, however my data migration is being executed before the sites application is installed. How can I force my data migrations to be executed after the sites migrations. This project is intended to be a seed to be used for other projects, and I often delete the database and start fresh so it is important that the initial makemigrations/migrate commands work out of the box. My migrations file exists in the main application folder: project folder ..+app ....+migrations ......-0001_initial.py Here is the content of the migration file: from __future__ import unicode_literals from django.db import migrations def set_development_site(apps, schema_editor): Site = apps.get_model('sites', 'Site') current= Site.objects.get_current() current.domain = "localhost:8000" current.name = "Django-Angular-Webpack-Starter" current.save() class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.RunPython(set_development_site), ] And the output from the python manage.py migrate command: Operations to perform: Apply all migrations: admin, app, auth, authentication, authtoken, contenttypes, sessions, sites Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying authentication.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying app.0001_initial...Traceback (most recent call last): File … -
Django Error: Deadlock found when trying to get lock; try restarting transaction
Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 223, in get_response response = middleware_method(request, response) File "/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/middleware.py", line 49, in process_response request.session.save() File "/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/db.py", line 64, in save obj.save(force_insert=must_create, using=using) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 710, in save force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 738, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 822, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 861, in _do_insert using=using, raw=raw) File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 127, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 920, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 963, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.py", line 124, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute self.errorhandler(self, exc, value) File "/usr/local/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue OperationalError: (1213, 'Deadlock found when trying to get lock; try restarting transaction') -
Django filter package
I have installed django filter the docs are here https://django-filter.readthedocs.io/en/master/ my code is from django import forms import django_filters from facilities.models import Facility from categories.models import Category from amenities.models import Amenity from locations.models import Location from catalogue.models import Business class BusinessFilter(django_filters.FilterSet): facilities = django_filters.ModelMultipleChoiceFilter( label='Facility', name='facilities', lookup_expr='contains', widget=forms.CheckboxSelectMultiple(), queryset=Facility.objects.all(), required=False) ammenities = django_filters.ModelMultipleChoiceFilter( label='Amenities', name='amenities', lookup_expr='contains', widget=forms.CheckboxSelectMultiple(), queryset=Amenity.objects.all(), required=False) seasonrate__price = django_filters.NumberFilter(name='seasonrate__price') location = django_filters.ModelChoiceFilter( label='Regions', queryset=Location.objects.regions(), required=False, initial=0) category = django_filters.ModelChoiceFilter( label='Category', queryset=Category.objects.all(), required=False, initial=0) class Meta: model = Business fields = { 'seasonrate__price': ['lt', 'gt'] } def __init__(self, *args, **kwargs): print(dir(self)) category_type = self.data['category_type'] print(category_type) category_type_form = getattr(Facility, str(category_type)) if category_type_form: self.fields['facilities'].queryset = Facility.objects.filter( type=category_type_form) self.fields['amenities'].queryset = Amenity.objects.filter( type=category_type_form) self.fields['category'].queryset = Category.objects.filter( type=category_type_form) super(BusinessFilter, self).__init__(*args, **kwargs) in my views.py i have search_form = BusinessFilter(request=self.request.GET, data={'category_type': category_type}, queryset=business_list) i can't pass the category type so as to customize querysets in my form. I tried also with kwargs with no success -
Post json data getting csrf token missing or invalid
Would appreciate if someone can help me find the problem. I know there are a lot of solutions regarding this specific problem. Have been stuck here for a quite a long time now. My code Views class HolidayList(ListCreateAPIView): queryset = Holiday.objects.all() serializer_class = HolidaySerializer permission_classes = [IsAdminUser, IsAuthenticated] authentication_classes = [SessionAuthentication,BasicAuthentication] url url(r'^$', HolidayList.as_view(), name='holiday-list-api'), Getting this error {"detail":"CSRF Failed: CSRF token missing or incorrect."} my rest framework configuration REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'base.csrf_exempt.CsrfExemptSessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.IsAdminUser', ), } Tried to use CsrfExempt but no luck. What am i missing here ? from rest_framework.authentication import SessionAuthentication class CsrfExemptSessionAuthentication(SessionAuthentication): def enforce_csrf(self, request): return -
Django template iteration through structure
Good morning I have the following structure coming from the backend: sentences_info = [ { "keyword": "", "sentences": [ { "sentence_id": "", "sentence": "" }, ... ], ... }, ... ] I need to put this structure in my template, in a checkbox form, like this: <form> <h3>Keyword: {{ keyword }}</h3> <div class="form-check"> <label class="form-check-label"> <input type="checkbox" class="form-check-input" id="{{ sentence_id }}" value="{{ sentence_id }}"> {{ sentence }} </label> <label class="form-check-label"> <input type="checkbox" class="form-check-input" id="{{ sentence_id }}" value="{{ sentence_id }}"> {{ sentence }} </label> ... </div> <h3>Keyword: {{ keyword }}</h3> <div class="form-check"> <label class="form-check-label"> <input type="checkbox" class="form-check-input" id="{{ sentence_id }}" value="{{ sentence_id }}"> {{ sentence }} </label> <label class="form-check-label"> <input type="checkbox" class="form-check-input" id="{{ sentence_id }}" value="{{ sentence_id }}"> {{ sentence }} </label> ... </div> ... </form> I tried some iterations, but can't make sense to put this on the template so far..can someone help me, please? -
Django templates inheritance
For example: base.html <body> {% block content} {% endblock %} </body> base_index.html {% extends 'base.html' %} {% block content %} something {% endblock %} # add new block "for_child" to fill in with next inheritance <h1>Name: {% block for_child %} {% endblock %}</h1> base_index_child.html {% extends 'base_index.html' %} {% block for_child %} Peter {% endblock %} Result base_index_child.html: <body> something <h1>Name:</h1> </body> But i want (base.html -> base_index.html -> base_index_child.html) <body> something <h1>Name: Peter</h1> </body> How to get this? -
get ID from UUID field(in master) and then insert it to detail serializer
We have 2 table in database, which is Lookups(master) and LookupCodes(Detail). class Lookups(models.Model): lookup_uuid = models.UUIDField(db_index=True,default=uuid.uuid4, editable=False) class LookupCodes(models.Model): lookupcode_uuid = models.UUIDField(db_index=True, default=uuid.uuid4, editable=False) lookup_id = models.ForeignKey(Lookups,on_delete=models.DO_NOTHING, db_column='lookup_id',related_name='lookupcodes') We dont specify the primary key,so the primary key is id when we migrated that 2 table. Below is our serializable: class LookupCodeSerializer(serializers.ModelSerializer): class Meta: model = LookupCodes fields = ( 'lookupcode_uuid',lookup_id) class LookupSerializer(serializers.ModelSerializer): class Meta: model = Lookups fields = ('lookup_uuid') We are using uuid as lookup_field to perform retrieve,delete,update master and detail form,which is lookup and lookup code. How to perform insert on lookupcode(which is detail),when we already have uuid of lookup(which is master) and dont have the lookup_id? -
"OperationalError, unrecognized token" while searching
I'm getting this error while making any search query: OperationalError at /search/ unrecognized token: "@" My view: class Search(ListView): model = Opinion template_name = 'home/search.html' context_object_name = 'search_results' paginate_by = 10 def get_queryset(self): qs = Opinion.objects.all() keywords = self.request.GET.get('q') if keywords: query = SearchQuery(keywords) vector = SearchVector('text') qs = qs.annotate(search=vector).filter(search=query) qs = qs.annotate(rank=SearchRank(vector, query)).order_by('-rank') return qs My search form: <form class="navbar-form navbar-left" role="search" method="get" action="{% url 'home:search' %}"> <div class="form-group"> <input type="text" class="form-control" name="q" value=""> </div> <button type="submit" class="btn btn-default">Search</button> </form> Any suggestion or feedback will be welcomed and greatly appreciated. Thank you. -
dango-reversion create new version of model instance when related model instance is changed
After spending plenty a lot of time, looking for the proper solution I think I need a help from someone who had more experience with django-reversion. Please, consider the situation I faced with. For example, I have next models: class Board(models.Model): ...some_fields class Topic(models.Model): board = models.ForeignKey(Board, related_name='topics') ...some_fields class Post(models.Model): topic = models.ForeignKey(Topic, related_name='posts') ...some_fields The behavior I expect to get is to create a new version of the Board instance when related topics or posts are changed. I can achieve this by registering models in the next order: reversion.register(Board) reversion.register(Topic, follow=['board',]) reversion.register(Post, follow=['topic',]) But in such case createinitialrevisions command creates as many initial versions for the Board instances as there are Topic and Post objects related to the certain Board, I don`t need this. To be more clear, please take a look at django-shell output: >>> from boards.models import Board, Topic, Post >>> from reversion.models import Version >>> board = Board.objects.get(id=1) >>> board.topics.count() 52 >>> board.get_posts_count() 5004 >>> versions = Version.objects.get_for_object(board) >>> len(versions) 5057 Here is the django-admin with board`s history: Thanks for any help in advance! -
Does django cassandra engine allows to query on multiple keyspaces of same cluster
I have multiple keyspaces in cassandra database each having few tables. I have done cassandra connection from settings.py . But don't know how to change the keyspace name for some query in django orm. -
Apache + Django + WSGI : Page is not working
i don't understand why my apache server doesn't work. When i try to connect to the address http://bde.yggdrasil.cafe with opera i have the following message This page isn't working bde.yggdrasil.cafe is currently unable to handle this request. i i don't undrstand why. I enables mod_wsgi in /etc/httpd/conf/http.conf Here is the config file I import in my main config : $ cat /etc/httpd/conf/extra/bdeweb.conf <VirtualHost *:80> # This is name based virtual hosting. So place an appropriate server name # here. Example: django.devsrv.local ServerName bde.yggdrasil.cafe ServerAdmin thibaut.cens@epita.fr DocumentRoot /srv/http/bdeweb # This alias makes serving static files possible. # Please note, that this is geared to our settings/common.py # In production environment, you will propably adjust this! Alias /static/ /hdd/bdeweb/static # This alias makes serving media files possible. # Please note, that this is geared to our settings/common.py # In production environment, you will propably adjust this! Alias /media/ /srv/http/bdeweb/media # Insert the full path to the wsgi.py-file here WSGIScriptAlias / /srv/http/bdeweb/bdewebsite/wsgi.py # PROCESS_NAME specifies a distinct name of this process # see: https://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIDaemonProcess # PATH/TO/PROJECT_ROOT is the full path to your project's root directory, # containing your project files # PATH/TO/VIRTUALENV/ROOT: If you are using a virtualenv specify the full # path … -
Django - must be str, not int
I get an interesting exception. If I have my code like this: {% if page_nr != 0 %} <a href="{% url 'post:detail' topic.id page_nr|increase:-1 %}">Previous Page</a> {% endif %} {%page_not_over_amount page_nr amount_comments limit_amount_comment%} {% if comment_not_over_amount %} <a href="{% url 'post:detail' topic.id page_nr|increase:1 %}">Next Page</a> {% endif %} I will get an exception: Error during template rendering In template C:\Users\Nutzer\PycharmProjects\selfTry\post\templates\post\comment_block.html, error at line must be str, not int line 22 is <a href="{% url 'post:detail' topic.id page_nr|increase:-1 %}">Previous Page</a> However, if I remove my custom tag, make my code looks like : {% if page_nr != 0 %} <a href="{% url 'post:detail' topic.id page_nr|increase:-1 %}">Previous Page</a> {% endif %} {% if comment_not_over_amount %} <a href="{% url 'post:detail' topic.id page_nr|increase:1 %}">Next Page</a> {% endif %} the exception is gone! This is my custom tag: @register.inclusion_tag('post/comment_block.html') def page_not_over_amount(page_nr, comment_amount, comment_limit): result = page_nr * comment_limit < comment_amount - comment_limit return {'comment_not_over_amount': result} Here is all the traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/post/1/0/ Django Version: 1.11.3 Python Version: 3.6.2 Installed Applications: ['post.apps.PostConfig', 'music.apps.MusicConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\Nutzer\PycharmProjects\selfTry\post\templates\post\comment_block.html, error at line 22 must be str, not … -
Django-CMS admin tool Template
I have created html template named testTemplate which is added to CMS_TEMPLATES: CMS_TEMPLATES = ( ## Customize this ('fullwidth.html', 'Fullwidth'), ('sidebar_left.html', 'Sidebar Left'), ('sidebar_right.html', 'Sidebar Right'), ('testTemplate.html', 'testTemplate') ) Then in fullwidth.html file I have changed the {% extends "base.html" %} to {% extends "testTemplate.html" %}. In testTemplate.html file I can find few {% placehoders %}. And now if I want to go to django-cms to add a content to placeholders, my cms-admin does not look right. Layout of cms admin looks like the template elements. How to separate the cms-admin template and my site template to make it work correctly? -
Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name
I have a problem with django's view "password_reset_done". When I try to open accounts/reset-password I have this error. But if I open url accounts/reset-password/done it works. URLS.PY of "accounts" app from django.conf.urls import url from django.contrib.auth.views import login , logout, password_reset, password_reset_done from . import views urlpatterns = [ url(r'^register/$', views.register, name='register'), url(r'^profile/$', views.profile, name='profile'), url(r'^profile/prpage/(\d+)/$', views.profile, name='prpage'), url(r'^profile-edit/$', views.profiledit, name='profile-edit'), url(r'^login/$', login ,{'template_name':'accounts/login.html'}, name='login'), url(r'^logout/$', views.logout_view, name='logout'), url(r'^profile/(?P<proj_id>\d+)/$', views.userprojectpage, name='userprojectpage'), url(r'^changepassword/$', views.changepassword, name='changepassword'), url(r'^reset-password/$', password_reset, name='reset_password'), url(r'^reset-password/done/$', password_reset_done, name='password_reset_done'), ] please help! Thanks in advance) -
How to get django template from django_pandas dataframe?
How do you get django templates from a django_pandas dataframe? Documentation with django and pandas focuses on models. It does not trace the coding process from model to view to template. Using the example here: https://github.com/chrisdev/django-pandas#dataframemanager it is possible to translate a django model to a pandas dataframe. # models.py from django.db import models from django_pandas.managers import DataFrameManager class MyModel(models.Model): full_name=models.CharField(max_length=25) age = models.IntegerField() department = models.CharField(max_length=3) wage = models.FloatField() objects = DataFrameManager() def __str__(self): return self.full_name Subsequently, you can manipulate the dataframe, for example, reseting the index. Q1: How should you use views.py to get that dataframe to a template? you might transform it using df.to_html() as per below, or use df.to_json(), but I'm expecting because its Django that there is a best practice to place the df into a template. # views.py - here spits out html string, do I just resort to ElementTree? from django.shortcuts import render from django_pandas.io import read_frame from .models import MyModel def LookatMyModel(request): queryset = MyModel.objects.all() template_name = 'pandatest/page1.html' df = queryset.to_dataframe() #df = df.set_index('full_name') # effectively we can change the model. print (df.head()) df1 = df.to_html() context = { 'object_list': df1} print(df1) return render (request, template_name, context,) # templates/page1.html {% block content … -
Django autocomplete light: no input field
I've installed "Django autocomplete light" and now following this tutorial: http://django-autocomplete-light.readthedocs.io/en/master/tutorial.html Here is my code so far: setting.py INSTALLED_APPS = [ 'dal', 'dal_select2', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.gis', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'directory', 'geopy', ] models.py class Company(models.Model): CATEGORY_CHOICES = ( ('P', 'Parrucchiere'), ('Ce', 'Centro estetico'), ) self_key = models.ForeignKey('self', null=True, blank=True, related_name='related_self_key_models') city = models.ForeignKey(City, on_delete=models.CASCADE) name = models.CharField(max_length=200) address = models.CharField(max_length=255) telephone = models.CharField(max_length=200) category = models.CharField(max_length=1, choices=CATEGORY_CHOICES, null=True) email = models.CharField(max_length=255, null=True, blank=True) vat = models.CharField(max_length=200, null=True, blank=True) location = gis_models.PointField(u"longitude/latitude", geography=True, blank=True, null=True) gis = gis_models.GeoManager() objects = models.Manager() slug = AutoSlugField(populate_from='name', null=True) def __str__(self): return self.name views.py class CompanyAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Company.objects.none() qs = Company.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs forms.py class AddCompanyForm(forms.ModelForm): vat = forms.CharField(required=True) class Meta: model = Company fields = ('name','city','address','telephone','email','vat','self_key') widgets = { 'self_key': autocomplete.ModelSelect2(url='company-autocomplete') } def clean_vat(self): vat = self.cleaned_data['vat'] if Company.objects.filter(vat__iexact=vat).count() > 1: raise ValidationError("L'attività digitata esiste già...") return vat urls.py url( r'^company-autocomplete/$', autocomplete.Select2QuerySetView.as_view(model=Company), name='company-autocomplete' ), html {% extends 'base.html' %} {% load static %} {% block title %} <title>Aggiungi azienda | ebrand directory</title> {% endblock title %} {% block upper_content %} … -
Django migrate command fails (duplicate key value) after a Heroku deployment
The migration made no problem in local environment. I'm using a "release phase" in my Heroku deployment, with the migrate command. The error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "django_content_type_pkey" DETAIL: Key (id)=(1) already exists. Here is the full traceback from heroku release logs: Operations to perform: Apply all migrations: admin, animation, api_hooks, auth, authtoken, contenttypes, feedback, profiles, sessions Running migrations: Applying animation.0001_initial... OK Applying feedback.0003_customerexperiencefeedback_kind... OK Applying profiles.0002_teammember... OK Applying profiles.0003_customer_balance_alert_threshold... OK Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/contenttypes/models.py", line 54, in get_for_model ct = self.get(app_label=opts.app_label, model=opts.model_name) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name __fake__.DoesNotExist: ContentType matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 464, in get_or_create return self.get(**lookup), False File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name __fake__.DoesNotExist: ContentType matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: duplicate key value violates unique constraint "django_content_type_pkey" DETAIL: Key (id)=(1) already exists. The above exception was the direct cause of the following exception: Traceback (most recent … -
NOT NULL constraint failed: music_song.album_id
I am using django 1.11.6 and python 3.6.2 I'm new to django and there is no one to help me where i live so you guys are all my hope in my django application in the add song section i faced an error error message = IntegrityError at /music/album/5/AddSong/ NOT NULL constraint failed: music_song.album_id here is my views file: from django.views import generic from django.views.generic import View from .forms import UserForm from django.views.generic.edit import CreateView,UpdateView,DeleteView from django.shortcuts import render,redirect from django.contrib.auth import authenticate, login from .models import Album, Song from django.core.urlresolvers import reverse_lazy class IndexView(generic.ListView): template_name = 'music/index.html' context_object_name = 'all_albums' def get_queryset(self): return Album.objects.all() class DetailView(generic.DetailView): model = Album template_name = 'music/detail.html' context_object_name = 'album' class AlbumCreate(CreateView): model = Album fields = ['artist', 'album_title', 'genre', 'album_logo'] class SongCreate(CreateView): model = Song fields = ['song_title', 'file_type'] class AlbumUpdate(UpdateView): model = Album fields = ['artist', 'album_title', 'genre', 'album_logo'] class AlbumDelete(DeleteView): model = Album success_url = reverse_lazy('music:index') class UserFormView(View): form_class = UserForm template_name = 'music/registration_form.html' #display a blank form def get(self,request): form = self.form_class(None) return render(request,self.template_name, {"form": form}) #procces form data def post(self,request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) #cleaned (normalized) data username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() … -
Log out every logged in user in django
I have one situation in which if admin performs any particular action I need to log user out. I know one that is remove authentication token from the database. is there any other way to do it? thank you in advance. -
Django - Enter a list of values - ManytoManyField
I made the supplier field a select dropdown box since I want it to behave that way but it produces an error: Enter a list of values my model class Product(models.Model): name = models.Charfield(max_length=250) supplier = models.ManytoManyField(Supplier) my form: class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['name', 'supplier'] widgets = { 'supplier': forms.Select() } def clean_supplier(self): return [self.cleaned_data['supplier']]] It displays the error: Enter a list of values -
Django : Retrieve objects from relation
I am new in Django (1.11 used) and I read this (https://docs.djangoproject.com/fr/1.11/topics/db/models/) but I didn't find a clear answer for my question : How to retrieve the objets With an example , Suppose I have the following models : class StudentCollaborator(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) code_postal = models.IntegerField() collaborative_tool = models.BooleanField(default=False) def get_skills(self): return SkillHistory.objects.filter(student=self.user, value="acquired").values_list('skill') The skill history : class SkillHistory(models.Model): """ The reason why a Skill is acquired or not, or not yet, when and by who/how """ skill = models.ForeignKey(Skill) """The Skill to validate""" student = models.ForeignKey('users.Student') """The Student concerned by this Skill""" datetime = models.DateTimeField(auto_now_add=True) """The date the Skill status was created""" value = models.CharField(max_length=255, choices=( ('unknown', 'Inconnu'), ('acquired', 'Acquise'), ('not acquired', 'None Acquise'), )) """The Skill status : unknown, acquired or not acquired""" content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() reason_object = GenericForeignKey('content_type', 'object_id') reason = models.CharField(max_length=255) """Why the Skill is validated or not""" by_who = models.ForeignKey(User) class Meta: ordering = ['datetime'] and finally the skill class : class Skill(models.Model): """[FR] Compétence A Skill can be evaluated through questions answered by a student. Thus, when evaluated, a Skill can be acquired by a student, or not. """ code = models.CharField(max_length=20, unique=True, db_index=True) """The Skill reference code""" … -
django 'str' object has no attribute '_meta'
Sorry for my english. I have some data form enother server, but i need output this data like json. if i print response it contains in console { 'responseStatus': { 'status': [], }, 'modelYear': [ 1981, 1982 ] } but, if i return this response like HttpResponse i have error AttributeError: 'str' object has no attribute '_meta' this my code: data = serializers.serialize('json', response, ensure_ascii=False) return HttpResponse(data, content_type="application/json") -
How to modify slice of queryset persistently without save
I'm transforming (highlighting query matches) of a content attribute for objects in a search result queryset. When transforming the attribute during enumeration over every object in the queryset the transformation persists, at least for the life of the queryset. For obvious reasons I'm not applying a save, because I only want the transformation to persist for the life of the queryset during the request. The problem arises when I try to optimize the enumeration to a slice of the queryset, then the transformation no longer (temporarily) persists. Is there way to have transformations persist for a slice too? Why are my transformations treated differently for a slice than the full queryset? A slice of a queryset is still a queryset, although it does not have equivalence to the original queryset, even if its a slice of the entire queryset. Using Django 1.11.4 and Python 3.6.3