Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I render my django login form with bootstrap?
I am struggling to understand how handling forms manually works... It's a bit of a headache because there are no relevant examples, or they are outdated. I just have the basic login form with username and password. I would like to display the errors under each field if possible. Thank you. <form method="post"> {% csrf_token %} {{ form.username }}<br> {{ form.password }}<br> {% if form.errors %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} <button type="submit" class="btn btn-primary">Submit</button> </form> Right now, the above snippet display errors in such way that my whole form gets moved to the left inside the html page. -
Django docs -- CBVs: Why not just define a get() method that takes an argument from a URL?
Noob here going through the Django docs, trying to get a grip on how it all fits together. In this section of their document on generic class-based views, they demonstrate the hard-coding of filter parameters for a particular publisher (in this example) into ListView's queryset attribute and suggest that doing so will become problematic once you need separate ListViews for every publisher. That makes sense to me. In the next section they suggest overriding ListView's get_queryset() method this way: class PublisherBookList(ListView): template_name = 'books/books_by_publisher.html' def get_queryset(self): self.publisher = get_object_or_404(Publisher, name=self.kwargs['publisher']) return Book.objects.filter(publisher=self.publisher) My question is, why not just declare a get() method in ListView and allow get() to take in publisher from the URL? What am I missing here? -
class based view passing parameters
I have just started using Class-based views and I am trying to pass the parameters to class-based view as: return HttpResponseRedirect(reverse('myView'), kwargs={'method': 'learning'}) My view is: class MyView(View): form_class = MyForm initial = {'key': 'value'} template_name = 'algoRunning.html' def dispatch(self, request, *args, **kwargs): print (kwargs['method']) data = self.readFile('myFile.txt') context = {'result': data} return render(request, self.template_name, context) def readFile(self, filePath): # read data return data my url pattern looks like: urlpatterns = [... url(r'^learning/(?P<method>[a-z]+)/$', my_views.MyView.as_view(), name='myView'), ..] But, it gives me following error Reverse for 'myView' with no arguments not found. 1 pattern(s) tried: ['learning/(?P<method>[a-z]+)/$'] What am I doing wrong?? -
AssertionError: `base_name` argument not specified
i'm trying to add a parameter of a model to a URL pattern, as such: http://111.111.11.111:8080/resultados/image.jpg where nome_ficheiro = image.jpg (nome_ficheiro is a model parameter, see below) But i'm getting the following error: File "/usr/local/lib/python2.7/dist-packages/rest_framework/routers.py", line 139, in get_default_base_name assert queryset is not None, '`base_name` argument not specified, and could ' \ AssertionError: `base_name` argument not specified, and could not automatically determine the name from the viewset, as it does not have a `.queryset` attribute. The URL pattern: router = routers.DefaultRouter() urlpatterns = [url(r'^', include(router.urls))] router.register(r'resultados/(?P<nome_ficheiro>.+)/$',resultUploadView.as_view({'get': 'get_queryset'})) The view: class resultUploadView(generics.ListAPIView): serializer_class = resultSerializer queryset = labelResult.objects.all() def get_queryset(self): nome = self.kwargs['nome_ficheiro'] return labelResult.objects.filter(nome_ficheiro=user) The model: class labelResult(models.Model): nome_ficheiro = models.CharField(max_length=120) especie = models.CharField(max_length=120) zona = models.CharField(max_length=120) data = models.CharField(max_length=120) USING: Python 2.7.12 and DRF 3.6.3 -
Django ChoiceField generated from a function
I want a generic list of choices in my form. In the devices.py def get_devices(): api_url = api_url_base response = requests.get(api_url,headers=headers) if response.status_code == 200: return json.loads(response.content.decode('utf-8')) else: return None ####################################### devices_infos = get_devices() if devices_infos is not None: print('Voici les devices: ') for each in devices_infos['data']: device_name = (each['name']) for k in range(len(devices_infos['data'])): mes_choix = ("(%s, ('%s'))," % (k,device_name )) else: print("[!] Request failed") It returns me my 2 devices like that (0, ('Erics phone')), (1, ('mySensor001')), In forms.py from django import forms from alertes.devices import * class NameForm(forms.Form): nom_alerte = forms.CharField(label='Nom Alerte', max_length=100) devices = forms.ChoiceField(label='Liste devices', choices=mes_choix, required=False) user_mail = forms.EmailField(label = 'Email a envoyer', max_length=100) Here, i would have in the devices label, a list of choice like Erics phone mySensor001 But i got the need more than 1 value to unpack error -
Parent Keys in Django Template URL lookup
In Django, I am trying to make an app with a tree hierarchy of models, i.e: My Models in models.py: class Book(models.Model): name = models.CharField("Book Name", max_length = 80) class Chapter(models.Model): name = models.CharField("Book Name", max_length = 80) book = models.ForeignKey('Book', on_delete = models.CASCADE) My URL patterns in urls.py: urlpatterns = [ path('books/', views.BookListView.as_view(), name='book_list'), path('books/<int:book>/', views.BookDetailView.as_view(), name='book_detail'), path('books/<int:book>/chapters/', views.ChapterListView.as_view(), name='chapter_list'), path('books/<int:book>/chapters/<int:chapter>/', views.ChapterDetailView.as_view(), name='chapter_detail'), path('books/<int:book>/chapters/create/', views.ChapterCreateView.as_view(), name='chapter_create'), My Views in views.py: class BookListView(generic.ListView): model = 'Book' class BookDetailView(generic.DetailView): model = 'Book' pw_url_kwarg = 'book' class ChapterListView(generic.ListView): model = 'Chapter' def get_queryset(self): return Chapter.objects.filter(book = self.kwargs['book']) class ChapterDetailView(generic.DetailView): model = 'Chapter' pw_url_kwarg = 'chapter' class ChapterCreateView(generic.CreateView): model = 'Chapter' fields = ['name', 'book'] def get_initial(self): initial = super().get_initial().copy() initial['book'] = self.kwargs.['book'] return initial; In my HTML-Template used for the list of chapters, I want to have a link to create a new chapter. Currently, that template looks as follows: Template chapter_list.html: <ul> {% for chapter in chapter_list %} <li>{{ chapter.name }}</li> {% endfor %} </ul> <a href="{% url 'chapter_create' 42 %}">Add new chapter</a> Obviously, I don't want to add all new chapters to the book with ID 42, rather I would like to use the book ID from the chapter list, … -
Heroku run migrate gives server error
I pushed my application to Heroku, assign the dyno, and create the database. Now if I run: heroku run python manage.py migrate I receive the error: 'Is the server running on host 'localhost' and accepting TCP/IP connections on port 5432? but I don't want to run on my server but one the Heroku server -
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?