Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Avoid Django duplicated queries without select or prefetch related
I new to Django so I have some problem with my QuerySets. I am buliding an app wihich collect many type of data from many table. Unfortunately I had an exisiting table structure so I can't modify my databse structure. To optimize my queries and find the reason of my slow loading I decided to use Django Debug Toolbar. The result was terrible, I saw that I hit the database to many times, so I want to improve my queries. I made some improvements but my page loading is still low (~6 sec). I have some query which I think can be improved, so I attach them. 1, question Here I hit the database two time, but I don't no how could be hit it once. query_all=Table.objects .filter(time_stamp__range=(before_now,now),network_id='1') .order_by('-time_stamp') query_last=Table.objects .filter(time_stamp__range=(before_now,now),network_id='1') .order_by('-time_stamp')[:1] 2, question Here I have the same problem, to select only the network 1 or 2 I have to make a new query which hit the database again. Unfortunately I in the tables there are more thousand data, so a good optimize method could be useful for me. I have read the documentation, but I can't find solution (or I missed) for these question. network_1=Table.objects .filter(time_stamp__range=(before_now,now),network_id='1') .order_by('-time_stamp') network_2=Table.objects … -
Get reverse relationship for item in a list of dictionaries
I have a list (QuerySet of 'DailyEnrollment' objects) of dictionaries that looks like this: [ {'location_id': 1, 'student_count': 780}, {'location_id': 4, 'student_count': 535}, {'location_id': 6, 'student_count': 496} ] The location_id relates to a Location object which has an attribute name Is there a simple way to iterate across this list, get each dictionaries location.name for the location_id and append it to the dictionary as location_name? I was considering a dictionary comprehension inside of a list comprehension - but I wasn't sure how Pythonic that was. Models: class Location(models.Model): name = models.CharField(max_length=50) short_name = models.CharField(max_length=50) The DailyEnrollment is data nabbed from a view built with external data class DailyEnrollment(SchoolModel): id = models.IntegerField(db_column='ID', primary_key=True) location_id = models.IntegerField(db_column='schoolID') grade = models.CharField(db_column='grade', max_length=10) end_year = models.IntegerField(db_column='endYear') run_date = models.DateField(db_column='runDate') student_count = models.IntegerField(db_column='studentCount') In the view this is how I get my Daily Enrollments # get past enrollments past_daily_enrollments = DailyEnrollment.objects.filter( run_date=datetime.strptime(since_date, '%m-%d-%Y'), location_id__lte='31', end_year='2018') I create a 'new list' of data with everything grouped on location_id, with the total student_count location_data = past_daily_enrollments.values('location_id').annotate( student_count=Sum('student_count') ) That's how I get to the issue I asked about. I have 'location_data', which is my list of dictionaries. -
Where store the Variables in Django?
my boss purchase a website make in Django, and i can see some variables using for the website. For example, the head site is a Variable, i want to insert a Google Analytics Code and other codes for the header, but i dont want to insert the code to each page, i want to insert the code in the Variable but i cant find it. I search the solution in Django website and Google, but the answers are not clear. Django where store the variables or how can i search it? Thanks. -
Registering Entry with the Admin Site with Django python "Safari
I've already activated virtual environment with source ll_env/bin/activate. I've already created the database with python manage.py migrate I've kept the server running with learning_log james$ python manage.py runserver I've already activated models in setting.py that is found in learning_log/learning_logs directory like this INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # My apps 'learning_logs', ] And now I've opened another terminal window and activated another virtual environment with source ll_env/bin/activate I've already set up a superuser with the command `python manage.py createsuperuser, I've already defined the entry model I've also set all the files that are needed in models.py in learning_log/learning_logs from django.db import models class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text class Entry(models.Model): """Something specific learned about a topic""" topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Return a string representation of the model.""" return self.text[:50] + "..." I've already migrated the entry model with python manage.py makemigrations learning_logs and python manage.py migrate but when I tried these command AGAIN it just now shows No changes detected in app 'learning_logs' … -
Django social auth with pipeline, email repeated
First, sorry for the bad english I am using django's social auth with pipelines to get the email from social networks, but when I login with facebook and then with google I am created two different accounts with the same email screenshot from admin site how can I avoid this by sending a message to the user, saying that there is already an account created with that mai, or directly logging in with the other account This is my code from Social auth pipelines in settings.py SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'users.utils.create_profile', #<-- Crear UserProfile 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'users.utils.get_avatar' ) -
Pass JavaScript variable into Django filter()
I have a Django filter in my views.py file: context['data_objects'] = Data.objects.filter(field=startDate) The variable "startDate" exists in a JavaScript file. Is it possible to pass a JavaScript file into the backend of my Django application. If not, are there any other ways to get data from my database based of a JavaScript variable? -
Getting unicode character 'u' in between 'key' text in Python dictionary
I am populating various metrics by executing data base views in a django view. However, I am getting the Unicode character in the key text for some in the final dictionary. I tried few things by going through internet, but not exactly clear on how to solve it. Appreciate help in this regard. ========Sample Code for a key that populates value for that key========= try: sqlQueryString = 'select * from primeApp_UniqueConsultationPatientFootFallDaily' cursor = connection.cursor() cursor.execute(sqlQueryString) statsInfo = dictfetchall(cursor) businessStats['DailyNewPatientsFootFall'] = statsInfo[0]['DailyNewPatientsFootFall'] except Exception as e: errorFlag = 1 error_record['JSONString'] = sqlQueryString error_record['ErrorMessage'] = 'getBusinessStats - Error in prepared SQL Statement or Selecting the Data:'+str(e) raw_ErrorRecord = rawErrorRecord(**error_record) raw_ErrorRecord.save() return false ================================================= Resulting Dict If you observe, some of the keys are embedded with 'u' in between their text. Such examples are "DailyNewP', u'atientsFootFall":"0" , 'AverageConv", u"ersionTime': 65 etc. Please suggest me where I am making a mistake and how to correct it. Thanks in advance. -
Django annotations using F() expressions with DateTimeFields
I want to write a custom QuerySet and Manager for a model that has a DateTimeField("installed_date" field) and an IntegerField ("expiration_days"), and I want to filter objects based on the rule " 'installed_date' plus 'expiration_days' is prior to current day" so to get objects that are currently due. For example: import datetime as dt from django.db import models from django.db.models import F, Func, ExpressionWrapper, DateField, IntegerField, FloatField from django.utils import timezone class MyQuerySet(models.QuerySet): def obsolete(self): current_date = timezone.localtime(timezone.now()) obsolete_qs = self.annotate( days_since_installed_date = ExpressionWrapper( F('installed_date')-current_date, output_field='IntegerField' ) ).filter( days_since_installed_date__lt=F('expiration_days') ) return obsolete_qs class MyManager(models.Manager): def get_queryset(self): return MyQuerySet(self.model, using=self._db) def obsolete(self): return self.get_queryset().obsolete() class MyModel(models.Model): description = models.CharField(max_length=100) installed_date = models.DateTimeField(default=timezone.now) expiration_days = models.PositiveIntegerField() obsolete = MyManager() @property days_since_installed_date = installed_date - timezone.now() When trying as before i get the error "'str' object has no attribute 'get_lookup'" Also tried this: class MyQuerySet(models.QuerySet): def obsolete(self): current_date = timezone.localtime(timezone.now()) obsolete_qs = self.annotate( days_since_installed_date = F('installed_date')-current_date ).filter( expiration_days__gt=days_since_installed_date ) return obsolete_qs Here I get "name 'days_since_installed_date' is not defined". If I encapsulate 'days_since_installed_date' in an F() expression inside the filter portion of the previous code i get "operator does not exist: integer > interval". And I've been trying a few more recipes based … -
django migration convert polygon to multipolygon [duplicate]
This question is an exact duplicate of: django change data type in migration I had a table with a column with Polygon type, I changed the type to MultiPolygon. Now I want to change the data which is in Polygon type to MultiPolygon. Is there any stored procedures or any other ways to do that? tnx -
How to return html or json from ViewSets depending on client django rest framework
I've created an APIs endpoints for mobile developers with all of the logic there. Now I need to create a web version of this app. Is it possible to not write the views specifically for this, but use already existing one in APIs? In API I am using Django Rest Framework ViewSets. Assume that this is my models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=20) description = models.CharField(max_length=100, blank=True, null=True) Then this is going to be my serializers.py: from rest_framework import serializers from .models import Post class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('id', 'title', 'description') read_only_fields = ('id',) viewsets.py: from rest_framework import viewsets from .serializers import PostSerializer from .models import Post class PostViewSet(viewsets.ModelViewSet): model = Post queryset = Post.objects.all() serializer_class = PostSerializer urls.py from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'posts', viewsets.Post, base_name='post') urlpatterns = router.urls I've seen this HTML & Forms in docs, but if I put renderer_classes and template_name it just renders html with the parameters that I want, but I want to have a separate endpoints for just returning json for mobile developers and rendering a user-friendly html for web version. Is it possible to do this and if it is, how … -
About django connecting MSSQL 2012 FileStream
I use MSSQL2012 「FileStream」to save images, and then connecting to django’s models.py . I set the FileStream first; and used “manage.pyinspectdb”. As below: http://arpheno.github.io/django/mssql/inspectdb/2015/11/15/Django-and-MSSQL.html Finally registered the table to admin.py, but i check to 127.0.0.1:8000/admin is Error DjangoUnicodeDecodeError How to fit it? # models.py class Filetable(models.Model): stream_id = models.CharField(unique=True, max_length=36) file_stream = models.BinaryField(blank=True, null=True) name = models.CharField(max_length=255) path_locator = models.BinaryField(primary_key=True) parent_path_locator = models.ForeignKey('self', models.DO_NOTHING, db_column='parent_path_locator', blank=True, null=True) file_type = models.CharField(max_length=255, blank=True, null=True) cached_file_size = models.BigIntegerField(blank=True, null=True) creation_time = models.CharField(max_length=34) last_write_time = models.CharField(max_length=34) last_access_time = models.CharField(max_length=34, blank=True, null=True) is_directory = models.BooleanField() is_offline = models.BooleanField() is_hidden = models.BooleanField() is_readonly = models.BooleanField() is_archive = models.BooleanField() is_system = models.BooleanField() is_temporary = models.BooleanField() class Meta: managed = False db_table = 'FileTable' unique_together = (('parent_path_locator', 'name'),) class DjangoMigrations(models.Model): app = models.CharField(max_length=255) name = models.CharField(max_length=255) applied = models.DateTimeField() class Meta: managed = False db_table = 'django_migrations' Filetable SQL info Filetable SQL info -
Django DRF: Make serializer field value equal to another one
I am creating an endpoint to reset the password and have created the serializer, views and I am using django.contrib.auth.forms to get the data and send email to the user. The form requires to type the new password two times but what I want is, to write it only once and make the value of new_password2 equal to new_password1. For example, I want to change the password on Swagger and it doesn't make sense to type it twice because it is a normal CharField and not a PasswordField. This is the serializers.py ResetPasswordConfirm class class ResetPasswordConfirmSerializer(serializers.Serializer): new_password1 = serializers.CharField(max_length=128) new_password2 = serializers.CharField(max_length=128) uid = serializers.CharField() token = serializers.CharField() set_password_form_class = SetPasswordForm def __init__(self, *args, **kwargs): super(ResetPasswordConfirmSerializer, self).__init__(*args, **kwargs) self.set_password_form = None def validate(self, value, *args, **kwargs): try: uid = force_text(uid_decoder(value['uid'])) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): raise ValidationError({ 'uid': ['Invalid value'] }) self.set_password_form = self.set_password_form_class(user=user, data=value) if not self.set_password_form.is_valid(): raise serializers.ValidationError(self.set_password_form.errors) if not default_token_generator.check_token(user, value['token']): raise ValidationError({ 'token': ['Invalid value'] }) return value def save(self, **kwargs): return self.set_password_form.save() And, the API View class ResetPasswordConfirmAPIView(GenericAPIView): serializer_class = ResetPasswordConfirmSerializer permission_classes = (AllowAny,) @method_decorator(csrf_protect) def dispatch(self, *args, **kwargs): return super(ResetPasswordConfirmAPIView, self).dispatch(*args, **kwargs) def post(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return … -
Create a django form, but instead of giving a file, give a folder/directory
I want to write a django form to upload a set of files to the database. However I don't want to do this with separate files - I want to have 'search button' and give the folder path, taking info from each file to upload to different models. Is there a way to handle this with an inbuilt django form (like using file = forms.FileField()) -
Python list: list index out of range
I am not so much familiar with python and got this code from a friend of mine and need some community help here to solve this issue.I'm getting "list index out of range" error from the following line. days = list(zip(Leave_type.objects.filter(type=leavetype).values_list('max_days', flat=True))[0]) Note: I have already execute migrations and setup my database already. def timeoffapply(request): if not request.session.get('id', None): return render(request, 'login.html') else: stdate = request.POST['startDate'] enddate = request.POST['endDate'] leavetype = request.POST['leaveType'] days = list(zip(Leave_type.objects.filter(type=leavetype).values_list('max_days', flat=True))[0]) d1 = datetime.strptime(stdate, "%Y-%m-%d") d2 = datetime.strptime(enddate, "%Y-%m-%d") d3 = abs((d2 - d1).days)+1 empid = (request.session['id'])[0] countdays = Leave.objects.filter(Emp_id = empid,type=leavetype).aggregate(Sum('days')) if countdays['days__sum'] == None: finaday = (days[0] - 0) else: finaday=(days[0] - countdays['days__sum']) if enddate>=stdate: if finaday >= d3: getleaveid = list(zip(Leave_type.objects.filter(type=leavetype).values_list('id', flat=True))[0]) split_lt_id = ("".join(str(e) for e in getleaveid)) empid = (request.session['id'])[0] get_emp_name = list(zip(Employee.objects.filter(id=empid).values_list('name', flat=True))[0]) get_emp_name = ("".join(str(e) for e in get_emp_name)) empid = (request.session['id'])[0] leave_id = Leave.objects.all().count() test = Leave(id=(leave_id + 1), name=get_emp_name, type=leavetype, start_date=stdate, end_date=enddate, days=d3, status="pending") test.Emp_id_id = empid test.leave_type_id_id = split_lt_id test.save() return HttpResponseRedirect('/') else: qs = Leave.objects.all().filter(Emp_id=(request.session['id'])[0]) context = { "qs": qs, "error": "true", "msg": "You are allowed to have holidays for " + str(finaday) + " days in " +str(leavetype) } return render(request, 'timeoff.html', context) -
python Django admin module occurs 404 error
I'm learning Django recently, I'm writing code according to official documentation.However, when I try to use the admin module, the bug occurs.Here is my project structure: structure and code in django_demo/urls.py: from django.urls import include, path from django.contrib import admin urlpatterns = [ path('poll/', include('poll.urls')), path('admin/', admin.site.urls), ] poll/urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>', views.detail, name="detail"), path('<int:question_id>/results/', views.results, name="results"), path('<int:question_id>/vote/', views.vote, name="vote"), ] settings.py: INSTALLED_APPS = [ 'poll.apps.PollConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] -
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration ... is applied before its dependency
I get this exception: myproject@aptguettler:~$ manage.py migrate Traceback (most recent call last): File "/home/myproject/src/djangotools/djangotools/bin/manage.py", line 32, in <module> main() File "/home/myproject/src/djangotools/djangotools/bin/manage.py", line 29, in main execute_from_command_line() File "/home/myproject/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/myproject/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/myproject/local/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/myproject/local/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/home/myproject/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 86, in handle executor.loader.check_consistent_history(connection) File "/home/myproject/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 292, in check_consistent_history connection.alias, django.db.migrations.exceptions.InconsistentMigrationHistory: Migration myapp.0029_bar is applied before its dependency myapp.0005_foo_squashed_0028_dynamic_year on database 'default'. My migrations: name ------------------------------------------- 0001_initial 0002_... 0003_... 0004_... 0005_foo 0006_... 0007_... ... 0028_dynamic_year 0029_bar 0030_... What could be the reason? -
django rest cant get session varible in get request
i have the following class for user's peyment progress when the request is POST , im setting amount in session like this request.session['amount'] = amount and when the request is GET i should get the session but session is empety and the if statment if 'amount' in request.session: is alwasy false ... how can i fix this?? class PaidApiView(APIView): MMERCHANT_ID = '??????????' # Required ZARINPAL_WEBSERVICE = 'https://www.zarinpal.com/pg/services/WebGate/wsdl' # Required amount = None # Required description = None # Required products = None email = 'user@userurl.ir' # Optional mobile = '09123456789' # Optional CallbackURL = 'http://127.0.0.1:8000/store/paid/' def post(self, request, *args, **kwargs): amount = request.data['amount'] products = request.data['products'] productstitle = request.data['productstitle'] productsTitlestr = ''.join(productstitle) self.amount = amount self.products = products self.description = productsTitlestr request.session['amount'] = amount client = Client(self.ZARINPAL_WEBSERVICE) result = client.service.PaymentRequest(self.MMERCHANT_ID, self.amount, self.description, self.email, self.mobile, self.CallbackURL) if result.Status == 100: return Response('https://www.zarinpal.com/pg/StartPay/' + result.Authority) else: return Response('Error') def get(self, request): if 'amount' in request.session: self.amount = request.session['amount'] client = Client(self.ZARINPAL_WEBSERVICE) if request.GET.get('Status') == 'OK': result = client.service.PaymentVerification(self.MMERCHANT_ID, request.GET['Authority'], self.amount) if result.Status == 100: del request.session['amount'] return Response('Transaction success. RefID: ' + str(result.RefID)) elif result.Status == 101: del request.session['amount'] return Response('Transaction submitted : ' + str(result.Status)) else: del request.session['amount'] return Response('Transaction failed. … -
How do I use a datetime object in a Django template filter?
I have a specific set of date formats that I want to set based on language and am hoping to do this with a Django template filter. This is what I currently have: @register.filter def date_with_lang(date_item, language): supported_languages={ 'en': '%M. %d, %Y', 'fi': '%M. %d, %Y'} if language in supported_languages: format_type = supported_languages[ĺanguage] else: #default to english if we can't find it. format_type = supported_languages['en'] return datetime.strftime(format_type) But with this design I get a string for the datatype. Do I need to translate the string version of the date to a datetime first? Sound silly. Perhaps another solution would be to put a method for the printout in the model. What's your take? How is this best done? -
How many connections a Python Django App opens by default?
I have a couple of services which query objects from the database. Event.objects.filter Connection.objects.filter and other methods to retrieve different objects from MySQL database. I come from JVM background, and I know that to setup a JDBC connection, you need a connector. A programmer can open a connection, query the database and close the connection. A programmer also can use Hibernate, which handles connection according to the configuration. Also it is possible to use pooled connections, so connections are not closed and removed, but stored in the pool untill they are needed. However, I checked my teams Python Django code, and I did not find how db connection is configured. The only thing I got is which does not configure connections. # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases try: import database_password DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': "mydb", 'USER': 'user', 'PASSWORD': database_password.password, 'HOST': '10.138.67.149', 'PORT': '3306' } } -
(Python Django MySQL) Lost connection to MySQL server during query
I run a Python Djanogo application that once in a day makes a request to the database. while True: today = datetime.date.today() for _ in range(3): print("checking...") # Access objects in the database. events = Event.objects.filter(deadline__gt=last, deadline__lt=today, processed=False) #Sleep once day. sleep(24*60*60) And I get an error I attached the log file from the python app, and I also attached a file from MySQL log. Python app log 0 events resolved. checking... 0 events resolved. checking... Traceback (most recent call last): File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 65, in execute return self.cursor.execute(sql, params) File "C:\Python36\lib\site-packages\django\db\backends\mysql\base.py", line 101, in execute return self.cursor.execute(query, args) File "C:\Python36\lib\site-packages\MySQLdb\cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "C:\Python36\lib\site-packages\MySQLdb\connections.py", line 50, in defaulterrorhandler raise errorvalue File "C:\Python36\lib\site-packages\MySQLdb\cursors.py", line 247, in execute res = self._query(query) File "C:\Python36\lib\site-packages\MySQLdb\cursors.py", line 411, in _query rowcount = self._do_query(q) File "C:\Python36\lib\site-packages\MySQLdb\cursors.py", line 374, in _do_query db.query(q) File "C:\Python36\lib\site-packages\MySQLdb\connections.py", line 277, in query _mysql.connection.query(self, query) _mysql_exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Python36\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Python36\lib\site-packages\django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python36\lib\site-packages\django\core\management\base.py", line 283, in … -
How to use the rest_framework_tracking.mixins.LoggingMixin in drf-tracking in django
How to use the rest_framework_tracking.mixins.LoggingMixin as stated by Add the rest_framework_tracking.mixins.LoggingMixin to any DRF view to create an instance of APIRequestLog every time the view is called. I have added the class in the views as stated by http://drf-tracking.readthedocs.io/en/latest/#usage. Please let me know on the same. -
django change data type in migration
I had a table with a column typed Polygon, which had dozens of fields. Now I changed the column type to MultiPolygon, but data is still in `polygon' mode. How can I convert all data to new type? There might be a problem that data be so big and we do not want to have them in RAM. tnx -
ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': No module named urls
[INFO] oauth2client.client: Refreshing access_token [ERROR] django.request: Internal Server Error: / get_package_libraries "trying to load '%s': %s" % (entry[1], e) InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': No module named urls This is a python 2.7 project. Django version 1.9 -
Django Forms ModelChoiceField with bootstrap-select
I'm trying to use https://django-bootstrap-select.readthedocs.io with my Django forms and use the 'data-live-search' attribute with my field. So far (to no avail) I have: forms.py: class Someform(forms.ModelForm): f1 = forms.DateField(initial=datetime.date.today, widget=forms.SelectDateWidget()) f2 = forms.ModelChoiceField(Model1.objects.filter(some_filter=0), widget=BootstrapSelect(attrs={'data-live-search':'True'})) class Meta: model = Model2 fields = ('f1', 'f2',) form.html <div class="jumbotron"> <h2>Select from model1</h2> <p></p><form method="post" enctype="multipart/form-data">{% csrf_token %} {{ form.as_p }} <button class="btn btn-primary" type="submit">Submit</button></form> </div> views.py: class FormView(generic.FormView): form_class = forms.SomeForm template_name = 'form.html' -
Many to Many relationships in DJANGO with or without a relation table
I'm new to Django. usually, when having a many to many relationships I would create a separate table to hold the relationship can somebody explain how to do that in Django here is my attempt: a 'Etudiant' can 'Etudier' many 'Modules' a 'Modules' can be 'Etudier' by many 'Etudiant' class Etudiant(models.Model): id_etudiant = models.OneToOneField('Utilisateur', models.DO_NOTHING, db_column='id_Utilisateur', primary_key=True) id_groupe = models.ForeignKey('Groupe', models.DO_NOTHING, db_column='id_Groupe') class Meta: db_table = 'Etudiant' class Module(models.Model): id_module = models.CharField(db_column='id_Module', primary_key=True, max_length=25) titre_module = models.CharField(db_column='titre_Module', max_length=25, blank=True, null=True) uniteenseignement_module = models.CharField(db_column='uniteEnseignement_Module', max_length=25, blank=True, null=True) finsaisie_module = models.IntegerField(db_column='FinSaisie_Module', blank=True, null=True) class Meta: db_table = 'Module' class Etudier(models.Model): id_etudiant = models.ForeignKey('Etudiant', models.DO_NOTHING, db_column='id_etudiant') id_module = models.OneToOneField('Module', models.DO_NOTHING, db_column='id_Module', primary_key=True) class Meta: db_table = 'etudier' unique_together = (('id_module', 'id_etudiant'),)