Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        How do I create a Team Leader/Group Leader in Django?I'm new(this is my first project) to web development. I'm creating an internal data management for the company i work for. We have different departments(like r&d, product development, etc) which I have instantiated as objects via Django admin. I have created employees as normal Users in django admin. I would like to know how I can create a model/anything which can tell me the department manager.
- 
        Django Login Form Input Fields not showing upworking on a Django Web project for a class. Created an own template for the login page, that looks like this {% extends 'thirdauth/base.html' %} {% block content %} <h2>Login</h2> <div class="login-form"> <form method="post" action="{% url 'thirdauth:login' %}"> {{form.as_p}} {% csrf_token %} <input type="hidden" name="next" value="{{ next }}" /> <p><input type="submit" value="Login"></p> </form> </div> <br> <p><strong>-- OR --</strong></p> <a href="{% url 'thirdauth:social:begin' 'github' %}">Login with GitHub</a><br> {% endblock %} The only problem that I face is that the input fields for user and password + labels are not showing up when the sites initially loads. When I click on the Login button, the fields appear and I can enter everything and it works fine... Here is the urls.py from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth import views as auth_views from . import views urlpatterns = [ url(r'^login/$', auth_views.login, name='login'), url(r'^logout/$', auth_views.logout, name='logout'), url(r'^auth/', include('social_django.urls', namespace='social')), url(r'^admin/', admin.site.urls), url(r'^accounts/login/$', views.authentication, name='authentication'), ] I'm thankful for help, I think it is just a small stupid mistake from me, but I'm not able to find it, most help on the internet focuses on self defined forms.
- 
        Trying to push Django app to Heroku - error around anaconda?I'm trying to push a Django app that uses NLTK and Scikit-learn. I have put all the relevant dependencies in the requirements.txt file, but I keep getting this error. Any suggestions? remote: -----> Installing requirements with pip remote: Collecting alabaster==0.7.10 (from -r /tmp/build_e87edffdf382e76739e44cf354aacd2b/requirements.txt (line 1)) remote: Downloading alabaster-0.7.10-py2.py3-none-any.whl remote: Collecting anaconda-client==1.6.5 (from -r /tmp/build_e87edffdf382e76739e44cf354aacd2b/requirements.txt (line 2)) remote: Could not find a version that satisfies the requirement anaconda-client==1.6.5 (from -r /tmp/build_e87edffdf382e76739e44cf354aacd2b/requirements.txt (line 2)) (from versions: 1.1.1, 1.2.2) remote: No matching distribution found for anaconda-client==1.6.5 (from -r /tmp/build_e87edffdf382e76739e44cf354aacd2b/requirements.txt (line 2)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to XXX. remote: To https://git.heroku.com/secure-mountain-49046.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/XXX.git'
- 
        Browser side cookie issueI am creating a cookie to store some data( how many times the user visited a page)in the client side. Here I am trying to understand the client side cookie. I am able to achieve the desired result using a server side cookie. But in this client side cookie set up every time I visit the page the cookie count is not increasing. Below is the cookie code in my Django view, Please help me understand what I am doing wrong. def index(request): if 'visited' in request.COOKIES: visited = int(request.COOKIES['visited']) visited += 1 response = render(request,'index.html',context={'visited':visited}) else : response = render(request,'index.html',context={'visited':0}) response.set_cookie('visited',1) return response
- 
        How to setup Django inside virtualenv on Windows?Any Windows python developers here? I created a virtualenv, activated it and installed django. If I run pip3 list, it shows Django (2.0.3) as installed. The problem is when I try and use django, it never works, it just returns "no module django." When I try pip3 install django again, it says it's already installed at myname\envs...\site-packages. But when I use the django command it never looks at this path, it looks at appdata/local/programs/python/python36-32/python.exe (i.e. not the virtualenv but the python installation itself). Anyone have any ideas?
- 
        Get only decimal django-moneyI've instaled django-money module to a project. When try to render in a template, the money file is rendered: $100.00 Is there any method to only render the decimal value without the symbol? Such as: 100.00
