Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Upload file to s3 from vuejs and Django backend
I would like to generate a signed URL in Django, send it to frontend using Axios Ajax and then using that url upload a file directly from Vue JS to S3 Thanks -
What order are urls checked, if the first match is used but the same url with /<int:pk> appears right after how is it parsing it?
From the Django Project docs: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL. ...the patterns are tested in order, and the first one is the first test to pass. Feel free to exploit the ordering to insert special cases like this. If that is the case, then why doesn't the url 'blog/page4' match for the first path 'blog/'? Does the url parser continue down the list to see if there is anything else that matches and then go back to the top if it doesn't? urlpatterns = [ path('blog/', views.page), path('blog/page<int:num>/', views.page), ] # View (in blog/views.py) def page(request, num=1): # Output the appropriate page of blog entries, according to num. I can see that it works, I'm not understanding the explanation in the Docs. I've googled around for answers and all I get is the same documentation on the djangoproject website. -
How to get input data from django request.POST
I want to get the input data from my frontend so I can create an object from my backend. This is my input request: return axios.post('http://127.0.0.1:8000/api/products/',{ name: name, description: description, category: this.category }, this.config ) .then(res=>this.props.update(res.data)) .catch(err=>console.err(err)); where name, description, and category are my input args, and this.config is just the the token. In my backend I am using a Viewset to handle all my requests. So far I have a one for GET but now I want one for POST. This is my code: class ProductViewSet(viewsets.ModelViewSet): def list(self, request): user = request.user queryset = Product.objects.filter(user=user) serializer = ProductSerializer(queryset, many=True) return Response(serializer.data) def create(self, request): data = request.POST["name"] print("name",name) return Response("test") I tried all variations of trying to extract my info from request.POST I tried request.POST.get('name'), request.POST['name'], and other stuff. They all return None/KeyError. What am I doing wrong? -
socket.gethostbyaddr() on a linux system and local network
I have a django application using this function, i'm trying to get the computer name of the ip address accessing my application. I'm doing this by using django-ipware to get the client's ip address, this part is working fine. Then i'm using socket.gethostbyaddr() to get the client's computer name, this works fine on my windows development machine. def get_comp_name(request): client_ip = get_client_ip(request) try: comp_name = socket.gethostbyaddr(client_ip[0])[0] except socket.herror: comp_name = '' When i tried to deploy to a centOS 7 machine, I get the following error when executing socket.gethostbyaddr() on local network ip addresses. socket.herror: [Errno 1] Unknown host I can ping local ip addresses without issue. Am I missing a configuration on my centOS 7 machine? -
RuntimeError: Model class oe_master.models.AcademicSession doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I get this error when i try to test the code, but runserver command is still working RuntimeError: Model class oe_master.models.AcademicSession doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. from django.db import models from core.student.models import Student from academic.models import Course import itertools class AcademicSession(models.Model): name = models.CharField(max_length=255) is_active = models.BooleanField(default=False) def __str__(self): return self.name class OESelect(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) course = models.ForeignKey(Course,on_delete=models.CASCADE) choice_level = models.IntegerField() academic_session = models.ForeignKey(AcademicSession, on_delete=models.CASCADE) date_time = models.DateTimeField(auto_now=True) def __str__(self): return str(self.student.name) class OEAllotmentManager(models.Manager): def OEAllot(self): #allot oe courses to students ifaccording to their past performance and the academic choice level courses = Course.objects.all() #iterate through each courses for course allotment for course in courses: if course.semester == 1: #get oe_selects of a course oe_selects=course.oeselect_set.all().order_by( '-student__sgpa_1st_semester', '-student__attendance_1st_semester ', 'date_time') for oe_select in oe_selects: OEAllotment.objects.create( student= oe_select.student, course= oe_select.course, academic_session= oe_select.academic_session ) #else: for second semester class OEAllotment(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) course = models.ForeignKey(Course,on_delete=models.CASCADE) academic_session = models.ForeignKey(AcademicSession, on_delete=models.CASCADE) objects = OEAllotmentManager() def __str__(self): return str(self.student.name) -
how can I return the sum (amount) sum(total_price) for each distinct currency that the user has made a transaction with
I'm trying to return a query set in django that returns the total amount purchased SUM(amount), total price paid SUM(total_price) for each distinct currency that the user has made transactions with. Is this possiible? advice would be very much appreciated Transaction model below class Transaction(models.Model): currency = models.CharField(max_length=20) amount = models.IntegerField() total_price = models.DecimalField(max_digits=8, decimal_places=2) date_purchased = models.DateTimeField() note = models.TextField(default="") owner = models.ForeignKey(User, on_delete=models.CASCADE) Function below @login_required def portfolio(request): sum_amount = Sum('amount') sum_total_price = Sum('total_price') context = { 'transactions': Transaction.objects.filter(owner=request.user).annotate( current_amount=sum_amount, purchased_amount=sum_total_price ) } return render(request, 'webapp/portfolio.html', context, {'title': 'Portfolio'}) HTML below {% for transaction in transactions %} <tr> <td>{{transaction.current_amount}}</td> <td>{{transaction.purchased_amount}}</td> </tr> {% endfor %} SaleForm Below class SaleForm(forms.ModelForm): amount_sold = forms.IntegerField() total_price_sold = forms.DecimalField() date_sold = forms.DateField( widget=forms.TextInput( attrs={'type': 'date'} ) ) note = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Keep a Note?'})) class Meta: model = Sale fields = ('date_sold', 'amount_sold', 'total_price_sold', 'note') labels = { 'date_sold': _('Sale Date'), } help_texts = { 'date_sold': 'Use Calendar to enter date', } -
How to set path in app's urls.py to show localhost:8000/xxx(with django2.1.8)
I want to show topics.html through visiting localhost:8000/topics start a project named learning_log start an app namede learning_logs this is url.py in learning_logs(app) from django.urls import path from . import views urlpatterns=[ path('',views.index,name='index'), path('/topics/',views.topics,name='topics') ] and this is url.py in learning_log(project) from django.contrib import admin from django.urls import path,include,re_path urlpatterns = [ path('admin/', admin.site.urls), path('',include('learning_logs.urls')) ] this is views.py in learning_logs(app) def topics(request): topics=Topic.objects.order_by('date_added') context={'topics':topics} return render(request,'learning_logs/topics.html',context) I runserver and visit localhost:8000/topics it says 404Error,current path didn't match -
How to do Django unit testing - to reuse data from 1 DB via 1 class
As you can see in the setUpClass we define user and profile. When you look at the method: test_create_project All is working fine and the test passes. Idea is since the Project and Position was created via that method, I would like to use it from DB in the method: test_homepage Problem is when you try to read them from DB they do not exist anymore. My question is why. I know if I create project in the setUpClass then it would be in the DB. My point is not to create extra Project and Position if I can create it via that method 1st - test it and then reuse it in the next one - but not via using (self) but by reading from DB. Question1: Is that possible? Question2: Are methods in this class using separated DBes? Question3: What is the most efficient - and proper approach to this - my point is not to create extra records and reuse data as we go. These coming out empty in the test_homepage method: print(project) print(positions) Django 2.2 Tests: from django.contrib.auth.models import User from django.test import TestCase from django.utils import timezone from stb.core.models import Profile, Skill, Project, Position class … -
How can I get Google Tag Manager to execute python and Django code?
I'm trying to replace Google Analytics (GA) code with Google Tag Manager (GTM) code. The code is meant to identify users with a username in our system. In my current GA code I call a file through Django: {{ google_analytics }} That pulls up this code: def google_analytics(request): disabled = {"google_analytics": ""} # don't track internal users if request.user and request.user.is_authenticated: if request.user.email and request.user.email.lower().endswith('@trellis.law'): return disabled if request.user.username in lawbook.config.developers: return disabled if request.user.username in lawbook.config.blog_writers: return disabled if request.user.username in lawbook.config.bio_writers: return disabled if request.user.is_staff or request.user.is_superuser: return disabled # don't track in local development environment if settings.DEBUG: return disabled # don't track in staging if lawbook.config.hostname.startswith('staging'): return disabled if request.user and request.user.is_authenticated: username = request.user.username else: username = None context = { "google_analytics_key": settings.GOOGLE_ANALYTICS_KEY, "username": username } return { 'google_analytics': render_to_string("google_analytics.html", context) } All I need to do is set a tag that does this on every page. How do I do that? -
Django Rest Framework - Nested Serialization not nesting
I am wanting a multi level nested serializer. Essentially every school has a list of students and every student has a list of grades. It is outputting this {"id":1,"name":"Sierra Grande Elem/Junior High"} and looks like it is not including any of the nests I created. Here is my models.py class School(models.Model): name = models.TextField(max_length = 150, blank=True) class Student(models.Model): current_school = models.ForeignKey( "School", null = True, on_delete = models.PROTECT, ) first_name = models.CharField(max_length = 35, blank=True) last_name = models.CharField(max_length = 35, blank=True) class Grade(models.Model): student = models.ForeignKey( "Student", null = True, on_delete = models.PROTECT, ) course = models.ForeignKey( "Course", null = True, on_delete = models.PROTECT, ) grade = models.FloatField(null = True) Here is my serializers.py class NestedSchoolSerializer(serializers.ModelSerializer): class Meta: model = School fields = ("id","name") class NestedStudentSerializer(serializers.ModelSerializer): school_set = NestedSchoolSerializer(many = True, read_only = True) class Meta: model = Student fields = ("school_set","id","first_name","last_name") class NestedGradeSerializer(serializers.ModelSerializer): student_set = NestedStudentSerializer(many = True, read_only = True) class Meta: model = Grade fields = ("student_set","id","course","grade") Here is my views.py file: class SchoolInfo(generics.RetrieveAPIView): queryset = School.objects.all() serializer_class = NestedSchoolSerializer Here is my url.py file: urlpatterns = [ path('school/grade/<int:pk>/', views.SchoolInfo.as_view()), ] Any help is much appreciated! New to Django and have been trouble shooting this for … -
Deleting formset field based on current user?
I have a modelformset being used to track inventory for a given supplier. What I'd like to do is use the current user to filter which fields in the modelformset are shown. Basically what I'd like to do is make an 'order amount' field that is specific to the user logged in. model.py class Sysco_Products(models.Model): Products = models.CharField(max_length = 200) order_amount = models.IntegerField(blank=True, null=True,) order_amount2 = models.IntegerField(blank=True, null=True,) order_amount3 = models.IntegerField(blank=True, null=True,) def __str__(self): return self.Products class meta: managed = True db_table = 'sysco_products' forms.py This doesnt work but hopefully helps you understand what I am trying to do class sysco1(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(sysco1, self).__init__(*args, **kwargs) if not self.user.filter(name_iexact='mshaf').exist(): del self.fields['order_amount'] class Meta: model = Sysco_Products fields = ('order_amount',) views.py class SyscoOrder(TemplateView): template_name= "SyscoOrder.html" def get_form_kwargs(self): kwargs = super(SyscoOrder, self).get_form_kwargs() kwargs.update({ 'user' : self.request.user }) return kwargs def get(self, request): OrderFormSet = modelformset_factory(Sysco_Products, fields=('order_amount', )) context = { 'OrderFormSet' : OrderFormSet, } return render(request, self.template_name, context) def post(self, request): OrderFormSet = modelformset_factory(Sysco_Products, fields=('order_amount',)) formset = OrderFormSet(request.POST,) if formset.is_valid(): formset.save() return redirect('Order') context ={ 'formset' : formset, } return render(request, self.template_name, context) -
Django: How to disable account registration without using a 3rd party library?
I will be releasing a website for beta testing soon, and I want to limit the number of users who are registered. I have found this stackoverflow post: (How) can i get django-registration to use the registration_closed template? which basically says to do: REGISTRATION_OPEN = False # in settings.py and create the registration_closed template. I have added that template and named it as: registration_closed.html However going to the register view does not show that the registrations are closed. It still accepts new accounts. Any ideas or help would be appreciated. I am running django 2.2 . -
Django models migrations: error--trying to add a non-nullable field
When I makemigrations to my models, the terminal gives a warning of: "You are trying to add a non-nullable field, etc" and asked for 2 options. I must have made migrations 7 times--should I delete the "0001_initial.py", "0002_auto file" as well as the db.sqlite3? I don't need to keep the database information I inputted since I merely only did tests to see if the models worked---I just want to make sure I don't delete the database itself so I can further test my models to see if they're working. Can someone please verify the specific files I would need to delete so I can make migrations? Your help will be much appreciated! So far my migrations folders look like this: 001_initial.py, 0002_auto file, 0003_auto file, 0004_auto_file, 0005_auto_file, 0006_auto file, and finally 007_order_buyers file----the last file concerns me--I think it's bc I must have clicked option 2. I just merely want to be able to makemigrations and I am wary of my models not working if I delete important files. -
Is it possible to put a constraint on a form so user cannot enter higher than value in DB in django
I have a form created in django and I want to put a constraint on it so the amount_sold must be > 0 or < coins_remaining , is this possible and if so how would I go about it? Sale form HTML below <div> <form method="POST"> {% csrf_token %} <fieldset class ="form-group"> <legend class="border-bottom mb-4">Enter Sale</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class ="btn btn-outline-info" type="submit">Enter</button> </div> </form> </div> Sale form model below class SaleForm(forms.ModelForm): amount_sold = forms.IntegerField() total_price_sold = forms.DecimalField() date_sold = forms.DateField( widget=forms.TextInput( attrs={'type': 'date'} ) ) note = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Keep a Note?'})) class Meta: fields = ['date_sold', 'amount_sold', 'total_price_sold', 'note'] model = Sale Sale model below class Sale(models.Model): amount_sold = models.IntegerField() total_price_sold = models.DecimalField(max_digits=8, decimal_places=2) date_sold = models.DateTimeField(default=timezone.now) note = models.TextField(default="") transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE, related_name="sales") amount_per_coin_sold = models.DecimalField(max_digits=8, decimal_places=2, editable=False) def __str__(self): return str(self.pk)+','+str(self.amount_sold) + ', '+self.note def save(self, *args, **kwargs): self.amount_per_coin_sold = self.total_price_sold / self.amount_sold super(Sale, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('sale-detail', kwargs={'pk': self.pk}) @property def profit_loss(self): return (self.amount_per_coin_sold - self.transaction.amount_per_coin) * self.amount_sold @property def profit_loss_percent(self): value = ((self.total_price_sold - (self.transaction.amount_per_coin * self.amount_sold))/self.total_price_sold) * 100 return round(value, 1) Transaction model below/ where I'm getting value coins_remaining from class Transaction(models.Model): currency = models.CharField(max_length=20) amount = … -
Wagtail - how to access StructBlock class attribute inside block
I'm trying to override my block template as described here: https://github.com/wagtail/wagtail/issues/3857 I added a BooleanBlock inside the class and tried to use that value to change the template but I get an error "no attribute found". class Features_Block(StructBlock): title = CharBlock() description = TextBlock(required=False) use_other_template = BooleanBlock(default=False, required=False) class Meta: icon = 'list-ul' def get_template(self, context=None): if self.use_other_template: return 'other_template.html' return 'original_template.html' I have found this thread which might be the answer but I don't understand how to implement it for my case: https://github.com/wagtail/wagtail/issues/4387 -
Upgrading Django from 2.0 to 2.2 breaks custom authentication
the files below is about custom authentication, mainly to use email as username and it works fine on Django 2.0.x. I'm starting a fresh new project in Django 2.2 and it doesn't work anymore. Why? authmanager/helper_functions.py from django.contrib.auth import authenticate, login, logout def _login(request): if request.method == 'POST': username = request.POST['email'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return True else: return False else: return False def _logout(request): request.session.flush() logout(request) return True authmanager/mybackend.py from django.contrib.auth.hashers import check_password from django.contrib.auth import backends from .models import User class MyCustomBackend(backends.ModelBackend): def authenticate(self, username=None, password=None, **kwargs): try: user = User.objects.get(email=username) if user and check_password(password, user.password): return user else: return None except User.DoesNotExist: return None def get_user(self, user_id): try: return User.objects.get(pk = user_id) except User.DoesNotExist: return None settings.py AUTHENTICATION_BACKENDS = ['crm.authmanager.mybackend.MyCustomBackend',] AUTH_USER_MODEL = 'authmanager.User' -
Why is this the right way to iterate through subwidgets of a MultiWidget?
I'm trying to use a MultiWidget form in Django. I want to use a custom template for this widget, in which I include the basic built-in templates of my subwidgets (two simple TextInputs). And I was blocked for some time on this. In order to include the templates of the two TextInput subwidgets, it seemed more clever to import the built-in ones that rewriting two HTML input tags myself. I spent a lot of time trying to understand why this wouldn't work: {% for subwidget in widget.subwidgets %} {% include subwidget.template_name %} {% endfor %} The HTML code created with that loop would be: <input type="" name="f" class="" required id="id_f" /> <input type="" name="f" class="" required id="id_f" /> And fail to work as intended: the input values wouldn't be compressed properly and the fields would both be set to the fallback value of the decompress method. Conversely,with no custom template, my multiwidget worked like a charm, with two fonctioning TextInputs rendered automatically by Django. I then had the idea I should have had at the very first: take a look at the built-in Django multiwidget HTML template! Surprise, the code looks a lot like mine: {% for widget in widget.subwidgets … -
Django: how to avoid redirecting to home page using meta tag?
Searching I've found that in order to redirect a user after he sees a confirmation page, I could put this meta tag in the html: <meta http-equiv="refresh" content="20;url=www.mysite.com/email_confirmation_needed.html"/> However, I've been told that this is not a good practice and should be avoided. How can I send users from www.mysite.com/email_confirmation_needed.html to www.mysite.com? views.py: Confirmation page appears after SignUp. ### Email Confirmation Needed ### def email_confirmation_needed(request): return render(request, "accounts/email_confirmation_needed.html") @transaction.atomic def signupView(request): if request.method == 'POST': user_form = SignUpForm(request.POST, request.FILES) profile_form = ProfileForm(request.POST, request.FILES) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) user.is_active = False user.save() username = user_form.cleaned_data.get('username') signup_user = User.objects.get(username=username) customer_group = Group.objects.get(name='Clientes') customer_group.user_set.add(signup_user) raw_password = user_form.cleaned_data.get('password1') user.refresh_from_db() # This will load the Profile created by the Signal profile_form = ProfileForm(request.POST, request.FILES, instance=user.profile) # Reload the profile form with the profile instance profile_form.full_clean() # Manually clean the form this time. It is implicitly called by "is_valid()" method profile_form.save() # Gracefully save the form # user = authenticate(username=username, password=raw_password) # login(request, user) #Cannot login a NOT Active user current_site = get_current_site(request) mail_subject = 'Confirmación de correo electrónico' message = render_to_string('accounts/acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) # to_email = user_form.cleaned_data.get('email') to_email = 'oma.gonzales@gmail.com' from_email = 'stickersgallito@stickersgallito.pe' email … -
How to hide POST request on view in django?
I have one view which has POST and GET request. For POST request data comes from other URL. I don't use this view to POST the data. However, I have GET request for same view which retrieve data from the model and display. Now, when I open(GET request) this view it correctly show the data. But in addition it shows text are for POST request as well. I want to hide POST request on my view. Code: @api_view(['POST','GET',]) def TestView(request): if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) customers_instance = Customers.objects.create(firstname=data[0]["value"], lastname=data[1]["value"], dob=data[2]["value"], emailaddress=data[3]["value"], address1=data[4]["value"], address2=data[5]["value"], city=data[6]["value"], state=data[7]["value"], postalcode=data[8]["value"]) return HttpResponse('Data has been received by API') if request.method == 'GET': qs= Customers.objects.values('emailaddress','customer_id') serializer_class = CustomersKeySerializer return Response(serializer_class(many=True).to_representation(qs)) -
How to create expiry date reminders of shop items with django
i am a beginner in Python Django programming. I want to develop an expiry date reminder for drugs in a drugstore app i am developing. i have tried some codes in the models.py and views.py files but it didn't work from django.shortcuts import render,redirect from django.contrib.auth.models import User from .models import Expiry from django.contrib import messages from datetime import datetime from django.utils import timezone def index(request): if ['date_expiry']==datetime.today(): messages.success(request,f'your drug has expired') context = {'posts': Expiry.objects.all()} return render(request, 'drugs/home.html',context) -
How to add cookie to header through Django Channels?
In my frontend, I have the following configuration. Authentication is manual because react native fails at having persistent sessions: ... const authLink = setContext(request => storage.getCookie().then(cookie => ({ // Before the request is sent: set cookie header headers: { cookie, }, credentials: 'omit', // set cookies manually })) ) const setTokenLink = new ApolloLink((operation, forward) => { // Send the request to the server return forward(operation).map(response => { // After response is returned: store cookie in local storage const context = operation.getContext() const { response: { headers }, } = context if (headers) { storage.setCookie(headers.get('set-cookie')) } return response }) }) storage.getCookie().then(cookie => console.log(cookie)) // console.log('cookie', storage.getCookie().then(cookie => {cookie})) const httpLink = createUploadLink({ uri: `${domainApi}/graphql/`, }) const wsClient = new SubscriptionClient( domainWs, { lazy: true, reconnect: true, connectionParams: { authToken: storage.getCookie(), }, }) ) ... Yet this seems to affect websockets, because at the backend, the headers don't contain the cookie. class GraphqlSubcriptionConsumer(SyncConsumer): def __init__(self, scope): super().__init__(scope) self.subscriptions = {} self.groups = {} def websocket_connect(self, message): self.send({"type": "websocket.accept", "subprotocol": "graphql-ws"}) def websocket_disconnect(self, message): for group in self.groups.keys(): group_discard = async_to_sync(self.channel_layer.group_discard) group_discard(f"django.{group}", self.channel_name) self.send({"type": "websocket.close", "code": 1000}) raise StopConsumer() def websocket_receive(self, message): request = json.loads(message["text"]) id = request.get("id") if request["type"] == "connection_init": … -
chrome extension getting session data from website
in my django project, i have a url that has login_required set, because i need the request.user variable in it to process some data, i also created a simple chrome extension where i'm going to have to send requests to that django project url. i do not want to use the username and password in the extension to login and send the request i want to: redirect the user when the extension is installed to the my website they will login, the extension will know that the user has logged in and it will get (and save) a key that i could maybe inject in the page after login is successful the key can be used as a query parameter in the request in order to identify the user without any username and password i'm sorry if this seems as a stupid question, but i'm very confused on how to do this PS: i have already a system in place where the user can use a key in order to make requests without logging in, i just need a way to open a tab when the extension is installed, and login then get the key (which is injected in the … -
How to get multiple objects of a model without using filter?
In Django 2.2, we can use filter() to get a QuerySet of created objects. Using list(), I can have a list of QuerySet. In order to get an instance of a model I can use the function get(), for instance MyModel.objects.all.get(name__exact="John"). However, the get() function works only for finding a single object. If if finds 2 or more objects, it returns an exception: MultipleObjectsReturned get() returned more than one. Since I need to process the multiple object of my model and its attributes, I would like to get a list of objects. Is it possible? If yes, how can I retrieve multiple objects in a list? Thanks. -
Django custom model field is not getting saved to database. Gives escaping error
I am creating a custom model field and I have copied the same code example given the docs so far. Using that example I am able to create a column in the database after running migrations but when I tried to save an object in the data base I am getting TypeError: can't escape str to binary I assumed that the given docs example would run without any problem and from that I could customize it but even after including all the docs material it didn't run. Portion of The Error return executor(sql, params, many, context) File "/home/vikram/python-virtual-environments/project/lib/python 3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) TypeError: can't escape str to binary The Model class test(models.Model): a = HandField() CustomField Class from django.db import models import re class Hand: """A hand of cards (bridge style)""" def __init__(self, north, east, south, west): # Input parameters are lists of cards ('Ah', '9s', etc.) self.north = north self.east = east self.south = south self.west = west def parse_hand(hand_string): """Takes a string of cards and splits into a full hand.""" p1 = re.compile('.{26}') p2 = re.compile('..') args = [p2.findall(x) for x in p1.findall(hand_string)] if len(args) != 4: raise ValidationError(_("Invalid input for a Hand instance")) … -
Another reason of django.db.migrations.exceptions.InconsistentMigrationHistory
Why else django.db.migrations.exceptions.InconsistentMigrationHistory exception may happen while trying to do migrations in Django?