Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Internal Server Error, when DEBUG = False
I have this relatively famous problem but I just can´t found the solution, when my DEBUG = True everything works fine and then I set it to False and it just doesn't work... And I set also the 'ADMINS = [('my_app', 'my_app@gmail.com')]' and I don't receive any email whit the error instructions. I hope someone can show the light, thanks! """ Django settings for my_app_web project. Generated by 'django-admin startproject' using Django 2.2.7. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('my_app_web_django_secret_key') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False DEBUG_PROPAGATE_EXCEPTIONS = True ALLOWED_HOSTS = ["my_app.herokuapp.com"] SERVER_EMAIL = 'my_app@gmail.com' ADMINS = [('my_app', 'my_app@gmail.com')] CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True # Application definition INSTALLED_APPS = [ 'clients.apps.ClientsConfig', 'home.apps.HomeConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'my_app_web.urls' TEMPLATES … -
Django: Problem with Adding Editing and Deleting Functionality in Django Form
I am learning Django by building an application, called TravelBuddies. It will allow travelers to plan their trip and keep associated travel items (such as bookings, tickets, copy of passport, insurance information, etc), as well as create alerts for daily activities. The application will also able to update local information such as weather or daily news to the traveler. Travelers can also share the travel information with someone or have someone to collaborate with them to plan for the trip. I have created a form that enables the users to add their trip information, like trip name, planner name, co-planner, date etc. However, I can't find a proper way of allowing them to edit and delete the forms. I have seen some videos. But they are not using TemplateView like me. So, I am a bit confused. Here are my codes in forms.py file under addtrip folder: from django import forms from django.contrib.auth.models import User from django.forms import ModelForm from trips.models import Trip class TripForm(ModelForm): class Meta: model = Trip fields = ['trip_name', 'date', 'planner_name', 'add_coplanner', 'trip_description'] class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password'] Here are my codes in views.py file under … -
Python 3 Django 3.0 Running but not listening or opening port
I am using PyCharm and an instance running in AWS for remote debugging. When I start debugging the server starts and continues to run. However, it is inaccessable and doesn't appear to be grabbing the port. Running with sudo doesn't change anything. When running the app using gunicorn it works perfectly. Pycharm Console ssh://ubuntu@34.204.XXX.X:22/usr/bin/python3 -u /home/ubuntu/.pycharm_helpers/pydev/pydevd.py --multiproc --qt-support=auto --client 0.0.0.0 --port 46691 --file /opt/ctp/cloudportal/manage.py runserver 0.0.0.0:8000 pydev debugger: process 3021 is connecting Connected to pydev debugger (build 193.5233.109) [2019-12-14 03:51:18] 3028 INFO django.utils.autoreload:run_with_reloader:598 - Watching for file changes with StatReloader Performing system checks... /usr/lib/python3/dist-packages/Crypto/Random/Fortuna/FortunaGenerator.py:28: SyntaxWarning: "is" with a literal. Did you mean "=="? if sys.version_info[0] is 2 and sys.version_info[1] is 1: /usr/lib/python3/dist-packages/Crypto/Random/Fortuna/FortunaGenerator.py:28: SyntaxWarning: "is" with a literal. Did you mean "=="? if sys.version_info[0] is 2 and sys.version_info[1] is 1: System check identified no issues (0 silenced). December 14, 2019 - 03:51:19 Django version 3.0, using settings 'CloudPortal.settings_dev' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. Linux Server ubuntu@ip-192-168-128-120:~$ sudo ps -alf F S UID PID PPID C PRI NI ADDR SZ WCHAN STIME TTY TIME CMD 0 S ubuntu 3028 3021 3 80 0 - 72808 poll_s 03:51 pts/0 00:00:09 /usr/bin/python3 /opt/ctp/cloudportal/manage.py runserver 0.0.0.0:8000 4 S root 3139 … -
Hitting 500 error on django with debug=False even with ALLOWED_HOSTS=["*"]
I am getting 500 errors on every page I try to go with. The only thing that i'm changing is DEBUG to False. Here is my config: SECRET_KEY = os.environ.get("SECRET_KEY", "0$ke!x1bz5cj0mpzo1zfx4omw-c9iqw%m95zb)(2@ddg5s+3!f") ALLOWED_HOSTS = ['*'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # Application definition INSTALLED_APPS = [ 'posts', # Contains all dynamic and static pages related to posts 'courses', # Contains all dynamic and static pages related to courses and modules 'pages', # Contains all static pages that are not post related 'markdownx', # Allows for editing and creating markdown content 'jet.dashboard', 'jet', # Django admin theme override 'pwa', # Sets app to be PWA compliant 'whitenoise.runserver_nostatic', # Serving static files 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Literally every answer i've seen says just set your ALLOWED_HOSTS to ['*'], as you can see i've done that and still no dice. I checked the Docs and they are pretty sparse on what else DEBUG mode effects there is a section of the docs that says: As a security measure, Django will not include settings that might be sensitive, such as SECRET_KEY. Specifically, it will exclude any setting whose name includes any of the … -
django, update modified_at when doing update()
Following field gets updated whenever model_obj.save() happens. modified_at = models.DateTimeField(auto_now=True, db_index=True) However, it is not updated when doing MyModel.objects.filter(id=model_obj.id).update(**kwargs) Is there a way to somehow enforce updating modified_at? -
Is Django REST framework suppose to be public?
I recently found some security holes in my university website. Among other issues was that, a page for viewing and managing api requests, using Django REST framework was found to be public. There were option to generate manage oauth tokens, and different things like that. I am planning to report the issues together soon. Is this actually a bug or is it suppose to be public? If it is a bug, what are the possible consequences? Is it to be taken seriously? -
django post api through postman
**Hi when I try to hit the post api from postman I am receiving the response from API but the request is not received from postman when I print the request it showing but not the data and i attached the screenshot of postman ** from django.shortcuts import render from django.http import HttpResponse from django.core.mail import send_mail from django.views.decorators.csrf import csrf_exempt # Create your views here. @csrf_exempt def email(request): print(request) subject = request.POST.get('subject', 'hello') body = request.POST.get('body', 'very bad') senderEmail = request.POST.get('senderEmail', 'my_email@gmail.com') send_mail(subject, body, 'sender@gmail.com', [senderEmail], fail_silently=False) return HttpResponse("Email Send.") -
CSRF verification failed only in production, Django
{% csrf_token %} is set. Tried @ensure_csrf_cookie as well. code: views.py: https://bpaste.net/show/UANTI template (landing.html): https://bpaste.net/show/P5YJA form_fields.html: https://bpaste.net/show/UQZKQ Can anyone help? Thanks in advance. -
django-cacheops... what is the "ops"?
I've searched, but I can't find anything that explains this. I know I'm risking a downvote here, but what is meant by "ops" with django-cacheops? https://github.com/Suor/django-cacheops I would think it's just a name, but sentences such as ...Here you can specify which ops should be cached... and ...You can pass any subset of this ops to... and ...with non-empty ops is... make me think I should know what 'ops' is... But the context clues aren't helping, and after reading the documentation and searching the internets, I feel like I'm missing something very obvious, and that I'm not going to get the full benefit of this tool... -
Structure in Django tutorial does not match match my strucuture
Starting a new project and realized that the structure for tutorial and my structure do not match. It looks like a directory was created for the myproject and a directory AND a file were created for myapp...I don't understand. Is this correct? Tutorial structure shows: mysite/ manage.py mysite/ init.py settings.py urls.py asgi.py wsgi.py My structure shows: myapp myappp __init__.py settings.py urls.py wsgi.py manage.py``` -
Invoke function after all methods Django Rest Framework ModelViewSet
I would like to invoke a function after all methods in a ModelViewSet. The function itself will be used as an external event log. So the response from the views would not be modified. I was not able to figureout how to achieve this. My ModelViewSet is a very basic one with serializer class and queryset defined. Any help would be appreciated. -
How to set initial value that is reference to an object
We are trying to set object as an initial value (image, it is a foreign key to an Image). We just cannot make it work, we are always getting NULL/blank value instead. Thanks for any help! from views.py def create_comment(request, image_id): image = Image.objects.get(id = image_id) if request.method == 'POST': form = CreateComment(request.POST, initial={'image':image}) if form.is_valid(): form.save() else: form = CreateComment() return render(request, 'ImagePost/create_comment.html', {'form':form, 'image_id':image_id}) from forms.py class CreateComment(forms.ModelForm): class Meta: model = Comment fields = ['user', 'text'] from create_comment.html <html> <body> <h1>Add comment</h1> <form action="{% url 'create_comment' image_id %}" method="POST"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Add"> </form> </body> </html> -
why home.html (for adding a new post) is not showing the rendered django form with ckeditor toolbar in add new post?
i am integrating some apps to make a bigger project but the problem is when i try insert ckeditor in html login page it is not showing. for this reason i tried to make separate app is to see whats going on here. i am showing you the code in detail. editing/settings.py: .......... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'editor', 'ckeditor_uploader', 'ckeditor', ] TEMPLATES = [ { 'DIRS': [os.path.join(BASE_DIR,'templates')],........ ..................... STATIC_URL = 'editor/static/' STATIC_ROOT='editor/static/' CKEDITOR_UPLOAD_PATH='editor/static/media/' editing/urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',include('editor.urls')), path('ckeditor/',include('ckeditor_uploader.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) in this case, my static folder is in editor/static when i execute python manage.py collectstatic and ckeditor folder is in editor/static directory also. editor/models.py: from django.db import models from ckeditor_uploader.fields import RichTextUploadingField # Create your models here. class Post(models.Model): title=models.CharField(max_length=255) body=models.CharField(max_length=2000) description=RichTextUploadingField() def __str__(self): return self.title editor/admin.py: from django.contrib import admin from .models import Post admin.site.register(Post) when i execute python manage.py makemigrations and python manage.py migrate, ckeditor can be seen in locahost:8000/admin's new post section perfectly. then i tried to make templates. base.html: {% load static %} <html> <head> <title>Django blog</title> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400" … -
Django Form Not Validating Properly
Code: https://dpaste.org/pwWT I want to validate the user's phone number and I want to display to the user who enters an incorrect phone number "Enter a valid phone number (e.g. +12125552368)." This message is the default of PhoneNumberField. The form is not validating and I am not sure why. I do not want any value to be accepted as the phone number. Also not sure why the recaptcha statements are not getting printed either. I would appreciate any help with this. -
Fail to load diferente content in modal Table
I Have two bootstrap tables, one of them (table_compras) call a modal (table_modal) depending on the column clicked, but i am having troubles refreshing the content rows in table, here is my code: HTML: <div id="modalTable" class="modal fade" tabindex="-1" role="dialog"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Acumulado por Obra</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body" id="bodyIP"> <table id="table_modal" data-detail-view="true" data-checkbox-header="true" data-search="true" data-search-align="left" data-detail-filter="detailFilter" data-pagination="true"> <thead id="thDel"> <tr> </tr> </thead> </table> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> JS Here i am getting the row and column index to populate the modal table but when I click on a different cell it continues getting the same data rows of the first cell, i have tried the commented lines of code but none of them give me the desired result : var $table_compras = $('#table_compras') var $table = $('#table_modal') $(function() { $('#modalTable').on('shown.bs.modal', function () { $table.bootstrapTable('resetView'); }) $('#modalTable').on('hide.bs.modal', function (e) { //var table = $('#table_modal').DataTable(); //table.clear(); //$("#table_modal tr").remove(); //$('#table_modal').empty(); //$(e.target).removeData('bs.modal'); $('#table_modal').detach(); //$("#table_modal").empty(); //$("#table_modal thead").remove(); //$('#modalTable').removeData(); }) }); $('#table_compras').on('click-cell.bs.table', function (field, value, row, $el) { buildTable2($table, 2, $el.C1, value); $("#modalTable").modal(); //alert($el.C1+"-"+$el.C2+"-"+$el.C3+"---"+value); }); function buildTable2($el, cells, ano, mes) { var columns … -
Add fields to a form with django at application level
I am using django and I need to use a form that is dynamic, that at the application level the user can add fields to the form. For example, I have a beer and I want to add features, which function would allow me to place an 'add' button and a new input will appear to put a new feature to the beer unlimited times, thus being able to add the number of features inputs that you want . If anyone knows the name of a function that allows me to do it or a link to the solution! Thanks in advance. I read a little about the FormSet and the Management Form but I really didn't understand exactly how to use it! If I could add a brief example it would be helpful -
Celery schedule
I have some schedule problem in Celery. The task works, however I want it to run once on Monday, but it runs every minute. My schedule config: CELERY_BEAT_SCHEDULE = { 'kek': { 'task': 'kek', 'schedule': crontab(day_of_week=6), } } -
How to delete 0001_initial.py in Django? Django migrations are not working
I am using Django 2.2 with Python 3.7 on Windows 10. I created a project and then an app. The models.py was populated by using INSPECTDB for an existing Postgres database. I removed the line 'managed = False' from each class. I created the initial makemigrations and did the migrate. There are app migration files, 0001_initial.py and init.py I had to make changes, adding more classes, in the models.py file. Then I ran the makemigration and migrate on the app. Now I get a message '.errors.DuplicateTable: relation "INT_ORG" already exists.' Throws an exception. I tried to use 'python manage.py makemigrations' and got the message that there were no changes detected. I tried to use 'python manage.py migrate --fake-initial'. This Errored with duplicate table already exists No luck. I'm failing badly here. And while working yesterday, somehow - don't know how, another migration file shows up called '0002_auto_20191212_1137.py' The '0002_auto_20191212_1137.py' migration file has all my changes in it. But it is not being migrated either when I try to makemigrations and migrate. I need to go back to a point I can understand and not loose everything. A co-worker had a similar problem and they just started a new project and … -
Getting PostSyncDb error when I run Python manage.py runserver (Trying to update to DJango 1.9)
I am trying to update my django slowly, I just went up to 1.9 today (from 1.8) and I am running into ImportError: cannot import name post_syncdb. I made sure my signals are imported for my models and that I have implement This Link . Any one else been through this? Here is my traceback when I try python manage.py runserver (www)ubuntu@prodcopy:/opt/django/www/src$ python manage.py runserver Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/opt/django/www/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/opt/django/www/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 302, in execute settings.INSTALLED_APPS File "/opt/django/www/local/lib/python2.7/site-packages/django/conf/__init__.py", line 55, in __getattr__ self._setup(name) File "/opt/django/www/local/lib/python2.7/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/opt/django/www/local/lib/python2.7/site-packages/django/conf/__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/opt/django/www/src/site_aggrigator/__init__.py", line 2, in <module> import management File "/opt/django/www/src/site_aggrigator/management/__init__.py", line 6, in <module> from django.db.models.signals import post_syncdb ImportError: cannot import name post_syncdb -
Return more than just the Auth Token with Django Rest + Djoser?
I'm using Django REST along with Djoser as my authentication service. However, when making a post request to the djoser auth endpoints, e.g. .../auth/token/login, the only response I get back is auth_token: xxxxx Is there a way to retrieve more than just the token value, e.g user id and username? -
Pass slug or id on GET request
I'm trying to test an API view for my Django project: BOOK_URL = reverse('api:book') // '/api/book/' book_id = 1 res = APIClient().get(f'BOOK_URL${book_id}') This works, but as you can see I need to interpolate the book_id into the string. Is there a way I can send a request without interpolating? I tried: res = APIClient().get(BOOK_URL, data={'book_id': book_id}) This is my views.py class BookView(APIView): def get(self, request, book_id): book = get_object_or_404( Book.objects.all(), id=book_id ) return book -
Problem with redirection on save form in UpdateView
I'm using Class Based Views in my project. After create object IdentityDocument in CreateView it redirects to correct Person DetailView (IdentityDocument owner), but after update in UpdateView redirects to current logged user detailed view (who is not parent owner object IdentityDocument). I have classes: class Person(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... def get_absolute_url(self): return reverse('person-detail', kwargs={'pk': self.pk}) class IdentityDocument(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) person = models.ForeignKey(Person, on_delete=models.CASCADE) ... def get_absolute_url(self): return reverse('person-detail', kwargs={'pk': self.person.pk}) My views: class PersonDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView): model = Person context_object_name = 'person' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['identity_documents_list'] = get_newest_identity_documents(self.kwargs.get('pk')) return context def test_func(self): person = self.get_object() if self.request.user == person: return True return self.request.user.is_admin class IdentityDocumentCreateView(LoginRequiredMixin, CreateView): model = IdentityDocument ... def dispatch(self, request, *args, **kwargs): self.person = get_object_or_404(Person, pk=kwargs['person_id']) return super().dispatch(request, *args, **kwargs) def form_valid(self, form): form.instance.person = self.person return super().form_valid(form) class IdentityDocumentUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = IdentityDocument ... def form_valid(self, form): form.instance.person = self.request.user return super().form_valid(form) def test_func(self): identity_document = self.get_object() if self.request.user == identity_document.person: return True return self.request.user.is_admin -
The POST method in DJANGO returns "None" when a form is submitted
I have built a small web application that will get the data from a HTML table and dump it into sqlite database. When I use the POST method to capture a particular cell value, it returns none. Could someone please help me how to get the data from the table I created below in table.html ? models.py from django.db import models class people(models.Model): Company = models.TextField() Contact = models.TextField() Country = models.TextField() def __str__(self): return self.Contact urls.py from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.getvalue, name='myapp'), ] views.py from django.shortcuts import render def getvalue(request): value = request.POST.get("R1") print("The R1 values is", value) return render(request, 'myapp/table.html') table.html <html> <head> </head> <body> <form id="form1" class="form1" method="post"> {% csrf_token %} <input type="submit" value="Update DB" /> <table> <tr> <th>Company</th> <th>Contact</th> <th>Country</th> </tr> <tr> <td name='R1'>Alfreds Futterkiste</td> <td name='R2'>Maria Anders</td> <td name='R3'>Germany</td> </tr> </table> </form> </body> </html> -
Django rest framework - Optimizng serialization of nested related field
Given the following models: class Model_A: ... class Model_B: ... class Model_C: model_a = ForeignKey(Model_A, related_name='c_items') model_b = ForeignKey(Model_B) ... And the following model serializers setup: class Model_A_Serializer: class Model_C_Serializer: class Meta: model = Model_C fields = ( 'model_b', ... ) c_items = Model_C_Serializer(many=True) class Meta: model = Model_A fields = ( 'c_items', ... ) And a basic vieweset: class Model_A_Viewset: model = Model_A queryset = model.objects.all() serializer_class = Model_A_Serializer ... When the user POST's the following JSON payload to create an instance of Model_A along with instances of Model_C: { 'c_items': [ { 'model_b': 1 }, { 'model_b': 2 }, { 'model_b': 3 } ] } Note: Model_B instances with IDs 1, 2, and 3 already exist, but no Model_A and no Model_C instances exist in the above example. Then I noticed that django seems to execute the following queries when serializing the incoming data: SELECT ... FROM Model_B WHERE id = 1; SELECT ... FROM Model_B WHERE id = 2; SELECT ... FROM Model_B WHERE id = 3; This seems unnecessary to me as a single SELECT ... FROM Model_B WHERE id IN (1,2,3) would do the job. How do I go about optimizng this? I have tried … -
registration with username and email, and login with email only
I am creating a login that requests for username and email with Django-rest-auth, the email is key as it will be used to log in to the user. but the username also has its importance in my app as when searching up a user, I would want to do something like this "accounts//". in trying to do this I have added a backend as advised in a former post. please, what can I do, so when signing up I can input my username and email, but when logging in i use only email? backend.py class EmailAndUsernameBackend(ModelBackend): """ this model backend would help me use both username and email, remember to overide your AUTHENTICATION_BACKENDS to this one """ def authenticate(self, request, username=None, password=None, **kwargs): UserModel = get_user_model() if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: user = UserModel.objects.get(Q(email=username) | Q(username=username)) except UserModel.DoesNotExist: UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user in my settings.py, apart from my installed apps and the authentication backends, I have: AUTHENTICATION_BACKENDS = ( # 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', 'core.backends.EmailAndUsernameBackend', ) # to use old_password when setting a new password OLD_PASSWORD_FIELD_ENABLED = True LOGOUT_ON_PASSWORD_CHANGE = False ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USER_EMAIL_FIELD = …