- 
        Django 2.0 SQLite3 to MySQL loaddata error: "The database backend does not accept 0 as a value for AutoField."I am attempting to transfer a database from sqlite to mysql. I've googled this error and found Stack Overflow matches, but havent seen how to debug/identify the offending "0 value AutoField" fields. I've tried skirting the issue by dumping/loading different tables, but all seem to generate the same error. I've attempted appending -e contenttypes, --natural-foreign, and --natural-primary to my datadump command, e.g., python manage.py dumpdata -e contenttypes --natural-foreign --natural-primary --indent=4 > datadump_3-7-18.json After running python manage.py loaddata --traceback datadump_3-7-18.json It produces the traceback error: (venv) ➜ bikerental git:(additional-features-march) ✗ python manage.py loaddata --traceback datadump_3-7-18.json Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/rentals/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/rentals/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/rentals/venv/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/rentals/venv/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/rentals/venv/lib/python3.6/site-packages/django/core/management/commands/loaddata.py", line 72, in handle self.loaddata(fixture_labels) File "/rentals/venv/lib/python3.6/site-packages/django/core/management/commands/loaddata.py", line 113, in loaddata self.load_label(fixture_label) File "/rentals/venv/lib/python3.6/site-packages/django/core/management/commands/loaddata.py", line 177, in load_label obj.save(using=self.using) File "/rentals/venv/lib/python3.6/site-packages/django/core/serializers/base.py", line 205, in save models.Model.save_base(self.object, using=using, raw=True, **kwargs) File "/rentals/venv/lib/python3.6/site-packages/django/db/models/base.py", line 759, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/rentals/venv/lib/python3.6/site-packages/django/db/models/base.py", line 842, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/rentals/venv/lib/python3.6/site-packages/django/db/models/base.py", line 880, …
