Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not read only not model field in ModelSerializer
How can I add not-read-only not model field to ModelSerializer? For example, note = serializers.CharField() (this value will be used for ItemHistory model) models.py class Item(models.Model): name = models.CharField(...) quantity = models.IntegerField() serializers.py class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ['name', 'quantity'] -
Install MySQL Client in Django Show Error
Hi I am trying to install Mysqlclient in Django and I got this message collecting mysqlclient Using cached https://files.pythonhosted.org/packages/f4/f1/3bb6f64ca7a429729413e6556b7ba5976df06019a5245a43d36032f1061e/mysqlclient-1.4.2.post1.tar.gz Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Complete output from command 'c:\users\usermo~1\virtua~1\tmsv2_~2\scripts\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\userMO~1\\AppData\\Local\\Temp\\pip-install-vzfx29bg\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\userMO~1\AppData\Local\Temp\pip-wheel-rd_6y67h' --python-tag cp37: ERROR: running bdist_wheel running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension creating build\temp.win32-3.7 creating build\temp.win32-3.7\Release creating build\temp.win32-3.7\Release\MySQLdb C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.16.27023\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,4,2,'post',1) -D__version__=1.4.2.post1 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include\mariadb" "-Ic:\users\user moe\appdata\local\programs\python\python37-32\include" "-Ic:\users\user moe\appdata\local\programs\python\python37-32\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\14.16.27023\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\cppwinrt" /TcMySQLdb/_mysql.c /Fobuild\temp.win32-3.7\Release\MySQLdb/_mysql.obj /Zl /D_CRT_SECURE_NO_WARNINGS _mysql.c MySQLdb/_mysql.c(29): fatal error C1083: Cannot open include … -
How to filter an ordered dictionary in Python using Django?
Actully I am new to Python.Working with Python,Django and Mysql. I was trying to filter some data from an ordered dictionary which i received while fetching data from mySQL database.The entire data is there in a variable. But I want to store some of it in another variable... This is my view.py file... all_dataobj=fetchdata.objects.all() pserializer=fetchdataSerializers(all_dataobj,many=True) p = pserializer.data print(p) And I am getting data like this... [OrderedDict([('id', 1), ('first_name', 'raunak'), ('middle_name', 'yy'), ('last_name', 'ron')]), OrderedDict([('id', 2), ('first_name', 'josh'), ('middle_name', 'yy'), ('last_name', 'mod')]), OrderedDict([('id', 3), ('first_name', 'david'), ('middle_name', 'yy'), ('last_name', 'cop')]), OrderedDict([('id', 4), ('first_name', 'bob'), ('middle_name', 'zj'), ('last_name', 'go')])] Now I want to filtre this ordered dictionary and store data of id 1 and 2 only in a variable. So, if I print the result variable it should look like this... [OrderedDict([('id', 1), ('first_name', 'raunak'), ('middle_name', 'yy'), ('last_name', 'ron')]), OrderedDict([('id', 2), ('first_name', 'josh'), ('middle_name', 'yy'), ('last_name', 'mod')])] Please help me...i am stuck for very long...How can I get so?? -
Redirecting public url fails on django - SignatureDoesNotMatch
Im trying to download a file from s3 to a client throught django. In order to do this Ive generate a public url from the s3 object required and the Im trying to redirect the user to that url, so the file is downloaded to his/her computer. The code is the following def generate_public_url(self, bucket, file) url = '' filename = file client = boto3.client( 's3', ) url = client.generate_presigned_url( ClientMethod ='get_object', ExpiresIn = 7200, Params = { 'Bucket': bucket, 'Key': file, } ) return url The code that redirects the url: from .django.http import HttpResponseRedirect . . . http_response_redirect = HttpResponseRedirect(url) return http_response_redirect And the response from aws is 403 with the following error: Code: SignatureDoesNotMatch Message: The request signature we calculated does not match the signature you provided. Check your key and signing method. After doing some research for a few days and trying a lot of things, Im sure this is a problem with django, and after reading some post in github people says that if the headers include something different compare to the ones used to generate the public url it can generate this error. So something in the django way of making the request must … -
Django - How to filter by annotated value
Consider the following model. I'd like to filter objects based on the latest timestamp, which might be either created_at or updated_at. For some reason, the filter function does not recognise the annotated field and I'm having hard time finding the appropriate code examples to do this simple thing. The error message is "Cannot resolve keyword 'timestamp' into field.". How would you retrieve the Example objects within 7 days, based on newer date. from datetime import timedelta from django.db import models from django.db.models.functions import Greatest from django.utils import timezone class Example(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(null=True) @property def recently_updated(self): return Event.objects .annotate(timestamp=Greatest('created_at', 'updated_at')) .filter(timestamp__gte=timezone.now() - timedelta(days=7)) .order_by('-timestamp') Django 1.11 -
static files in django framework that holds css and javascript they cant display in the web browser
I already have an index file in a template folder that hold the html code,Also i have css and javascript file in the static folder so when i load the browser i only see the index content without css and javascript in setting.py file i set clearly the path to the static files that hold css and javascript also in index file we put special tags that specify our static files The following is the setting.py contents: STATIC_URL = '/static/' STARTICFILES_DIRS=[ os.path.join(BASE_DIR,'static'), ] STATIC_ROOT= os.path.join(BASE_DIR,'assets') The following is the index file contents: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>Travello</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href=" {%static'styles/bootstrap4/bootstrap.min.css' %}"> I expect the output of css style and javascipt functionality -
How to create superuser for django in docker programatically withput using the manage.py createsuperuser commad?
I am a newbie to django. I have my django app running in docker, I need to create a superuser without using the createsuperuser command I tried using this code initadmin.py (shown below) but I am not able to run it in a bash file using "python manage.py initadmin". It is not working! initadmin.py from django.contrib.auth.models import User from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): if User.objects.count() == 0: for user in settings.ADMINS: username = 'admin' email = 'admin.com' password = 'admin' print('Creating account for %s (%s)' % (username, email)) admin = User.objects.create_superuser(email=email, username=username, password=password) admin.is_active = True admin.is_admin = True admin.save() else: print('Admin accounts can only be initialized if no Accounts exist') Can anyone tell me what am I doing wrong? Any better way to create superuser programmatically ? -
MSSQL uses db_owner prefix in selects on client's database
My Django app is normally working on SQLite3, but this time I had to convert it to use MSSQL. On test server everything went well, but when my friend copied this database to client's server I had an error: (norm)esd@server:~/Desktop/norm/myproject> python manage.py runserver Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function wrapper at 0x7fc57eb4f8c0> Traceback (most recent call last): File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check_migrations() File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/core/management/commands/runserver.py", line 163, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/migrations/loader.py", line 176, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/migrations/recorder.py", line 66, in applied_migrations return set(tuple(x) for x in self.migration_qs.values_list("app", "name")) File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/models/query.py", line 258, in __iter__ self._fetch_all() File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/models/query.py", line 1074, in _fetch_all self._result_cache = list(self.iterator()) File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/models/query.py", line 128, in __iter__ for row in compiler.results_iter(): File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/models/sql/compiler.py", line 802, in results_iter results = self.execute_sql(MULTI) File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/models/sql/compiler.py", line 848, in execute_sql cursor.execute(sql, params) File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/esd/Desktop/norm/lib64/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) … -
Auto Delete user entered data after window close or user logout
I have an, where the user enters data and it is saved in the db through Djnago forms. But I don't want to save this user entered data forever, only until the user is logged in. As soon as the user logs out or closes his browser I want Djnago to delete all that user entered data. Please look at the code and tell me how can I achieve this. views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import * from django.contrib.admin.views.decorators import staff_member_required from .forms import * from django.shortcuts import * from .models import * from django.contrib.auth.forms import * from django.contrib.auth import * from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.views.generic import CreateView from django.views import generic from .models import * def reg_user(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') return redirect('LoginPage') else: form = UserCreationForm() return render(request, 'userfiles/reg.html', {'form': form}) Also there is an issue here. Whenever I use the following decorator I get this error File "C:\Users\Bitswits 3\Desktop\Maala\MaalaWeddings\userfiles\urls.py", line 22, in <module> url(r'^invite/$', InviteCreate.as_view(), name='Invite-Page'),le "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-package AttributeError: 'function' object has no attribute 'as_view' # @login_required(login_url='LoginPage') class InviteCreate(CreateView): form_class = InviteForm model = … -
Uploading all image files from a folder into Django Template [duplicate]
This question already has an answer here: displaying all images from directory Django 2 answers I have a pdf that I am converting into individual png files in a specific folder in my app folder. The purpose is to display all the files in the folder on the template with a caption no matter what is the number of image files in the folder? Another question I have here is does it have to be inside the static folder to display the image files, can I give the path from which I want django to display the image files. Thanks. -
I need to change the value of a field and redirect to a url on button click. How am I supposed to do it?
I am working on a problem where I need to change the value of a model field "verified" on button click and redirect it to mail url so the the verified users get mail. I am not familiar with ajax. Please help me out in doing this. models.py: class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True) role = models.CharField(max_length=50, choices=Roles, default='client') verified =models.BooleanField(default = False,blank=True) template: <td> < a class="btn btn-primary"><i class="feather icon-edit mr-1">Verify</i></a> <a class="btn btn-primary"><i class="feather icon-trash-2">Delete</a> </td> -
Django filtering: from a list of IDs
I'm using Django Rest Framework. The model class is class MyModel(models.Model): id = models.CharField(max_length=200) name = models.CharField(max_length=200) genre = models.CharField(max_length=200) And what I have set up so far is that, when the user does a POST request, the backend will take the request data and run a python script (which takes some parameters from the request data) which will in turn return a list of IDs corresponding to the "id" in MyModel. But the problem is, let's say I want to return only the ids that point to the model instances with genre "forensic", how do I do that? I don't really have a clue how to do that, apart from doing a query on each id returned by the python script and filtering out the ones I want based on the genre returned from the query? -
How to enable HTTP access for Django APIs on HTTPS server
I have a website running on a server that redirects all HTTP requests to HTTPS as shown below. I also have a few Django APIs that the server serves (let's say https://www.example.com/apis/log). I am running the Django implementation on Ubuntu + Nginx and have installed SSL certificate using Let's Encrypt. server { if ($host = www.example.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = example.com) { return 301 https://$host$request_uri; } # managed by Certbot server_name xxx.xx.xx.xx example.com www.example.com; listen 80; return 404; # managed by Certbot } Now, I would like to do the following: Run the website in the present settings (all HTTP requests should redirect to HTTPS) Django APIs should work with both HTTP and HTTPS. Hence, I would like to have both http://www.example.com/apis/log and https://www.example.com/apis/log accessible. -
how to get the SimpleListFilter lookups list in template in django
I am new in Django. I want to get the SimpleListFilter lookups list in my custom template. I want to show the list, like a dropdown menu. But i don't know how to get the loopups list in my custom template. Could anyone help me. class PollDataListFilter(SimpleListFilter): template = 'admin/input_filter.html' title = 'Author Name' parameter_name = 'author_name' def lookups(self, request, model_admin): return (('1', 'True'), ('0', 'False')) From the above code i want to get the lookups method's return list to populate my custom template. Is it possible to get that list in django? -
Use django multiple settings config, is that OK or fine? I mean recommended way
I want django settings like spring boot *.yml settings way to develop, default settings could set, and active settings could overwrite default settings. I trid many ways, finally find this way blow, I want get some recommendations or advices. refer to Django multiple settings I create project.settings module and add multiple settings file, and change the manage.py like: import os import sys from mysite.settings import settings if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', settings.ACTIVE_SETTINGS) In default settings.py file add ACTIVE_SETTINGS for manage.py to import. default setting file mysite/settings/settings.py like: import datetime import os ACTIVE_SETTINGS = 'mysite.settings.dev_settings' more default settings..... In develop dev_settings.py file set default settings refer to #custom-default-settings in mysite/settings/dev_settings.py like: from django.conf import settings from mysite.settings import settings as default # use this could set default settings to active setting settings.configure(default, DEBUG=True) more dev settings..... Setting django in this way could realize only change one setting ACTIVE_SETTINGS to develop and default settings could also set if ACTIVE_SETTINGS file not set, I've read many blogs, no other way could better than this. -
TextField onchange feature with Django CMS Wizard, Form and App Config
I am developing a website using django CMS. In their built-in app config for Pages (for example), they have a field wherein we can input a slug for the page we create. By default, while you type the page title, the slug textfield also types in a value automatically in a slug format, like below: I want to learn how to do this in my custom app configs as well as on my CMS wizards. Reason being, we will have non-technical staff who will later be given permission to add events and news. Adding events and news requires providing a slug which will be used later for URL routing. Since they are non-technical personnel, it is not ideal for them to provide the slug manually i.e. they might forget to add a hyphen or misspell some words. Thus, it would be safer to just automatically fill the slug field with default value as you type the page title. If anyone can share a piece of code or share the concept on how to do this as simple and straightforward as possible it would greatly help. Cheers! -
MySQL row-column-value format to python dictionary
I am relatively new to Python (and Django) and have some data in a MySQL database in a row-column-value format Django Model "UserParameters": user_id | param | value ----------------------------------- 123 | param_1 | xxx 123 | param_2 | yyy 123 | param_3 | zzz 123 | param_4 | aaa 123 | param_5 | bbb 123 | param_6 | xxx ... ... 456 | param_1 | sse 456 | param_2 | aca 456 | param_3 | cce 456 | param_4 | dwe 456 | param_5 | cck 456 | param_6 | aq1 ... ... 789 | param_1 | zzz ... I'm trying to get this data in MySQL into a dictionary in the following format: users = { 123: {'param_1': 'xxx', 'param_2': 'yyy', 'param_3': 'zzz', 'param_4': 'aaa', 'param_5': 'bbb', 'param_6': 'xxx'}, 456: {'param_1': 'sse', 'param_2': 'aca', 'param_3': 'cce', 'param_4': 'dwe', 'param_5': 'cck', 'param_6': 'aq1'}, 789: {'param_1': 'zzz', ..... } So far, I've tried users = {} users_params = UserParameters.objects.all().values() for u in users_params: users[u['user_id']].add(u['param'], u['value']) This gives me a key error. Any idea what I could be doing wrong? Thank you! -
Wagtail PASSWORD_REQUIRED_TEMPLATE is not overriding the default login
I'm building a global login page for Wagtail. The setting for PASSWORD_REQUIRED_TEMPLATE isn't working. In fact, i can't find n example where it actually does work which makes me think that I don't understand what it's supposed to do. When I add; PASSWORD_REQUIRED_TEMPLATE = 'utils/auth/password-required.html' to the settings file it does not catch the login form and use my custom form. Is this a know issue? -
How to remove Ck editor tag in django rest framework
I am using Django rest framework. The CkEditor tags I've used for the web appear in the API part. How do I remove these tags from the API I had not used Ckeditor before, I was using the Django TextField field models.py ''' class Lesson(models.Model): ... lesson_content = RichTextField( verbose_name=_('Ders İçeriği'), blank=True ) ... ''' seriaizer.py ''' class LessonSerializer(serializers.ModelSerializer): class Meta: model = Lesson fields = (...,'lesson_content',...) ''' output(Json Data) {"id":1,"user":2,"lesson_name":"Microprocessors","lesson_content":"Merkezi işlem birimi (CPU) : CPU kaydedicileri , Aritmetik ve lojik birim, Durum bayrakları, Mikroemirlerin icrası, Mikroprogramlama ve kontrol birimi , CPU bacakları. Bellekler: ROM, RAM, PROM, EPROM ve E2PROM bellekler. Kod çözücüler ve belleklerin CPU'ya bağlanışı. Paralel Giriş/Çıkış : Programlı G/Ç, kesmeli G/Ç, Doğrudan bellek erişimli G/Ç. Seri Giriş/Çıkış. Mikrobilgisayarların programlanması: Kaynak ve amaç programlar. Assembly dili ve assembler direktifleri. Bellek adresleme yöntemleri. CPU emir takımı. Gerçek CPU'lar. Mikrobilgisayar sistem tasarımı. Uygulamalar. .","lesson_content_file":"http://192.168.2.7:8000/media/user%20ulutas%40ktu.edu.tr/microprocess.pdf","lesson_notes":" \r\n\r\nYazıcı, R., 1998, Mikrobilgisayar Donanım ve Yazılımı, KTÜ Yayınları, Trabzon, 345 s.\r\n\r\nBrey, B., B., 1984, Microprocessor/Hardware Interfacing and Applications, Merrill, 414 p.\r\n\r\nLeventhal, L., A., 1979, Z80 Assebly Language Programming, Osborne/McGraw-Hill, 612 p.\r\n\r\nUffenbeck, J., 1985, Microcomputers and Microprocessors: The 8080, 8085, and Z80 Programming, Interfacing, and Troubleshooting, Prentice-Hall, 670 p.\r\n\r\n ","lesson_notes_file":"http://192.168.2.7:8000/media/user%20ulutas%40ktu.edu.tr/microprocess_qUAazMf.pdf"} & nbsp; \ r \ n \ r … -
How to pass variable as ARG or KWARG in my get_success_url
I have been working all afternoon to try and pass a variable to a get_success_url to show the correct record after I process an UpdateView. I am using class based views, and I am trying to update a record and then show the corresponding update record in a different view. However, when I am passing the pk, it works but it's not the right one. Essentially, here is the code in question... def get_success_url(self): return reverse_lazy('Book:create_new_author_detail', kwargs={ 'pk' : self.object.pk }) The above would work fine and does in many scenarios. However, in this case, I am trying to pass a specific pk that does not align with this particular updateview. I have tried something like.... def get_success_url(self): return reverse_lazy('Book:create_new_author_detail', kwargs={ 'pk' : self.object.new_author.pk }) Perhaps something like.... def get_success_url(self): return reverse_lazy('Book:create_new_author_detail', kwargs={ 'pk' : self.object.pk, 'new_author' : self.new_author.id }) Would work? I can get the pk using this code, just not the right one. I want to reference new_author.id so that the reverse_lazy picks the right pk. Thanks in advance for any thoughts. -
How to fix 'NoReverseMatch at /' error on Django app?
I'm new to Django and I'm trying to just build a basic application to work off in the future. I keep getting an error saying "NoReverseMatch at/ Reverse for 'about' not found. 'about' is not a valid view function or pattern name." I've searched for other people with the same issue and it seems their issues used an older version of Django and they used different functions from what I'm using. I'm using a book called Hello Web App by Tracy Osborn, which simplifies everything, and all the code I've found dealing with a similar problem seems far more complicated than what I've done so far. I've tried changing my views.py file to request the base.html file instead of the index.html file which didn't work. I've double checked my syntax on all files, including the html file. And, I've made sure the urls.py file matched up exactly. I still keep getting the same error. here is my urls.py file from django.contrib import admin from django.urls import path from django.views.generic import TemplateView from condata import views urlpatterns = [ path('', views.index, name='home'), path('about/', TemplateView.as_view(template_name='about.html'), name='about'), path('contact/', TemplateView.as_view(template_name='contact.html'), name='contact'), path('admin/', admin.site.urls), ] views.py from django.shortcuts import render # Create your views here. … -
App crashed , deployment Heroku error in Django
I'm deploying my first Django app on Heroku and i get this error: 2019-06-17T22:02:04.615398+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=carlosdelgado1.herokuapp.com request_id=210a779e-59ba-46c3-af78-e60215244798 fwd="24.55.161.197" dyno= connect= service= status=503 bytes= protocol=https 2019-06-17T22:34:14.393752+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=carlosdelgado1.herokuapp.com request_id=cc7678e9-c3ec-4b97-9a34-383b6f6f0a4e fwd="24.55.161.197" dyno= connect= service= status=503 bytes= protocol=https this is whats in my Procfile: web: gunicorn porfolio.wsgi i did these import in the wsgi.py file: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kloudless.settings") from django.core.wsgi import get_wsgi_application from dj_static import Cling application = Cling(get_wsgi_application()) here is the github link to the blog project: https://github.com/Poucarlos/portfolio I'm trying to display my blog in Heroku to see it when I access it -
Error in production No module named 'django.db.migrations.migration'
recently I pulled from my git the new version of the project, unfortunately I made a mistake and my settings.py file was completly overwrite. I fix it but when I run my apache server and tried to make a request in the logs I found this: [Mon Jun 17 17:31:02.934215 2019] [wsgi:error] [pid 29830] [remote 200.116.66.129:52114] from .migration import Migration, swappable_dependency # NOQA<br/> [Mon Jun 17 17:31:02.934240 2019] [wsgi:error] [pid 29830] [remote 200.116.66.129:52114] ModuleNotFoundError: No module named 'django.db.migrations.migration' I looked in this other question: Updating Django - error: 'No module named migration' and tried every posibility unsuccessfully. What else should I do to fix this? -
How to create checkboxes with the values of model instances created by users
I want to create forms with checkboxes in them which values of these checkboxes is a model instance created by users. Here is my SessionModel: class SessionModel(models.Model): starting_time = models.TimeField() . . Imagine that I have several instances of this model with various starting_times. and I have another model which is: class TimeModel(models.Model): time = models.TimeField() now i want to select the required instances of SessionModel and update them. But the problem is that I want to have a form with checkboxes with the values of TimeModel.time to grab the instances in SessionModel with the starting_time same as selected TimeModel.time but I don't know how to create these checkboxes should I use dynamic forms or is there any other way I can do this? -
How do I add information from javascript variables to Django ModelForm input?
I am building a web application using Django. The page shows a large leaflet map, in which users can select one out of several layers. I want users to be able to select a layer, click on the map and add a note to that location and that layer. I've created a model form, which holds the note itself. This works fine, and saves to my database. However, I need to also include the currently selected layer and mouse-click-location, which is readily available as a JS variable. How do I pass this on in Django? My views.py holds the following: if request.method == 'POST': form = MapNoteForm(request.POST) if form.is_valid(): form.save() else: form = MapNoteForm() And forms.py: class MapNoteForm(forms.ModelForm): note = forms.CharField() class Meta: model = MapNote fields = ('note',) Finally, the relevant section of the template: map.on('click', function (e) { var MapNote = L.popup(); var content = '<form method="post"> {% csrf_token %} {{form}} <br> <button type="submit"> Save</button>' MapNote.setContent(content); MapNote.setLatLng(e.latlng); //calculated based on the e.layertype MapNote.openOn(map); }) I'm kind of looking to reverse the workings of the Django-view, trying to pass something from the template to Django, instead of vice versa. What would be the best approach here?