Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I customize the "username already exists" message?
My forms.py has a custom user-creation class... class RegisterForm(UserCreationForm): error_messages= { "password_mismatch": _("Passwords do not match."), } To clarify, I do not know which error_messages key corresponds to the one Django spits out when a user tries to sign up with a username that already exists. Which error message do I need to replace for when the user chooses a username that already exists? -
Escape additional characters with Django autoescape
I'm trying to extend Django default autoescape behavior to escape the {} characters. The issue is our Django templates are printing inline JS templates (angular.js). But this means some variable django prints might contains {{}} characters that are going to be executed - thus allowing XSS. We're usually doing escapes and backend validation, but some old pages might've skipped the basic checks. Any chance we can hook directly in the autoescape behavior to also HTMl encode those extra characters automatically? -
Where do I run the terminal from when I deploy my django app from a public server?
So at the moment I run my django app in a virtual environment locally. I go to my project root an perform source bin/activate and now I am running my projects terminal from there. My question is where do I run the terminal when I deploy my app on a public server? Lets say I deploy my app on Digital Ocean with Nginx & Gunicorn. On what platform do I run the terminal through? And how do I activate it similar to how I activted my virtual env? -
How to get input value from templates and store to database [Django]
I'm trying to get {{ id }} when user clicks on movie and save it to models. I can't use modelForm because id parameter comes from html template. Any suggestions? Maybe, there is a different way to get an id of that movie user clicks? Btw, I'm using tmdb api. {% for id, poster in poster_id_zip %} <div style="display: inline-block; margin: 10px;" class=""> <a href="{{ movie_details }}"><img src="{{ poster }}" alt=""></a> <form class="add-movie-form" method="POST"> {% csrf_token %} <input type="hidden" name="movie-id" value="{{ id }}"> <button style="display: block; margin: 5px auto 0 auto;" type="submit" name="add">Add</button> </form> </div> {% endfor %} views.py def index(request): api_key = "api_key" image_base_url = "https://image.tmdb.org/t/p/" if request.method == "POST": user_query = request.POST.get('search-box', ' ') if user_query == '': user_query = ' ' search_movies_url = "https://api.themoviedb.org/3/search/movie?api_key={}&query={}".format(api_key, user_query) search_results_data = requests.get(search_movies_url) total_results = search_results_data.json().get("total_results") # for handling no search results movie_ids, poster_path, poster_full_url = [], [], [] for movie in search_results_data.json().get("results"): movie_ids.append(movie.get("id")) poster_path.append(movie.get("poster_path")) for poster in poster_path: poster_full_url.append(image_base_url+"{}{}".format("w185", poster)) movie_details = "https://api.themoviedb.org/3/movie/{}?api_key={}".format(movie_ids, api_key) poster_id_zip = zip(movie_ids, poster_full_url) # groupping ids with poster images context = {"movie_ids": movie_ids, "poster_url": poster_full_url, "movie_details": movie_details, "poster_id_zip": poster_id_zip, "total_results": total_results,} return render(request, 'homepage/movies.html', context) return render(request, 'homepage/index.html') models.py from django.db import models # Create your … -
child node is treated as grand child node when trying to structure
I am using django-mptt library for the category. I could show the list of categories in template but I wanted to indent it properly so user can know which is a main category and which one is sub-category and etc. The way i tried to structure is {% recursetree nodes %} <li class="node"> <a href="/category/{{ node.get_absolute_url }}" class="{% if not node.is_leaf_node and not node.is_root_node and node.is_child_node %} child_parent {% elif node.is_leaf_node and not node.is_root_node %}leaf_node{% endif %}"> {{ node.name }} {% if node.is_root_node %} <span class="badge">{{ node.get_count_children }}</span> {% endif %} </a> {% if not node.is_leaf_node %} <ul class="children"> <li>{{ children }}</li> </ul> {% endif %} </li> {% endrecursetree %} This yields the following design of category Here Dressing Table is a child of Bedroom Items like Bed and Almirah not a child of Bed. How could i fix this? I know the problem is here <a href="/category/{{ node.get_absolute_url }}" class="{% if not node.is_leaf_node and not node.is_root_node and node.is_child_node %} child_parent {% elif node.is_leaf_node and not node.is_root_node %}leaf_node{% endif %}"> but could not fix this issue -
grab the first item in an object array in DJango Templates
I have a django template that has two different querysets passed through to the html template. I want to go through each item in an query set and display the content, I then want to go through the second array while still in the iniital loop and check to see if two peices of info match. If there is a match between the two peices of info, I want to just grab the first result from teh matching info. I have a query that grabs a list of group items. I have another query that grabs the list of activities. I want to get all the activity objects that are related to the group through the foreignkey and reference to the group within the activity object. From the list of related activities ot the group, I want to grap the first record and display that record only... If a group (a) has 10 activities related tot he group, I want to grab the first one and display it... Here is my code: html tempalte: <div class="col-12 info-div"> {% for group in groups %} <div class="row"> <p class="col-12"> <a href="{% url 'group_home' group.group.name|slugify group.group.id %}">{{ group.group.name }}</a> </p> {% for act … -
NoReverseMatch when it has not to occur
everyone! I'm new to Django and actually making a study project. I'm getting a NoReverseMatch exception and can't understand why. It seems not to have namespace conflicts, the other list views are made in the same way as for the StoredItem model, but only this one throws an exception: models.py: from django.db import models from django.urls import reverse # Create your models here. class LegalEntity(models.Model): name = models.CharField(max_length=100, help_text="Name") rif = models.CharField(max_length=10, help_text="RIF") address = models.TextField(help_text="Address") phone_num = models.CharField(max_length=15, help_text="Phone number") def __str__(self): pass class Contract(models.Model): name = models.CharField(max_length=100, help_text="Name") number = models.CharField(max_length=50, help_text="Contract number") description = models.TextField(help_text="Contract description") start_date = models.DateField(null=False, blank=False, help_text="Start date") expiry_date = models.DateField(null=True, blank=True, help_text="Expiry date") def __str__(self): return "number: {0}, " \ "name: \"{1}\", " \ "starts: {2}, " \ "expires: {3}."\ .format(self.number, self.name, self.start_date, self.expiry_date) def get_absolute_url(self): return reverse('contract-detail', args=[str(self.id)]) class Provider(LegalEntity): contract = models.ForeignKey(Contract) def __str__(self): return "name: \"{0}\", " \ "RIF: {1}, " \ "phone: {2}."\ .format(self.name, self.rif, self.phone_num) def get_absolute_url(self): return reverse('provider-detail', args=[str(self.id)]) class Item(models.Model): name = models.CharField(max_length=100, help_text="Name") serial = models.CharField(max_length=50, help_text="Serial No.") manufacturer = models.CharField(max_length=50, help_text="Manufacturer") provider = models.ForeignKey(Provider) def __str__(self): return "name: \"{0}\", " \ "serial: {1}, " \ "manufacturer: {2}," \ "provider: {3}."\ .format(self.name, self.serial, self.manufacturer, … -
Django: redirect to DetailView without pk in URL
I want to make sign-up forms with Django1.11. urls.py app_name = 'accounts' urlpatterns = [ url(r'^create/$', views.SignUpView.as_view(), name='create'), url(r'^check/$', views.CheckView.as_view(), name='check'), url(r'^update/$', views.CorrectView.as_view(), name='update'), # ... ] views.py class SignUpView(CreateView): model = User form_class = UserForm template_name = "accounts/create.html" def get_success_url(self): check_view = CheckView.as_view() return redirect(check_view, pk=self.object.pk) class CheckView(DetailView): model = User template_name = "accounts/check.html" class CorrectView(UpdateView): model = User form_class = UserForm template_name = "accounts/create.html" def get_success_url(self): check_view = CheckView.as_view() return redirect(check_view, pk=self.object.pk) After a new user inputs his information in SignUpView(generic.CreateView), he will see what he just has input in CheckView(generic.DetailView), and if he notice that he has made some mistakes, he reinput his information in CorrectView(generic.UpdateView). I want not to make url r'^check/(?P<pk>[0-9]+)$' for example. This is because if an user inputs a URL .../check/1 for example in browser, unfortunately he can see the information of another person. When I run the code above, the error Reverse for 'accounts.views.CheckView' not found. 'accounts.views.CheckView' is not a valid view function or pattern name. is occurred. Please tell me how to redirect to CheckView(generic.DetailView) without url include pk. -
Create ModelChoiceField with annotation
I need to make a selector with genders (male and female) with the respectives counts of each type. For example, if I have 4 males and 8 females in my DB, I need a select tags with options "Select gender" "Male (4)" "Female (8)" In my Form class I have gender = forms.ModelChoiceField( queryset=Gender.objects.all().annotate(counter=Count('user')), required=False, label="Gender" ) And I don't know how to render this select element. If I use {{ form.gender }} I can't even display the options. I get Error binding parameter 0 - probably unsupported type. It could be an SQLite issue? I will use PostgreSQL as my DB anyway. Any suggestions? -
Python Celery Q Task Status Always Pending or Success
I am trying to run around Django and Celery. I just using sample program and get stuck in Status of the Tasks. I am not sure, if I doing any wrong with configuration, but everything seems to follow all the steps. Also the Backend and Workers is working properly. In case, I want to get the status of the Q-tasks so that it's easy to identify whether the Job is "Running", "Success", or "Failure". But I end up with the status always "PENDING" and "SUCCESS" in case of Success. Sample Sum for Worker Worker Information Job Call Job 1st Check Status --> Always Pending Check Status from AsynChronization --> Also Always Pending or Success in Case of complete -
Get a dynamically changing django modelform based on user input
Django noob here. I'm trying to learn how to implement a modelform that based on a fkey for an event, can accept multiple items a user is trying to sell at an event. Here is my models.py: class seller_event_items(models.Model): item_id = models.AutoField(primary_key=True) event_id = models.ForeignKey(seller_event) item_name = models.CharField(max_length = 300, default = 'Null') item_price = models.CharField(max_length = 300, default = 'Null') item_quant = models.CharField(max_length = 300, default = 'Null') def __unicode__(self): return str(self.item_id) + str(self.event_id) So what I'm trying to do is: 1. Accept a form where the user creates an event. This can be part of the same html form or not. I can figure that out separately. 2. Get the event_id as foreign key and then let the user input as many items as they want for that event by clicking an html button to multiply the item fields. So for example, the html form first only contains fields for 1 item. Then the user presses a button and fields for another item gets added dynamically and so on. Any suggestions on how I could go about doing this? Thanks in advance! Let me know if I should add any more details. -
django-decouple throws an error whenever it encounters '.'
django-decouple throws an error 'tuple' object has no attribute 'rsplit' module_path, class_name = dotted_path.rsplit('.', 1) AttributeError: 'tuple' object has no attribute 'rsplit' whenever it encounters '.' e.g django.core.mail.backends.smtp.EmailBackend, smtp.gmail.com Kindly help -
Dynamic form field rendering/validation
I’ve been trying to come up with a scalable solution for a dynamic form. The problem is that the form itself has a tree structure similar to: A / | \ B C D / \ / \ E F G H Each level is a different panel, containing a number of fields that may or may not have dependencies on lower levels. The problem comes in when a field E is directly dependant on B, but a user can pick C or D at any given point, removing the choice/flow selected (E). I believe for this solution a tree would be best to use, but that approach becomes increasingly complex to handle and maintain as more options can be introduced for any level, specifically the first one. The most efficient solution I’ve found is to use nested dictionaries to map the different dependencies, but this proves to be a very costly method in terms of updating the structure to handle new fields or existing fields differently, since all of the logic would need to be readded. Is there a library/known solution to this problem? -
Django Form Logic: Split and display prefilled values
Let's say I have a model that holds several different charfields. models.py class Items(models.Model): languages = models.Charfield(...) settings = models.Charfield(...) audio = models.Charfield(...) The data is saved within each with a delimiter ("||"). I would like to create a form that splits the data then prefills the value with the saved data. Theoretically: {'languages': 'English||French||German'} {'settings': '1.1||1.1||2.0'} {'audio': 'yes||no||yes'} Would be split to: {'languages': ['English', 'French', 'German']} {'settings': ['1.1', '1.1', '2.0']} {'audio': ['yes', 'no', 'yes']} Then each value would auto-populate the value field. Eventually displaying as: <tr> <td><input type="text" name="languages[]" value="English"></td> <td><input type="text" name="settings[]" value="1.1"></td> <td><input type="text" name="audio[]" value="yes"></td> </tr> <tr> <td><input type="text" name="languages[]" value="French"></td> <td><input type="text" name="settings[]" value="1.1"></td> <td><input type="text" name="audio[]" value="no"></td> </tr> ... As each row would have a different amount of 'languages', for example, what is the preferred way to create this type of form. I am using Django 1.11. First question posted, so if I have missed something within this post, would you kindly let me know? I also have searched for information related to this, however I have yet to find a solution. Thanks! -
django form textarea allow vertical resize only
in my django project I made a form using message = forms.CharField(widget=forms.Textarea) It works out ok and I get this. The text area is resizeable both horizontally and vertically: I would like to make it un-resizeable horizontally, what should I do? I tried adding "attrs=" to the textarea but can't figure out what to call... Please help... Thanks. -
How to use icontains in a key value of a DictField in Django queryset?
Given the following model: class Team(models.Model): name = models.CharField(max_length=50) others = DictField() And the following code: bahia = Team() bahia.name = "E.C. Bahia" bahia.others = {"title": "Ninguém nos Vence em Vibração!!!"} bahia.save() vicetoria = Team() vicetoria.name = "E.C. Vicetoria" vicetoria.others = {"title": "Vice de tudo!"} vicetoria.save() I want to find the object that have the word vence, (case insensitive) contained in title value of the field others. I tried something like: teams = Team.objects.filter(others__title__icontains="vence") that gives me the following error: FieldError: Join on field 'others' not permitted. Did you misspell 'title' for the lookup type? I also already tried: teams = Team.objects.filter(others__icontains={"title":"vence"}) that returns None and I know there is at least one collection as result. How can I solve this? Thanks for your help. -
Working with multiple related django modelforms
I'm trying to get two forms derived from related models to display on the same page and save together. This is my models.py: class userinfo(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key= True, on_delete=models.CASCADE) name = models.CharField(max_length = 200, blank = True) email = models.EmailField(max_length= 300, default = 'Null') phone = models.CharField(max_length= 10, default = 'Null') def __unicode__(self): return self.user class seller_event(models.Model): event_id = models.AutoField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length = 300, default = 'Null') description = models.CharField(max_length = 300, default = 'Null') location = models.CharField(max_length= 300, default = 'Null') cash_payment = models.BooleanField(default=False) paytm_payment = models.BooleanField(default=False) def __unicode__(self): return str(self.event_id) + str(self.title) As you can see, the user (saved as user_id in my sqlite3 db) is the foreign key from the userinfo table. I'm trying to get multiple events listed for each seller. forms.py: class Userinfo(forms.ModelForm): class Meta: model = userinfo exclude = {'user'} class Seller_event(forms.ModelForm): class Meta: model = seller_event exclude = {'user'} views.py: def newlist(request): if request.user.is_authenticated(): user = request.user print user if request.method == 'POST': userinfo_form = Userinfo(request.POST, instance = user.userinfo) seller_event_form = Seller_event(request.POST, instance = user.seller_event) if userinfo_form.is_valid() and seller_event_form.is_valid(): userinfo_form.save() seller_event_form.save() return redirect('/home') else: userinfo_form = Userinfo() seller_event_form = Seller_event() return render(request, 'home/newlist.html', {'userinfo_form': userinfo_form, 'seller_event_form': … -
Proxy model error: Local field in class clashes with field of the same name from base class
class EmailUser(User): class Meta: proxy = True email = models.EmailField(_('email address'), unique=True) In the above, I'm trying to implement a proxy model, but I'm getting this error message: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10e04ed08> Traceback (most recent call last): File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/workout/workoutcal/models.py", line 28, in <module> class EmailUser(User): File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/models/base.py", line 231, in __new__ base.__name__, django.core.exceptions.FieldError: Local field 'username' in class 'EmailUser' clashes with field of the same name from base class 'User'. I wonder why I get this error, and what to do … -
django creating generic class to validate User authentication
I am trying to replace the generic View class with a custom class so that the user authentication happens automatically when i make a reference to this class. The Base Class class CustomView(View): def __init__(self, request): if not request.user.is_authenticated: redirect('register.registerForm') The sub class class DashboardPage(CustomView): def get(self, request): user_object = User.objects.get(username=request.user) all_files = user_object.files_set.all() return render(request, 'dashboard/dashboard.html', {'all_files': all_files}) I expected the user authentication happened automatically when the CustomView class is called. And also wanted to know if this is the best way to generalize user authentication for all the pages in my application which require authentication. I am getting the below error: TypeError at /dashboard/ __init__() missing 1 required positional argument: 'request' Request Method: GET Request URL: http://127.0.0.1:8000/dashboard/ Django Version: 1.11.7 Exception Type: TypeError Exception Value: __init__() missing 1 required positional argument: 'request' Exception Location: C:\Program Files (x86)\Python36-32\lib\site-packages\django-1.11.7-py3.6.egg\django\views\generic\base.py in view, line 62 Python Executable: C:\Program Files (x86)\Python36-32\python.exe Python Version: 3.6.3 Python Path: ['C:\\Users\\Varun\\Desktop\\newsite', 'C:\\Program Files (x86)\\Python36-32\\python36.zip', 'C:\\Program Files (x86)\\Python36-32\\DLLs', 'C:\\Program Files (x86)\\Python36-32\\lib', 'C:\\Program Files (x86)\\Python36-32', 'C:\\Program Files (x86)\\Python36-32\\lib\\site-packages', 'C:\\Program Files ' '(x86)\\Python36-32\\lib\\site-packages\\django-1.11.7-py3.6.egg', 'C:\\Program Files ' '(x86)\\Python36-32\\lib\\site-packages\\pytz-2017.3-py3.6.egg'] Server time: Mon, 4 Dec 2017 20:43:12 +0000 -
Where to put bin, include and lib directories from virtual environment into development repository?
I have a Django project which I've been running on a local virtual environment, here's how the root directory looks (draft1 is my app). I'm now ready to push this project to a repo so I can start to develop it on a public server - so my question is - where do the bin, include and lib directories go? How do they translate from local development to when using a public server? -
'WSGIRequest' object has no attribute 'some_attribute'
I am trying to render html to pdf and include it as a django action, however, for some odd reason, I seem to keep getting the issue that the object has no attribute 'some_attribute'. My view looks like this: class CreatePdf(ContextMixin, View): def get_context_data(self, obj, request): cxt = {'some_attribute': obj.some_attribute, 'today': date.today()} return cxt def create_pdf(self, some_template, some_dict={}): template = get_template(some_template) html = template.render(some_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue()) return None And the action, which had the purpose to call everything and do all the magic, looks like this: def get_pdf(self, obj, request): pdf_view = views.CreatePdf() pdf = pdf_view.create_pdf('templates/some_template.html', pdf_view.get_context_data(obj,request)) return HttpResponse(pdf) I thought, that using get_context_data will get the fields of the selected object in the admin field, however, it seems to through me the same error. -
How to override Model.objects.all() to a subset of the same globally
The Scenario I'm developing a web application that will store multiple Organizations and each organization has it's own users. For me an organization is a domain and the domains can't see each others at database level. Instead of creating N databases/views to simplify the management and speed up the performances I store the data of all organizations onto the same database. The Goal What I want to implement is a simple way to retrieve the data from my database that are already filtered by domain. Since each domain belongs to an User (or vice versa) the first option that come in my mind is to use a queryset defined in this way: def MyCustomViewSet(viewsets.ModelViewSet) queryset = Model.objects.all(domain__iexact=request.user.domain) I can't use this solution because it forces the developer to filter all queries manually all around the web application. If for some reason someone forget to properly filter queryset, the users of an organization can see the data of other organizations (and vice versa) - It's error-prone. Using thread locals Since I can find the user inside the request another solution would be to expose the request through a middleware and automatically filter by domain using the domain of the user that … -
Edit form that has ForeignKey to other model
I have a form that a user need to fill up, the model of that form as ForeignKey to another model (Question) When I create a new form, it works as I expect. When I try to do edit an existing record I am able to get the relevant data in the template but when I click on submit It fails with no error – when I debug it its failes on form is not valid and that the question is None. # form class AnswerForm(forms.ModelForm): question = forms.ModelChoiceField( label=_(u'question'), widget=forms.HiddenInput(), queryset=Question.objects.all()) description = forms.CharField( label=_(u'description'), widget=forms.Textarea(attrs={'class': 'form-control', 'rows': '4'}), max_length=2000, required = False) link = forms.URLField( label=_(u'link'), max_length=1000, required = False) price = forms.DecimalField( label=_(u'price'), widget=forms.TextInput(attrs={'class': 'form-control'}), #max_length=100, required = False) currency = forms.ModelChoiceField( label=_(u'currency'), required=False, queryset=Currency_converter.objects.all()) class Meta: model = Answer exclude = ('user','link_domain_name',) fields = ['link','price', 'currency','description'] def clean(self): cleaned_data = super(AnswerForm, self).clean() if cleaned_data.get('link')=='' and cleaned_data.get('price')==None and cleaned_data.get('description')=='' : raise forms.ValidationError(_("You must fill at least one field!")) if cleaned_data.get('link')=='' and cleaned_data.get('price')!=None : raise forms.ValidationError(_("Add link to the price you found!")) if cleaned_data.get('price')!=None and cleaned_data.get('currency')==None : raise forms.ValidationError(_("set currency for the price you set!")) return cleaned_data #view def answer(request,question_id ,answer_id): path_to_pic = filepath_link_as_pictures() question = get_object_or_404(Question, pk=question_id) … -
PyCharm + Django ImportError: cannot import from models in python console
I'm building Django website (Django 1.11.2 and Python 3.5.2), and I faced with the problem File "<input>", line 1, in <module> ImportError: cannot import name 'Test' When executing a command from events.models import Test Code of events.models # coding=utf-8 from __future__ import unicode_literals from http.client import HTTPSConnection from datetime import timedelta from django.conf import settings from django.contrib.auth import get_user_model import json from django.utils.safestring import mark_safe from django.db import models from django.urls import reverse from django.utils.timezone import now from django_cron import CronJobBase, Schedule from django.db.models import Max class EventClass(models.Model): game_class = models.CharField(max_length=100) game_name = models.CharField(max_length=100) tournament_name = models.CharField(max_length=100) tournament_round = models.CharField(max_length=100) tournament_type = models.CharField(max_length=100) class Event(models.Model): game_class = models.CharField(max_length=100) ........................................ ........................................ class Test(models.Model): test = models.CharField(max_length=100) How can I import without any error? -
Why is django 2 available under python 2?
According to Django 2.0 release notes Django 2.0 onwards will only support python 3, making the 1.11.X the last release series to support python 2. See quote from the release notes page: Django 2.0 supports Python 3.4, 3.5, and 3.6. We highly recommend and only officially support the latest release of each series. The Django 1.11.x series is the last to support Python 2.7. However when running pip2 install Django, django version 2 is being installed (which then fails because it assumes functionality not available in python 2): (venv-crap) mbp15:server nir$ pip2 install django Collecting django Downloading Django-2.0.tar.gz (8.0MB) 100% |████████████████████████████████| 8.0MB 177kB/s Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/PATH/django/setup.py", line 32, in <module> version = __import__('django').get_version() File "django/__init__.py", line 1, in <module> from django.utils.version import get_version File "django/utils/version.py", line 61, in <module> @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/PATH/django/ I know I can manually specify requirement version below 2, making pip install a version valid for python 2, however that will complicate the installation process if I want to support both python2 and …