- 
        Parsing JSON Github API - Django 1.8I have this in my views.py: def profile(request): parsedData = [] if request.method == 'POST': username = request.POST.get('user') req = requests.get('https://api.github.com/users/' + username + '/repos') jsonList = [] jsonList.append(req.json()) userData = {} data = ['owner'] for data in jsonList: userData['html_url'] = data['owner'][0]['html_url'] userData['created_at'] = data['created_at'] userData['updated_at'] = data['updated_at'] userData['forks_count'] = data['forks_count'] parsedData.append(userData) return render(request, 'app/profile.html', {'data': parsedData}) This throws me: TypeError at /app/profile/ list indices must be integers, not str This is an example JSON returned by /repos on Github: { "id": 77549474, "name": "acp", "full_name": "kkoci/acp", "owner": { "login": "kkoci", "id": 3047897, "avatar_url": "https://avatars0.githubusercontent.com/u/3047897?v=4", "gravatar_id": "", "url": "https://api.github.com/users/kkoci", "html_url": "https://github.com/kkoci", "followers_url": "https://api.github.com/users/kkoci/followers", "following_url": "https://api.github.com/users/kkoci/following{/other_user}", "gists_url": "https://api.github.com/users/kkoci/gists{/gist_id}", "starred_url": "https://api.github.com/users/kkoci/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/kkoci/subscriptions", "organizations_url": "https://api.github.com/users/kkoci/orgs", "repos_url": "https://api.github.com/users/kkoci/repos", "events_url": "https://api.github.com/users/kkoci/events{/privacy}", "received_events_url": "https://api.github.com/users/kkoci/received_events", "type": "User", "site_admin": false }, "private": false, "html_url": "https://github.com/kkoci/acp", "description": null, "fork": true, "url": "https://api.github.com/repos/kkoci/acp", "forks_url": "https://api.github.com/repos/kkoci/acp/forks", "keys_url": "https://api.github.com/repos/kkoci/acp/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/kkoci/acp/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/kkoci/acp/teams", "hooks_url": "https://api.github.com/repos/kkoci/acp/hooks", "issue_events_url": "https://api.github.com/repos/kkoci/acp/issues/events{/number}", "events_url": "https://api.github.com/repos/kkoci/acp/events", "assignees_url": "https://api.github.com/repos/kkoci/acp/assignees{/user}", "branches_url": "https://api.github.com/repos/kkoci/acp/branches{/branch}", "tags_url": "https://api.github.com/repos/kkoci/acp/tags", "blobs_url": "https://api.github.com/repos/kkoci/acp/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/kkoci/acp/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/kkoci/acp/git/refs{/sha}", "trees_url": "https://api.github.com/repos/kkoci/acp/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/kkoci/acp/statuses/{sha}", "languages_url": "https://api.github.com/repos/kkoci/acp/languages", "stargazers_url": "https://api.github.com/repos/kkoci/acp/stargazers", "contributors_url": "https://api.github.com/repos/kkoci/acp/contributors", "subscribers_url": "https://api.github.com/repos/kkoci/acp/subscribers", "subscription_url": "https://api.github.com/repos/kkoci/acp/subscription", "commits_url": "https://api.github.com/repos/kkoci/acp/commits{/sha}", "git_commits_url": "https://api.github.com/repos/kkoci/acp/git/commits{/sha}", "comments_url": "https://api.github.com/repos/kkoci/acp/comments{/number}", "issue_comment_url": "https://api.github.com/repos/kkoci/acp/issues/comments{/number}", "contents_url": "https://api.github.com/repos/kkoci/acp/contents/{+path}", "compare_url": "https://api.github.com/repos/kkoci/acp/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/kkoci/acp/merges", "archive_url": "https://api.github.com/repos/kkoci/acp/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/kkoci/acp/downloads", "issues_url": "https://api.github.com/repos/kkoci/acp/issues{/number}", "pulls_url": "https://api.github.com/repos/kkoci/acp/pulls{/number}", "milestones_url": "https://api.github.com/repos/kkoci/acp/milestones{/number}", "notifications_url": "https://api.github.com/repos/kkoci/acp/notifications{?since,all,participating}", …
- 
        Django search "DoesNotExist"I'm using Django to build a website for a football club, which contains many blog articles. I'm trying to include a search bar, but I can't make it work. When submitting the search term, the following error is shown: DoesNotExist at /web/search/ Articulo matching query does not exist. Here is my code: views.py def search(request): query = request.GET.get('q', '') if query: try: qset = ( Articulo(titulo__icontains=query) | Articulo(cuerpo_icontains=query) ) results = Articulo.objects.filter(qset).distinct() except Articulo.DoesNotExist: results = None else: results = [] return render_to_response('web/buscar.html',{"results": results, "query": query}) index.html <div id="busqueda" class="row"> <div class="col-md-12"> <span id="cruz" class="fas fa-times fa-2x"></span> <form method="GET" action="/web/search/" class="form my-2 my-lg-0"> <input id="searchBox" value="{{ query|escape }}" class="form-control mr-sm-2" type="text" name="q" placeholder="Buscar" aria-label="Buscar"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Buscar</button> </form> </div> </div> urls.py url(r'^search/$', search), models.py class Articulo(models.Model): """Un artículo de la página""" id = models.AutoField(primary_key=True) titulo = models.CharField(max_length=100) slug = models.SlugField(unique=True, default="") CATEGORIAS = ( ('Primera y Sub 21', 'Primera y Sub 21'), ('Inferiores', 'Inferiores'), ('Básquet', 'Básquet'), ('Hockey', 'Hockey'), ('Gurises', 'Gurises'), ('Generales', 'Generales'), ('Institucionales', 'Institucionales'), ('Senior', 'Senior'), ) categoria = models.CharField( max_length=200, choices=CATEGORIAS ) cuerpo = RichTextField() fecha_hora= models.DateTimeField() foto = models.ImageField() url_video = models.CharField(help_text='Url del video de facebook (opcional). Para obtener el link, ir al video, apretar …
- 
        Should i do db_index for charFields that I use in search?I have the following that i use in a search bar: Model1 subject = models.CharField(max_length =200) last_updated = models.DateTimeField(auto_now_add = True, null=True) created_at = models.DateTimeField(auto_now_add = True,db_index = True ) Model2 first_name = models.CharField(max_length = 20) last_name = models.CharField(max_length = 20) full_name = models.CharField(max_length=40, null=True, blank=True ) I use full_name and subject charfield in a seach bar. the search bar works by autocomplete, where the results are filtered everytime a character is added to the search. Will db_index=True for the charfields help for a quicker search? Thank you:)
- 
        Foreign key not returning child instance using django-polymorphicI just started using django-polymorphic and I'm having trouble returning the child instance of a parent model from a Foreign Key relationship. Here's an example: >>> poll = Poll.objects.create(asker=official, question='test question',background='background') >>> poll.asker <Official: Mayor Test Official> >>> poll.save() >>> poll = Poll.objects.get(question='test question') >>> poll.asker <Asker: Test Official> In this instance, the Official model is a child of Asker. All help is appreciated, thanks!
