Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to provide requested user in initial values with django ModelForm and assign the form in django admin
I'd like to create articles with ModelForm and generic CreateView without choosing my user as author. Author should be the requested user. I know it can be solved in multiple ways, but I'd like to solve it with a form that I can use everywhere (django-admin and views). So far, I've tried this: models.py class Article(TimeStampedModel): ... author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = RichTextUploadingField(config_name='default') status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') ... forms.py class ArticleCreateForm(forms.ModelForm): class Meta: model = Article fields = [ 'title', 'featured_image', 'content', 'status' ] author = forms.IntegerField(widget=forms.HiddenInput) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) user_field = kwargs.get('instance') self.fields['author'].initial = user_field.id views.py class ArticleCreateForm(forms.ModelForm): class Meta: model = Article fields = [ 'title', 'featured_image', 'content', 'status' ] author = forms.IntegerField(widget=forms.HiddenInput) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) user_field = kwargs.get('instance') self.fields['author'].initial = user_field.id It renders the form, but instead of saving the article, it throws this error: File "/home/tareq/Desktop/PERSONAL/Blog/blog/blog/articles/forms.py", line 19, in __init__ self.fields['author'].initial = user_field.id AttributeError: 'NoneType' object has no attribute 'id' ERROR 2021-01-23 00:58:31,533 log 85374 140159710901824 Internal Server Error: /new/ Traceback (most recent call last): File "/home/tareq/.local/share/virtualenvs/Blog-i5phkViF/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/tareq/.local/share/virtualenvs/Blog-i5phkViF/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/tareq/.local/share/virtualenvs/Blog-i5phkViF/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, … -
Dropzone.js blocks "return render" call from Django
I am writing a website with drag and drop upload using Dropzone.js and Django. Dropzone.js is blocking somehow the return render call from Django. I tried a lot but couldn't disable it. Any help appreciated. views.py: def upload(request): if request.method == 'POST': uploaded_file = request.FILES['file'] file_obj = File.objects.create(file=uploaded_file) return render(request, 'uploadapp/nextpage.html') return render(request, 'uploadapp/upload.html') upload.html {% extends "base.html" %} {% load static %} {% block title %}Upload{% endblock %} {% block head_scripts %} <script src="{% static 'uploadapp/custom_dz.js' %}" defer></script> <script src="{% static 'uploadapp/dz/dist/dropzone.js' %}"></script> {% endblock %} {% block content %} <section class="bg-light text-center"> <div class="container"> <div class="row"> <div class="col-xl-10 mx-auto"> <h2 class="mb-4">upload</h2> </div> <div class="col-md-10 col-lg-8 col-xl-9 mx-auto"> <form action="{% url 'upload'%}" method="POST" class="dropzone dz" id="testdropzone" enctype="multipart/form-data"> {% csrf_token %} <div class="fallback"> <input name="file" type="file"> <button type="submit">Upload</button> </div> </form> <br> </div> </div> </div> </section> {% endblock %} custom_dz.js Dropzone.autoDiscover = false; const myDropzone = new Dropzone("#testdropzone", { maxFiles: 1, maxFilesize: 20, }) So the POST request is running, everything works, file is saved, but then this line (return render(request, 'uploadapp/nextpage.html')) from the views.py is not working. I did try to solve it by adding this function to custom_dz.js which is working, but then I can't pass variables and so … -
Getting error=H14 on Django-Heroku App using gunicorn
I'm trying to deploy my django-react app to heroku. Deployment goes smoothly but on heroku open I'm greeted by an application error. heroku logs --tail reveals the following in short: error code H14 "No web process running" in detail: > 2021-01-22T18:12:32.000000+00:00 app[api]: Build started by user > johndoe@gmail.com 2021-01-22T18:13:42.032970+00:00 app[api]: > Deploy f905f66c by user johndoe@gmail.com > 2021-01-22T18:13:42.032970+00:00 app[api]: Running release v3 > commands by user johndoe@gmail.com > 2021-01-22T18:13:42.786292+00:00 app[api]: Starting process with > command `/bin/sh -c 'if curl $HEROKU_RELEASE_LOG_STREAM --silent > --connect-timeout 10 --retry 3 --retry-delay 1 >/tmp/log-stream; then 2021-01-22T18:13:42.786292+00:00 app[api]: chmod u+x /tmp/log-stream > 2021-01-22T18:13:42.786292+00:00 app[api]: /tmp/log-stream /bin/sh -c > '"'"'python manage.py migrate --no-input'"'"' > 2021-01-22T18:13:42.786292+00:00 app[api]: else > 2021-01-22T18:13:42.786292+00:00 app[api]: python manage.py migrate > --no-input 2021-01-22T18:13:42.786292+00:00 app[api]: fi'` by user johndoe@gmail.com 2021-01-22T18:13:50.874352+00:00 > heroku[release.2135]: Starting process with command `/bin/sh -c 'if > curl > https://heroku-release-output.s3.amazonaws.com/log-stream?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAJ3LIQ2SWG7V76SVQ%2F20210122%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20210122T181342Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Signature=5fc1b225b8a71466d45518b4029f165af938e8c5d766033b8a335481d6a46e84 > --silent --connect-timeout 10 --retry 3 --retry-delay 1 >/tmp/log-stream; then 2021-01-22T18:13:51.619515+00:00 heroku[release.2135]: State changed from starting to up > 2021-01-22T18:13:54.000000+00:00 app[api]: Build succeeded > 2021-01-22T18:13:55.388498+00:00 app[release.2135]: > /app/.heroku/python/lib/python3.6/site-packages/environ/environ.py:630: > UserWarning: /app/recipemanager/.env doesn't exist - if you're not > configuring your environment separately, create one. > 2021-01-22T18:13:55.388523+00:00 app[release.2135]: "environment > separately, create one." % env_file) 2021-01-22T18:13:56.208813+00:00 > app[release.2135]: Operations to perform: > 2021-01-22T18:13:56.208840+00:00 … -
Unable to hide server name in django based website hosted in azure webapp
Django based website is hosted in azure webapp (python 3.8). As part of the security measure, I am trying to hide the server name from the response header. By default, it is gunicorn/20.0.4. In the Django app, I have implemented the middleware layer and added the following code class testMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) response["Server"] = "dummyserver" response["X-XSS-Protection"] = 1 return response In the local env, this setting is working. In the response header, the server name was dummyserver. But once it is deployed in the Azure web app the server name is displayed as gunicorn/20.0.4 in the response header, but strangely the other setting like X-XSS-Protection is working as expected. It looks like the Azure web app by default replace the Django server name. Is there any way we can handle this? Thanks for your help. -
Can not display Django models on Homepage
I am new to Django and I am creating a portfolio test site. When I try to import models in home.html from views.py, which I imported from models.py, error displays on my website page (no such column: portfolio_project.title). Help would be greatly appreciated! models.py file from django.db import models class Project(models.Model): title=models.CharField(max_length=100) description=models.CharField(max_length=100) image = models.ImageField(upload_to='portfolio/images/') url = models.URLField(blank=True) views.py file from django.shortcuts import render from .models import Project def home(request): projects = Project.objects.all() return render(request, 'portfolio/home.html', {'projects':projects}) home.html file <h1>This is Home!</h1> {% for project in projects %} {{project.title}} {% endfor %} -
Django - how can users create groups and add other users to see content provided by that group (like on facebook)
I am creating a website with Django and I want My Users to be able to create there own groups (like on Facebook) and give permission to other members to see content only in that group can you give me a general idea of how I can go about coding that. -
Django - joining via the most recent through table row on a many-to-many
If I have a many-to-many relationship, with a custom through table, how can I join via only the most recent through table row? For example: class Price(models.Model): amount = models.DecimalField(max_digits=21, decimal_places=2) class PricingSchedules(models.Model): name = models.CharField(max_length=100) price = models.ForeignKey(Price, on_delete=models.CASCADE) class Product(models.Model): name = models.CharField(max_length=100) pricing_schedulesfd = models.ManyToManyField( PricingSchedules, related_name='pricing_schedule_set', through='ProductPricingSchedule', ) class ProductPricingSchedule(models.Model): created_at = models.DateTimeField(auto_now_add=True) product = models.ForeignKey(Product, on_delete=models.CASCADE) pricing_schedule = models.ForeignKey( PricingSchedule, on_delete=models.CASCADE, ) class Meta: unique_together = ('product', 'pricing_schedule') I realize these models are a little contrived, but the question still stands. Say I want to select all products whose price is equal to "5.00", but I only want to consider the most recent row in the ProductPricingSchedule table, if any exists at all? -
Implement API REST to an existing Django app
I'm looking for a good tutorial that illustrates that how can I Implement API REST to an existing Django app. Because I tried the official docs and other tutorials, and I'm still confusing, I'm unable to build an API for each function that I have. Is there any easy way to implement that? Thanks, -
How to set daily update limit for django model(db)?
Hi I'm having one Django web app where My model A contains 1000 records and I want to set a daily update limit for example if users are updating that data by uploading a .xls file then it should count how many records updated and once it is more than 500 then the user should get an Error message(Is there Any easy way to implement this at file processing level). Can Anyone help me how to implement this (Is there an SQLite parameter that I can mention in settings.py) below is my upload code. (Here I have tried to store the count value and comparing it with half of the record but again how to reset it after 12/certain time/hrs?) def CTA_upload(request): try: if request.method == 'POST': movie_resource = CTAResource() ##we will get data in movie_resources#### dataset = Dataset() new_movie = request.FILES['file'] if not new_movie.name.endswith('xls'): messages.info(request, 'Sorry Wrong File Format.Please Upload valid format') return render(request, 'apple/uploadinfosys.html') messages.info(request, 'Uploading Data Line by Line...') imported_data = dataset.load(new_movie.read(), format='xls') count = 1 for data in imported_data: value = CTA( data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], ) count = count + 1 value.save() # messages.info(request, count) # time.sleep(1) messages.info(request, 'File Uploaded … -
Heroku does not upgrade python version
I am trying to deploy a django project in Heroku but the package 'django-mongoengine' needs a python version >=3.7. I have declare the ``runtime.txt`` file with one of the aviable python versions for Heroku but when I deploy the project, python-3.6.12 is still being installed. ``` Total 4 (delta 2), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Python app detected remote: -----> Installing python-3.6.12 remote: -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting Django==3.0.5 remote: Downloading Django-3.0.5-py3-none-any.whl (7.5 MB) remote: Collecting django-mongoengine==0.4.4 remote: Downloading django-mongoengine-0.4.4.tar.gz (186 kB) remote: Installing build dependencies: started remote: Installing build dependencies: finished with status 'done' remote: Getting requirements to build wheel: started remote: Getting requirements to build wheel: finished with status 'done' remote: Preparing wheel metadata: started remote: Preparing wheel metadata: finished with status 'done' remote: ERROR: Package 'django-mongoengine' requires a different Python: 3.6.12 not in '>=3.7' remote: ! Push rejected, failed to compile Python app. ``` The content of my runtime file is: ``` python-3.7.9 ``` And my Procfile file is: web: gunicorn graffitisWeb.wsgi Also the … -
when i tried to add urls in mysite directory nd checking the default server it shows like this?
i don not makesence how do get from it? Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in mysite01.urls, Django tried these URL patterns, in this order: polls/ admin/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
DjangoREST - How can I make my view/serializer more efficient on the server?
I'm using a serializer to extract a specific object from my models, followed by using said object field as a parameter in URL's via requests. I'm not getting any errors and everything is working fine, however I think it can be optimized better and be more efficient on the server. serializer.py class BucketListExtraDataSerializer(serializers.ModelSerializer): bucket_return = serializers.SerializerMethodField() bucket_sectors = serializers.SerializerMethodField() class Meta: model = Bucket fields = ('id','stock_list','bucket_return','bucket_sectors') def get_bucket_return(self, obj): print(obj.stock_list) if obj.stock_list: symbols_unicode = (','.join(map(str, obj.stock_list))) print(symbols_unicode) postgrest_urls = f"http://localhost:3000/rpc/bucketreturn?p_stocks=%7B{symbols_unicode}%7D" bucket_return = requests.get(postgrest_urls, headers={'Content-Type': 'application/json'}).json() return bucket_return def get_bucket_sectors(self, obj): if obj.stock_list: symbols_unicode = (','.join(map(str, obj.stock_list))) postgrest_urls = f"http://localhost:3000/rpc/bucketsectors?p_stocks=%7B{symbols_unicode}%7D" bucket_sectors = requests.get(postgrest_urls, headers={'Content-Type': 'application/json'}).json() return bucket_sectors I don't think it's optimal having multiple SerializerMethodField()'s. Which makes me wonder if I should translate all the extra requests def_bucket_return + def_buket_sectors into a view instead. I have doubts that in the future things can get really slow if a user has multiple objects. view.py class BucketListExtraData(generics.ListAPIView): permission_classes = [IsAuthenticated] serializer_class = BucketListExtraDataSerializer queryset = Bucket.objects.all() Disclaimer: my localhost:3000 is not an issue. Focusing on how I set up my serializer and view. Any recommendations on how I can optimize my serializer and view better to retrieve and display data quicker to … -
where i can host django on aws to have acces on cpanel and database
hello everyone am begginer sorry for my eng, i have bucket on amazon aws e3 whitch i contact by dns to subdomain and i made that for upload different resolution images for original and one for timeline for low resolution i want to size how much far it goes to learn properly what i need for and i have python api for back end and i will make next time front end , i am hosting on godaddy and i want to host on amazon but dont get and bunch of settings and by ssh its hard to control files how i can host my site to work on cpanel and lunch rest api to have acces on database can you guys links some source about that? thanks so much -
How to create a model in Django based on the instance of another model, but filtered
I am new to Django, I am searching a way to create a model in Django based on the instance of another model, but filtered. I have a table called Person, which has name and role, in my models.py: class Person(models.Model): id = models.UUIDField(primary_key=True) name = models.CharField(max_length=100) role = models.CharField(max_length=100) created_on = models.DateTimeField(auto_now_add=True) class Meta: db_table = 'person' What I want is to be able in my admin.py to call some subclass, which will display only actors (role="actors"): @admin.register(Actor) class Actor(admin.ModelAdmin):... Is it possible? Or do I have to create one more table only with actors? I know that I can use list_filter = ('role',), but this is not what I am searching for, I need actors exclusively. I see solution as something like this: class Actor(models.Model): objects = Person.objects.filter(role='actor') class Meta: verbose_name = 'actor' or class Actor(Person): self.objects.filter(role='actor') class Meta: verbose_name = 'actor' That obviousely does not work. -
How do you render a image in django?
I've been trying to render this image in django template but can't seem to accomplish it. Html: <span><a href="{% url 'logout' %}">Logout</a></span> {% for imagess in userimage %} <img src="{{ UserProfile.avatar }}"> {% endfor %} models.py: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") avatar = models.ImageField(upload_to = "avatars/", null=True, blank=True) views to render the image: def imageprofile(request): userimage = UserProfile.objects.all() context = {'userimage': userimage} return render(request, 'leadfinderapp/dashboard.html', context) Any help I would really appreciate it. Where I'm getting it wrong? -
Plotly Dash - Pattern Matching Callbacks Not Working Properly
here is some sample code that i have been trying to run from plotly dash's 'pattern matching callbacks examples page'. For the life of me, i cannot see what is wrong - the only error i get in the browser is Syntax Error - unexpected end of JSON input. I can see that the problem only occurs when i try to register the last callback with the pattern matching syntax. If it helps, I am using DjangoDash, so i can integrate dash with Django. My code is below: Thanks! import dash import dash_core_components as dcc import dash_html_components as html from django_plotly_dash import DjangoDash import dash_bootstrap_components as dbc from dash.dependencies import Input, Output, State, MATCH, ALL from dash.exceptions import PreventUpdate from django_dash.app import app layout = html.Div([ dbc.Button("Add Filter", id="dynamic-add-filter", n_clicks=0), html.Div(id='dynamic-dropdown-container', children=[]), ]) @app.callback( Output('dynamic-dropdown-container', 'children'), [Input('dynamic-add-filter', 'n_clicks')], [State('dynamic-dropdown-container', 'children')] ) def display_dropdowns(n_clicks, children): new_element = html.Div([ dcc.Dropdown( id={ 'type': 'dynamic-dropdown', 'index': n_clicks }, options=[{'label': i, 'value': i} for i in ['NYC', 'MTL', 'LA', 'TOKYO']] ), html.Div( id={ 'type': 'dynamic-output', 'index': n_clicks } ) ]) children.append(new_element) return children @app.callback( Output({'type': 'dynamic-output', 'index': MATCH}, 'children'), [Input({'type': 'dynamic-dropdown', 'index': MATCH}, 'value')], [State({'type': 'dynamic-dropdown', 'index': MATCH}, 'id')] ) def display_output(value, id): return html.Div('Dropdown … -
'Python manage.py runserver' "ValueError: Unable to configure handler 'mail_admins'".:
I'm working on a Django project. When starting the server I get "ValueError: Unable to configure handler 'mail_admins'". I'm in the correct directory, with virtual environment started. I can't make migrations, same error apears. Everything was working fine was able to start the server on this method in the past with no problem, until today. Thanks in advance! Version: Windows 10 Python 3.8.1 Django==3.1.5 frego@Yisus-Robles MINGW64 ~/Desktop/news $ python manage.py runserver Traceback (most recent call last): File "c:\users\frego\appdata\local\programs\python\python38\lib\logging\config.py", line 563, in configure handler = self.configure_handler(handlers[name]) File "c:\users\frego\appdata\local\programs\python\python38\lib\logging\config.py", line 744, in configure_handler result = factory(**kwargs) File "C:\Users\frego\.virtualenvs\frego-6ij68a4f\lib\site-packages\django\utils\log.py", line 89, in __init__ self.reporter_class = import_string(reporter_class or settings.DEFAULT_EXCEPTION_REPORTER) File "C:\Users\frego\.virtualenvs\frego-6ij68a4f\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "c:\users\frego\appdata\local\programs\python\python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\frego\.virtualenvs\frego-6ij68a4f\lib\site-packages\django\views\__init__.py", line 1, in <module> … -
Use of api key in Django
I´m trying to consume a web services with an api key. I've got the 200 answer but I really don´t know how to show the results. I need some help or guide to do it correctly. import requests headers = {'Content-Type': 'application/x-www-form-urlencoded'} url='http://plataforma.devteame.ml/plugin/chamilo_app/rest.php' response = requests.post(url, params= {'action': 'loginNewMessages','username':'demo','password': 'demo'}, headers=headers) if response.status_code == 200: return response.json() -
How to serve static files with django-rest framework?
I am new to Django development and I want to deploy my project on Azure WebApp service. When I switch to DEBUG = False, I get this error : The resource from “http://127.0.0.1:8000/static/css/index.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). Yet, I followed the steps described in this post : ALLOWED_HOSTS and Django I understood Django does not serve the static files by itself, that's why I installed WhiteNoise and put in the Middleware. (As shown in the post above.) Thus I don't understand why I have this error. Here my settings.py : """ Django settings for WebApp project. Generated by 'django-admin startproject' using Django 3.1.4. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'my_hidden_secret_key' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', … -
Django : Image files not diplayed in templates
I am trying to create a blog and to display user-uploaded images on a webpage. When I upload the image files using the Django admin interface (I made a model for Post images with an ImageField), the image is stored in /media/images correctly. But I can't display the image on my webpage. However, when I inspect my template with GoogleChrome, the path of my files are ok but there is a 500 error (Failed to load resource: the server responded with a status of 500 (Internal Server Error). Media Settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'core/static'), ) Project urls.py: from django.conf.urls import include, url from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin' , admin.site.urls), path("", include("authentication.urls")), path("", include("app.urls")), ]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) App urls.py: from django.urls import path, re_path from django.conf.urls import include, url from app import views from . import views urlpatterns = [ path('', views.index, name='home'), url(r'^blog$', views.blog_view, name ='blog'), url(r'^blog/(?P<id>[0-9]+)$', views.post_view, name ='blog_post'), re_path(r'^.*\.*', views.pages, name='pages'), ] Views.py def blog_view(request): query = Post.objects.all().order_by('-date') context = {'post_list' : query} … -
django 1.8.6 django-datatable-view==0.8.2: export buttons not showing
I have an old django app that I am moving into a docker container. It uses: Django==1.8.6 django-datatable-view==0.8.2 django-extensions==1.5.9 django-formtools==1.0 This is my template: {% load static %} {% autoescape off %} <script src="{% static 'js/datatableview.js' %}"></script> <script> datatableview.auto_initialize = false; $(function(){ var table = datatableview.initialize($('.datatable'), { lengthMenu: [ [ 10, 25, 50, 100, -1], [10, 25, 50, 100, "All"] ], {% if editable %} fnRowCallback: datatableview.make_xeditable({}), {% endif %} {% if page_length %} bPaginate: true, iDisplayLength: {{ page_length }}, {% else %} bPaginate: false, {% endif %} {% if filter %} bFilter: true, {% else %} bFilter: false, {% endif %} {% if dom %} sDom: '{% if export %}B{% endif %}{{ dom }}', {% else %} sDom: 'lrftip', {% endif %} {% if export %} buttons: [ "copy", "print", "csvHtml5", "excelHtml5", "pdfHtml5" ], {% endif %} }); }); </script> {% endautoescape %} and this is the result: the working version (in another server and not running in a docker component) give this result: as you can see I am missing the export buttons: Copy, Print, CSV, etc Even if I remove the if statement around the buttons' code, the buttons are not showing: {% endif %} {% if … -
Django: form CSRF verification failed
This is my first Django project, however, I have a problem submitting the form. I'm getting 'CSRF verification failed'. It's a very simple form just 2 fields(frontpage) and on submit to display the same page. views.py def newsletter(request): if request.method == 'POST': name = request.POST('name') email = request.POST('email') newsletter = Newsletter(name = name, email = email) newsletter.save() return redirect('/newsletter/') models.py class Newsletter(models.Model): name = models.CharField(max_length = 200) email = models.CharField(max_length=100) publish_date = models.DateTimeField(default = datetime.now, blank = True) def __str__(self): return self.name admin.py class NewsletterAdmin(admin.ModelAdmin): list_display = ('name','publish_date') admin.site.register(Newsletter, NewsletterAdmin) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name = 'home'), path('events/', events, name = 'events'), path('news/', news, name = 'mainnews'), path('about/', about, name = 'about'), path('', newsletter), ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) -
How to return DRF Forms data in the POST
So I have a class based view views/users.py where the POST is supposed to send the data from the form to the serializer to validated it and if its alright create the user and return me the data, but for some reason it returns me a 404 bad request. Here's the view: class UserSignUpAPIView(APIView): """ User sign up API view. """ permission_classes = [AllowAny] renderer_classes = [TemplateHTMLRenderer] template_name = 'users/signup.html' def get(self, request): serializer = UserSignUpSerializer return Response({'serializer': serializer,}) def post(self, request, *args, **kwargs): """ Handle HTTP POST request. """ serializer = UserSignUpSerializer(data=request.data) if serializer.is_valid(raise_exception=True): user = serializer.save() data = UserModelSerializer(user).data return Response(data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The get function is working fine, it returns the template but when I submit the form, it returns a 404 BAD Request. My serializer is the following serializers/users.py class UserSignUpSerializer(serializers.Serializer): """ User sign up serializer. Handle sign up data validation and user creation. """ email = serializers.EmailField( validators=[UniqueValidator(queryset=User.objects.all())] ) username = serializers.CharField( min_length=4, max_length=20, validators=[UniqueValidator(queryset=User.objects.all())] ) password = serializers.CharField( min_length=8, max_length=64 ) password_confirmation = serializers.CharField( min_length=8, max_length=64 ) first_name = serializers.CharField( min_length=2, max_length=30 ) last_name = serializers.CharField( min_length=2, max_length=30 ) birth_date = serializers.DateField() def validate(self, data): """ Check that passwords match. Check … -
How to redirect from FormView to a ListView after form validation
In my Django application, I would like to display a form where a user enters a name to search for Persons from an external data source (not model). I am using class-based generic views and have a working application (code attached below) with a minor inconvenience - I would like to see if there is a better way to do this. First, here's how I have done it: I have a Form with 3 fields (first, second and last name) and a clean() where I check if at least one field is populated A FormView which renders this form, and form_valid() method which does nothing at the moment (reasons will become clear shortly) An entry in urls.py to render this view and display the form in a template. The form is being submitted to a ListView with GET, and not the FormView itself (sad!) A ListView where I define get_queryset(self) because data comes from an external source, not a Model; and I use self.request.GET.get('first_name', '') etc. to retrieve query string values, make a connection to the external data source and get a Pandas dataframe which I convert to a list of records and render, paginated, in the template. An entry … -
Django TemplateDoesNotExist at templates
I created new project and can't find where the place where mistake was made. Django versiob - 3.1.5 Python 3.7.4 TemplateDoesNotExist at / index.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.5 Exception Type: TemplateDoesNotExist Exception Value: index.html Exception Location: C:\Users\user\PycharmProjects\Django learning\Portfolio\venv\lib\site-packages\django\template\loader.py, line 19, in get_template Python Executable: C:\Users\user\PycharmProjects\Django learning\Portfolio\venv\Scripts\python.exe Python Version: 3.7.4 Python Path: ['C:\Users\user\PycharmProjects\Django learning\Portfolio\landingpage', 'C:\Users\user\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\user\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\user\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\user\AppData\Local\Programs\Python\Python37', 'C:\Users\user\PycharmProjects\Django learning\Portfolio\venv', 'C:\Users\user\PycharmProjects\Django ' 'learning\Portfolio\venv\lib\site-packages', 'C:\Users\user\PycharmProjects\Django ' 'learning\Portfolio\venv\lib\site-packages\setuptools-40.8.0-py3.7.egg', 'C:\Users\user\PycharmProjects\Django ' 'learning\Portfolio\venv\lib\site-packages\pip-19.0.3-py3.7.egg'] structure: landingpage: --forms #app: urls views --landingpage: templates: index.html settings.py urls others ... landingpage/settings: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) project_name = "landingpage" 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/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # apps 'forms', ] 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 = 'landingpage.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] landingpage/urls: …