- 
        Django: Not working the translation of stringsim study the Django and faced with a problem translating strings. This code is send keyboard for the Telegram bot. In the code you will see SQL request, since the bot was writeed on clear python. Im need translate the keyboard text on "ru" or "en" (default) depending on what text the user sent. def bot_message(request): def settinngs(chat_id, message): con = lite.connect('db.sqlite3') cur = con.cursor() sql = "SELECT City, Lang FROM Userprofile WHERE Id={} ".format(chat_id) cur.execute(sql) result = cur.fetchall()[0] keyboard = types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True) button_change_city = types.KeyboardButton(text=_('Change name city')) button_subs = types.KeyboardButton(text=_('Subscriptions')) button_change_language = types.KeyboardButton(text=_('Change language')) backs_button = types.KeyboardButton(text=_('Back')) keyboard.add(button_change_city, button_subs, button_change_language, backs_button) bot.send_message(message.chat.id, '{}{}\n{}{}'.format(_('Your city: '), result[0].capitalize(), _('Language: '), result[1]), reply_markup=keyboard) I created translate in .po and compilemessages .mo file LANGUAGES = ( ('ru', 'Russian'), ('en', 'English'), ) USE_I18N = True LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) And set in MIDDLEWARE MIDDLEWARE = [ 'django.middleware.locale.LocaleMiddleware', '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', ] What am I doing wrong?
- 
        Django ImportError WindowsSo I created a virtualenv. I activated it (workon). Then I installed Django. py -3 -m django --version returns "No module named django." Then I try pip3 install django and it returns "Already satisfied." I created my project successfully using django-admin (meaning django IS installed?). Then I cd into the folder and run py -3 manage.py runserver and it says the following: "ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?"
- 
        Queryset distinct() with filter() and order_by() does not workI am using the following models and forms to build two dropdown menus. The City menu is dependent upon the Country menu. Right now my code does the filtering and ordering correctly. However, distinct() is not working. I've played around with the ordering of the queries for a while and it still doesn't work. How can I fix this? models.py from django.db import models class Country(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class Person(models.Model): country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name forms.py from django import forms from .models import Person, City class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('country', 'city') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['city'].queryset = City.objects.none() if 'country' in self.data: try: country_id = int(self.data.get('country')) self.fields['city'].queryset = City.objects.filter(country_id=\ country_id).order_by('city').distinct('city').\ exclude(city__isnull=True) except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['city'].queryset = self.instance.country.city_set.order_by('name')
- 
        Execute linux command within Django viewsI would like to execute a linux curl command through python. I went through multiple links but my problem is that it keeps saying file name too long. Is there a way to tackle this error? I use subprocess call to go about it.
- 
        Django object retrieval not workingFor some reason UserProfile.objects.all() isn't retrieving the models I have to serialize them as json. Any ideas? views.py def get_modelAPI(request): UserProfile_json = serializers.serialize("json", UserProfile.objects.all()) data = {"UserProfile_json": UserProfile_json} return JsonResponse(data) urls.py url(r'^details/json/$', views.get_modelAPI, name='json'), models.py class UserProfile(models.Model): fullName = models.CharField(max_length = 250) address = models.CharField(max_length = 250) gender = models.CharField(max_length = 250) dob = models.CharField(max_length = 250) homePhone = models.CharField(max_length = 250) personalPhone = models.CharField(max_length = 250) emergencyContact = models.CharField(max_length = 250) email = models.CharField(max_length = 250) ppsn = models.CharField(max_length = 250) maritalStatus = models.CharField(max_length = 250) employment = models.CharField(max_length = 250) personalPic = models.CharField(max_length = 1000) I am simply attempting to view this model in json format for now later to be parsed. Output
- 
        Restrict access to Geoserver except for javascriptI have Django web application that request wms and wfs from geoserver using javascript(leaflet). When user click on leaflet map a request sent to web server(apache2.4) and apache will redirct the request to tomcat 8.5 using proxy. Everything is working perfect. I want to Restrict access to Geoserver except for javascript from https://app.mydomain.com Geoserver exsist in deffrent server and we use this url to access it geoserver.mydomain.com. I used HTTP_REFERER with apache: RewriteEngine on # Options +FollowSymlinks RewriteCond %{HTTP_REFERER} "app.mydynamo.com" [NC] RewriteRule .* - [F] Can you help me to Restrict access to Geoserver except for javascript from https://app.mydomain.com
- 
        Why Django doesnt have Error Page Handler for 405 - Method Not Allowed?When i read Django documentation i found only handlers for: 400, 403, 404, 500 errors. Why 405 error handler doesn't exists but decorators like require_POST() is in common use? The point is, what is proper way to create custom error page for Method Not Allowed error ?
- 
        Django Serializer lookup value from id of another modelI'm using Vue as my frontend and Django DRF as my backend. I created 2 models - Snippet and age. I'm trying to return the value from the lookup table instead of the id: POST on Snippet List by passing in {title: 'x', code: 'y', age: 21} instead of passing the age id PUT on Snippet instance by passing in {age: 21} instead of passing the age id to update the record GET on Snippet List get return results with {other_fields, age: 21}. Is it possible to modify the serializer to do these? I'm using axios to call GET/POST/PUT on the REST endpoints. Snippet data as viewed in the API **Snippet List** { "id": 1, "title": "hello", "code": "print", "age": 2 }, { "id": 2, "title": "dsd", "code": "sds", "age": 1 } **Age List** { "id": 1, "year": "21", "snippets": [ 2 ] }, { "id": 2, "year": "30", "snippets": [ 1 ] } models.py class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() age = models.ForeignKey('age', related_name='snippets', on_delete=models.CASCADE, null=True) class age(models.Model): year = models.CharField(max_length=100) serializers.py class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields = ('id', 'title', 'code', 'age') age = serializers.ReadOnlyField(source='age.year') class ageSerializer(serializers.ModelSerializer): snippets = …
- 
        Need django website to work on a local windows network through WAMPI’ve got a python and django app built and I am able to go to http://127.0.0.1:8000/pos/index/ and it works on computer1 within a virtual environment. Now I am trying to make it work on another computer (computer2) in the network. So I installed WAMP on computer1 and am trying to configure apache to host the django. Details: Computer1: has Windows10, WAMP 3.1.1 with Apache 2.4.27 and mySQL 5.7.19, python 3.6.4 with virtualenv==15.1.0 and within the virtual environment is Django==2.0.3, mod-wsgi==4.5.24+ap24vc14, mysqlclient==1.3.12, and pytz==2018.3 Computer2: windows10 Apache currently has the following configuration: httpd.conf file: Listen 0.0.0.0:80 Listen [::0]:80 Listen 0.0.0.0:8000 Listen [::0]:8000 LoadModule wsgi_module "c:/myproject/north/env/lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win_amd64.pyd" WSGIScriptAlias / "C:/myproject/north/north_system/north_system/wsgi.py" WSGIPythonHome "c:/python36" WSGIPythonPath "C:/myproject/north/north_system/pos" Alias /static/ C:/myproject/north/north_system/pos/static/ <Directory "C:/myproject/north/north_system/pos/static"> Require all granted </Directory> <Directory "C:/myproject/north/north_system/pos"> <Files wsgi.py> Require all granted </Files> </Directory> httpd-vhosts.conf file: <VirtualHost *:80> ServerName localhost ServerAlias localhost DocumentRoot C:/myproject/north/north_system/pos <Directory "C:/myproject/north/north_system/pos/"> Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require all granted </Directory> </VirtualHost> <VirtualHost *:8000> ServerName north.local DocumentRoot C:/myproject/north/north_system/pos <Directory "C:/myproject/north/north_system/pos/"> Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require all granted </Directory> </VirtualHost>
- 
        How do I only accept uploaded images with a 1:1 (square) aspect ratio and throw an error otherwise?The admin is able to upload an image but I would like to restrict it to only being a square image. Here is my models.py file: class Author(models.Model): author_name = models.CharField(max_length=200) author_image = models.ImageField(upload_to=upload_location, null=True, blank=True,) author_bio = models.TextField() def __str__(self): return self.author_name
- 
        NoReverseMatch at /posts/Just quick info I'm a beginner in python and django. Here is an issue: I'm trying to create simple blog app with django, I've created all whats needed and I'm able to render one of my main pages however when I try to access posts page(to be able to view current posts) I receive the following error: Request Method: GET Request URL: http://localhost:8000/posts/ Django Version: 2.0.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'post' not found. 'post' is not a valid view function or pattern name. I'm not sure why I receive this error as I have posts view function written and accessible, here are my files: my_blog/urls.py """Defines URL patterns for my_blog.""" from django.conf.urls import url from . import views #needed app name app_name='my_blog' urlpatterns=[ #Homepage url(r'^$',views.home,name='home'), # Show all posts. url(r'^posts/$', views.posts, name='posts'), models.py from django.db import models # Create your models here. class BlogPost(models.Model): """Post that can be viewed""" title=models.CharField(max_length=200) text=models.TextField() date_added=models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" if len(self.text)<50: return self.text else: return self.text[:50] + "..." views.py from django.shortcuts import render from .models import BlogPost from django.http import HttpResponseRedirect # Create your views here. def home(request): """The home page for Learning Log""" return …
- 
        Debugging is not supported for python 2.5 or earlier?I keep getting this error in visual studios. There are currently no documentation that I can find that solves this error. Im using Pythong 3.7. Also, I get this same error when I try to debug a Django web application as well as a just regular python web application. I have also tested with Google Chrome, Internet Explorer, and Firefox, all of which give me the same error. The configuration is set up for 3.7
- 
        Django/Postgres: Returning error: duplicate key value violates unique constraintI have had this issue occur several times with a project I've been working on, and though I used the "python manage.py sqlsequencereset " fix that I've found on this site, it works for a while, and then begins throwing the error again. The error I keep getting is pretty straightforward: IntegrityError at /projects/v/portola/planting-sites/new/ duplicate key value violates unique constraint "urbanforest_plantingsite_pkey" DETAIL: Key (id)=(194016) already exists. In my view I have: form = PlantingSiteForm(request.POST) if form.is_valid(): f = form.save(commit=False) if PlantingSite.objects.all().exists(): last_planting_site = PlantingSite.objects.all().order_by('-created_at')[0] f.id_planting_site = last_planting_site.id_planting_site f.id_planting_site += 1 else: f.id_planting_site = 100000 if request.POST.get('neighborhood_id'): f.neighborhood = Neighborhood.objects.filter(id_neighborhood=request.POST.get('neighborhood_id'))[0] if request.POST.get('district_id'): f.district = District.objects.filter(id_district=request.POST.get('district_id'))[0] if request.POST.get('basin_type_id'): f.basin_type = BasinType.objects.filter(id_basin_type=request.POST.get('basin_type_id'))[0] if request.POST.get('aspect_id'): f.aspect = Aspect.objects.filter(id_aspect=request.POST.get('aspect_id'))[0] if request.POST.get('orientation_id'): f.orientation = Orientation.objects.filter(id_orientation=request.POST.get('orientation_id'))[0] if request.POST.get('hardscape_damage_id'): f.hardscape_damage = HardscapeDamage.objects.filter(id_hardscape_damage=request.POST.get('hardscape_damage_id'))[0] if request.POST.get('status_id'): f.status = PlantingSiteStatus.objects.filter(id_planting_site_status=request.POST.get('status_id'))[0] else: f.status = PlantingSiteStatus.objects.filter(id_planting_site_status=9)[0] if f.zipcode: f.property_zipcode = f.zipcode f.created_by_fuf = True f.created_by = request.user f.save() I've done the sqlsequencereset a couple of times now, and then the error returns after a couple of weeks. I'm not importing any data, but my coworkers are using their phone in the field to create new objects, one at a time. Running sqlsequencereset gets me this code: SELECT setval(pg_get_serial_sequence('"urbanforest_plantingsite"','id'), coalesce(max("id"), 1), max("id") IS NOT …
- 
        How to map JSON keys with non-alphanumeric characters in Django Rest Framework SerializerI have some JSON keys that contain non-alphanumeric characters e.g. "my-key=" I need to map this key to a field my_key in my Django model. The traditional way to do this is to add a custom field to the ModelSerializer where you specify the source: class MyModelSerializer(serializers.ModelSerializer): my_key= = serializers.CharField(source='my_key') class Meta: model = MyModel fields = ('my-key=',) However this obviously doesn't work because: my_key= = serializers.CharField(source='my_key') is not valid python for declaring an attribute. How do I map my JSON key to the model field?