Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-webpack-loader not rendering react app using react-app-rewired
I'm working on tying my react and Django apps together. Right now I'm just working to get the dev server working and will focus on production later. I've been following a handful of guides on this process, but they're all a little different and I haven't been able to find the right combination to get this working. I'm using react-app-rewired because I'd like to not have to eject. My understanding is that its more desirable to not eject and manually configure all of the Webpack configs. This may especially be true as I'm still learning react/webpack. Its my understanding that once this is configured I just need to run the Django server and it should display my app. I'm not running collectstatic or any npm start or build commands. Here's what I have configured: base.py ... STATICFILES_DIRS = [ # os.path.join(os.path.join(BASE_DIR, 'frontend'), 'build', 'static') os.path.join(BASE_DIR, "frontend", "build", "static"), ] ... local.py ... WEBPACK_LOADER = { "DEFAULT": { "CACHE": not DEBUG, "BUNDLE_DIR_NAME": "frontend/build/static/", # must end with slash "STATS_FILE": os.path.join(BASE_DIR, "frontend", "build", "webpack-stats.json"), } } ... config-overrides.js var BundleTracker = require('webpack-bundle-tracker'); module.exports = { webpack: (config, env) => { config.plugins.push( new BundleTracker({ path: __dirname, filename: './build/webpack-stats.json' }), ); return config; }, … -
How to display the website three inside page? Even an instance
I can't show the website tree on every pages as a menu…? I’m quite confuse with wagtails querySet… and how to move inside the three… I got always the same error Manager isn't accessible via BlogPage instances I able to display ancestors of a page but not able to show sibling of my current page. class BlogIndexPage(Page): ... class BlogPage(Page): ... def event_index(self): homepage = self.get_ancestors().type(BlogIndexPage).last() return homepage def siblings_index(self): siblings = self.objects.sibling_of(BlogIndexPage) return siblings I got : Manager isn't accessible via BlogPage instances I'm trying to do it only with wagtails basic query. (without wagtailmenu add-on) -
How to use django with a sqlcipher encrypted sqlite database
I am trying to integrate my sqlite database, encrypted with sqlcipher, to my database and have found very little support for this online. I have set my engine to 'django.db.backends.sqlcipher.backend' or 'sqlcipher.backend' and keep getting this type of error django.core.exceptions.ImproperlyConfigured: 'sqlcipher.backend' isn't an available database backend. Does django need a specific backend for each database type that is tailored for django-db integration? I only found this that I couldn't get to work https://github.com/codasus/django-sqlcipher and an SO question that never got answered Set database engine to sqlcipher in Django Any one have any ideas on preferably how to make this work, or otherwise know of an easy way to encrypt an sqlite database and integrate with django? -
How to load the data within the viewset class automatically on the server?
I had the backend Django project running on EC2, Ubuntu18.04, nginx. Basically, when I test the project locally by running 'python manage.py runserver', i can see the matrix i want to generate loaded before the server is ready to go. However, after i deployed it on the server, it gave back the error that the views doesn't have the attribute called 'matrix'. I tried locally, and i can see my prints so that it truly generate the matrix. However, i cannot debug the project as the same way i did locally as i run the project automatically by setting up the .conf file. module 'test.views' has no attribute 'matrix' class CreateMatrixViewSet(viewsets.ModelViewSet): serializer_class = MatrixSerializer queryset = Matrix.objects.all() print("start creating ls_frame") global ls_frame ls_frame = read_frame(queryset) print("end creating ls_frame") print("start creating matrix") global matrix matrix = generateMatrix(ls_frame) print("end creating matrix") http_method_names = ['post'] def create(self, request): ... I assume that when running on the server, it won't do the initial loading. So if i want to generate something before i make the server ready, what should i do? -
Get around Internal Server Error for Hello World django project in production
I have my apache server directing traffic from mysite.com/home to my wsgi.py file, but when get_wsgi_application() is called I get an internal server error. Running apache2 on amazon linux EC2. In wsgi.py, I've replaced the line, application = get_wsgi_application() with the function, def application(environ, start_response): status = '200 OK' output = b'sys.path = %s\n' % repr(sys.path).encode('UTF-8') output += b'sys.version = %s\n' % repr(sys.version).encode('UTF-8') output += b'sys.prefix = %s\n' % repr(sys.prefix).encode('UTF-8') response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(output)))] start_response(status, response_headers) return [output] and the server error goes away. It shows that apache is using the correct python version (3.7) and doesn't return an error when I import get_wsgi_application() from django.core.wsgi. To my understanding this means apache is finding the access point to my django project just fine, and it has permission to look into the file and show its contents. What am I missing? Other possibly relevant information I can think of: user "apache" and group "apache" own the outer mysite directory and everything in it. I've set all the settings in settings.py for production according to the django deployment checklist. https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ wsgi.py: import os, sys from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') sys.path.append('/usr/local/wsgi/django') sys.path.append('/usr/local/wsgi/django/mysite') application = get_wsgi_application() httpd.conf: <VirtualHost *:80> ServerName www.mysite.com … -
Overloading changelist_view with no changes causing errors
Overloading changelist_view and calling the super() causes attribute errors. I'm creating a super basic dashboard and I am overriding the changelist_view method of a ModelAdmin class. However, this override is resulting in an error "NoneType object has no attribute 'has_header'." However, I'm literally not doing anything but override the changelist_view and calling the super class - I haven't made any changes yet. In admin.py class SummaryAdmin(admin.ModelAdmin): def changelist_view(self, request, extra_context=None): response = super().changelist_view(request, extra_context) The corresponding model in models.py class Summary(Failure): class Meta: proxy = True verbose_name = 'Failure Summary' verbose_name_plural = 'Failures Summary' This is literally the entire contents of the admin model. When I try to go to the django admin panel, I get the attribute error. As far as I can tell, this should be no different than not overrifing changelist_view at all, but if I delete the override everything functions as normal. -
How do I stay on the same page after submitting a post request and hit another post request?
I'm doing a one page website where I'm wanting to input some text and upload files. Basically, how I want my form to look like at the front end is, first I can type some text in the textarea given, below that I should be able to select multiple files, once the files are selected I'll click on the upload button, the files should be uploaded, and then I'll hit submit and that's how I create a post. I'm attaching my code below. I do have written my broken views.py file but I'm not attaching it for now. models.py : class Post(models.Model): post_body = models.TextField(blank=False, max_length=500) class PostMedia(models.Model): file = models.FileField() body = models.ForeignKey(Post, on_delete=models.CASCADE) forms.py : from django.forms import ClearableFileInput from django.forms import ModelForm from .models import Post, PostMedia class PostModelForm(ModelForm): class Meta: model = Post fields = ['post_body'] class PostMediaModelForm(ModelForm): class Meta: model = PostMedia fields = ['file'] widgets = { 'file': ClearableFileInput(attrs={'multiple': True}), form.html (I was trying to write the jquery function): <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> $('text-form').on('submit',upload(e) { e.preventDefault(); $.post( '../create-post', $('form').serialize(), function( data ) { alert( data ); } ); }); </script> <div class="site-form"> <h2>Create a New Post here! … -
Django global filter
Is there a way to filter globally a Django model? We need to set a filter in a single place so that it gets applied in all queries generated by Django ORM including related objects lookups etc. Example: class A(Model): n = IntegerField() class B(Model): a = ForeignKey(A) We want to set on A a global filter id__gte=10 (static to make it simple). The filter must be then automatically applied also when doing related queries, e.g. B.objects.filter(a__n=123) # this code cannot be modified should expand somehow magically to an equivalent of B.objects.filter(a__n=123, a__id__gte=10) We can change models, managers, querysets but we cannot change the code where objects are actually queried (a lot of code, third party apps, generic API). -
Converting raw sql query to Django ORM
I have 3 models in my projec like this: class Model_A(Models.Model): field_a_1 = models.IntegerField() ...other fields... class Model_C(models.Model): field_c_1 = models.IntegerField() field_c_2 = models.IntegerField() ...other fields... class Model_B(Model_C): table_a_fk_id = ChainedForeignKey(Model_A, .... ) ...other fields... Because of that in my database I have the following three tables: Table_A(id, name, field_a_1, ...other fields....) Table_B(id, table_a_fk_id, table_c_fk_id, .....other fields...) Table_C(id, field_c_1, field_c_2, ...other fields....) and I need a query that retrive data like this output: Table_A_id Table_A_name count ------------------------------------------------ 12 Table_A_name_12 138 1 Table_A_name_1 133 13 Table_A_name_13 55 15 Table_A_name_15 38 9 Table_A_name_9 34 7 Table_A_name_7 0 19 Table_A_name_19 0 I have solved the problem with a raw sql query, but I don't know how do the same in Django ORM. This is my SQL code: SELECT `Table_A`.`id` AS 'Table_A_id', `Table_A`.`nome` AS 'Table_A_name', COUNT(`ptr`.`table_a_fk_id`) AS `count` FROM `Table_A` LEFT OUTER JOIN ( SELECT `Table_C`.`id`, `Table_B`.`table_a_fk_id` FROM `Table_B` INNER JOIN `Table_C` ON ( `Table_B`.`table_c_fk_id` =`Table_C`.`id`) WHERE ( `Table_B`.`table_a_fk_id` = xx AND `Table_C`.`field_c_1` = yy AND `Table_C`.`field_c_2` = zz ...other constraints on Table_C fields.... ) ) ptr ON (`Table_A`.`id` = `ptr`.`table_a_fk_id`) WHERE (`Table_A`.`field_a_1` = x ) GROUP BY `Table_A`.`id` ORDER BY `count` DESC, `name` ASC I want translate the above sql in Django ORM … -
NOAUTH Authentication required. Redis settings on docker compose for django
I keep on getting the error message: redis.exceptions.ResponseError: NOAUTH Authentication required.. (I'm using celery to perform background tasks). My settings.py looks like this: CELERY_BROKER_URL = 'redis://user:my_strong_password@'+REDIS_IP+':6379/0' the docker-compose I have: services: redis: image: redis:latest container_name: jh_redis ports: - '6379:6379' command: redis-server --appendonly yes --requirepass my_strong_password you can see that my attempt to provide the password (--requirepass) is exactly as it shown in the settings.py however, while the docker is up and running I still get the subject error message. I have tried different combination such as: --requirepass user:my_strong_password but still didn't work. Note: when I take off the entire command line - it works (but 32 hours after - I get the error message and it stop working). What should be the appropriate settings in docker-compose to have it work smoothly? -
How to add disable password for django users
I have created a tool for my colleagues and i have integrated SSO with this django application as well. Now the way i'm planning to authenticate users are like the following. SSO page is sending the logged in user ID in cookie. If the logged in user have an account in django users, i'll check for a match and i should authenticate the user. The challenge i'm facing here is while creating users i have to provide password and i don't want to validate user password again. Is there a way i can disable the password while we add the user in to django admin itself? I'm using Django 1.11 with python 3.4. Let me know your thoughts. -
How to translate variables in Jinja2/Django
I use i18n in my Jinja2 templates and everything works fine for plain text. But I can't find any info how to use translations with variables, which I can't avoid using. Here is an example: {% set words = ["Hello", "world"] %} {% for word in words %} {{ _(word) }} {% endfor %} What should I do to get "Hello" and "world" in my .po file? -
what to do instead of foreign key for one to many relations?
For one to many relations, we can use a foreign key but it has its own problems. I want to remove the foreign key from my field and define relations between tables using ORM. but I don't know how? -
How does attribute of model only for user.is_staff?
Model "Post" has the boolean attribute "moderation". I need the this attribut was only in user.is_staff on the page "Post update". models.py class Post(models.Model): ... moderation = models.BooleanField(default=True) ... forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'body', 'logo'] views.py class PostUpdateView(PermissionRequiredMixin, UpdateView): model = Post fields = ['title', 'body', 'logo'] permission_required = 'post.can_mark_returned' post_form.html {% extends "base_generic.html" %} {% block content %} <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit" /> </form> {% endblock %} -
Django Select2MultipleWidget not allowing multiple selection
I am trying to implement a Select2 Multi-select box in my Django project where a user can select from a range of interests and choose more than 1. What is instead happening is this Where a user sees a scrollable list and can select one. I am looking for this example from Select2 My code is below, I have omitted code that is not relevant. My scripts for JQuery etc are in my base.html file which include Bootstrap, Js, Popper,js and JQuery forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile from django_select2.forms import Select2MultipleWidget class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['interests'] widgets = { 'interests': Select2MultipleWidget, } models.py from django.db import models from multiselectfield import MultiSelectField from django.contrib.auth.models import User INTEREST_CHOICES = ( ('FITNESS', 'Fitness'), ('SPIRITUAL', 'Spiritual'), ('VEGANISM', 'Veganism'), ('MOVIES', 'Movies'), ) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) interests = MultiSelectField(choices = INTEREST_CHOICES) profile.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% load static %} {{ form.media.css }} {% block head %} <title>User profile</title> {% endblock %} {% block body %} <script type="text/javascript"> window.onerror = function (msg) { $("body").attr("JSError", msg); } </script> {{ form.media.js }} <div class="container-fluid … -
How to render the options in a select of a Django form?
I would like to render two selects with Django (one multiple select, the other a simple one) and customize it with Materialize. I manage to code the following: In my forms.py class ZonesForm(forms.Form): zones_options = ( (1, 'Zone 1'), (2, 'Zone 2'), (3, 'Zone 3'), (4, 'Zone 4') ) zones = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=zones_options) conn_options = ( (1, 'ABCDE'), (2, 'FGHIJ'), ) connections = forms.ChoiceField(choices=conn_options) In my zones.html {% block content %} <div class="container"> <div class="row"> <form method="post"> <div class="input-field col s6"> <select multiple name="{{ form.zones.name }}"> {% for opt in form.zones %} <option value="{{ opt.id }}">{{ opt.label }}</option> {% endfor %} </select> <label>Zones</label> </div> <div class="input-field col s6"> <select name="form.connections.name"> {% for opt in form.connections %} <option value="{{ opt.id }}">{{ opt }}</option> {% endfor %} </select> <label>Connection</label> </div> </form> </div> </div> {% endblock %} My problem is: when the page is rendered, I get 4 checkboxes for the first select (as expected), and no names for it (all options are blank). For the second select I get 4 options (one blank, one with 'ABCDE', one blank, one with 'FGHIJ'). I suspect that the problem is with the attributes. I am not getting the right values for them (I have tried … -
Django Gmail API send EMails
Im already using Gmail API for login in my Django project. Im using social-auth-app-django 2.1.0 SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'XXXXXX.apps.googleusercontent.com' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'XXXXXXX' now I want to extend this and also send emails via the Gmail API. This means that the sender of the email is the user's own email and not the one from the project page. I've been looking at the reference here. https://developers.google.com/api-client-library/python/guide/django But it doesn't seem to be up-to-date, already the modules CredentialsField and FlowField can't be imported. So my question is, is it possible to integrate this directly via social-auth-app-django as described? If so, how could this be implemented? Unfortunately I didn't find anything suitable on the internet how I could realize it in Django. Im using Django 2.1.3 on Python 2.5.4 -
How to merge the result of two queries using update
I have to show the name of the category and the quantity of items in each category. The items can change the category, so I save the history of the items in the table items_history To show all the category name I'm running this query: category_total = Category.objects.all() Example of result: <QuerySet [<Category: Drink>, <Category: Food>, <Category: Fun>, <Category: Suplies>]> To get the quantity of items in each category, I have to check in the table items_history: items_history = Category.objects.filter(items_history__current=1).annotate(qtd=Count("items_history__idea_id")) Example of result: <QuerySet [<Category: Food>]> items_history[0].name -> 'Food' items_history[0].qtd -> 5 In this case, I have only items in Food Category. So I can't do just one query in items_history, because I'm not gonna get the quantity of the items in the other categories (0, in this case). I need to get all the categories with their respective quantity, so if a category is not persisted in items_history I should get the category name and the quantity = 0. The result expected: items_history[0].name -> 'Drink' items_history[0].qtd -> 0 items_history[1].name -> 'Food' items_history[1].qtd -> 5 items_history[1].name -> 'Fun' items_history[1].qtd -> 0 items_history[1].name -> 'Suplies' items_history[1].qtd -> 0 I'm trying to use update to merge the result of category_total and items_history … -
registered router url returns 404
I'm using django and rest-framework to develop a website. I have a users app in which the models are shown below: class User(AbstractUser): pass class Comment(models.Model): comment_text = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL,default=DefaultUser,on_delete=models.SET_DEFAULT,related_name='author') # DefaultUser is similar to AnonymousUser in django.contrib.aut.models date = models.DateTimeField(default=now) class User_Comment(Comment): on_user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='on_user',default=DefaultUser) class User_Comment(Comment): on_user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='on_user',default=DefaultUser) so it's basically a comment system where a user can comment on another user. I've used a rest framework serializer for posting comments: class User_CommentSerilizer(serializers.ModelSerializer): comment = User_Comment class Meta: model = User_Comment fields = ('comment_text','on_user') # extra_kwargs = {'password': {'write-only': True}} def create(self, validated_data): comment = User_Comment( author= User.objects.filter(username=self.context['request'].user)[0], on_user= User.objects.filter(username=validated_data["on_user"])[0], validated=False, comment_text= validated_data["comment_text"] ) comment.save() return comment and then using a UserCommentViewSet in views.py: class User_CommentViewSet(viewsets.ViewSet): serializer_class = User_CommentSerilizer queryset = User_Comment.objects.all() and finally in the urls file I've registered the view: router = DefaultRouter() router.register('profile' , views.UserViewSet) router.register('comment' , views.User_CommentViewSet) router.register('login' ,views.LoginViewSet, base_name='login') urlpatterns = [ # path('', views.GetUser.as_view()), path('users/', include(router.urls)), ] the profile and login routers are working fine. however the comment router is not showing at all (and returns 404) without raising any other error. I can't figure out what the problem is Although I did find out that it has something … -
django-compressor CACHE folders are empty when CACHES is set to MemcachedCache
I have the following installed on my project Django==2.1.4 django-compressor==2.1 python-memcached==1.59 with the following settings COMPRESS_ENABLED = True CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', 'TIMEOUT': 3600, } } With this configuration, all css and js files are not loaded due to 404 errors. When I check the static folders, CACHE/css and CACHE/js are empty. This is a project that was upgraded from a lower django version. It was working with the same settings prior to upgrade. Previous working version: Django==1.8.4 django-compressor==1.5 python-memcached==1.57 Am I missing some configuration? -
Error moving SQL query from Postgres to MariaDB
This is part of a query which works fine in PostgreSQL (in a Django app): CASE WHEN abc.name = 'foo bar' AND user.first_login <= (now() - interval '{new_user_interval} day') THEN 0 ELSE COALESCE(abc.rank, 0) END AS interesting_value, However, when I try to run it in a MariaDB database, I get this error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ') THEN 0\n ELSE COALESCE(abc.rank, 0)\n END AS interesti' at line 13" It seems to follow the MySQL case operator syntax fine. Why is this error occurring? -
RuntimeWarning for DateField in Django
Hello i'm using dates for search queries. But i am getting runtime error. RuntimeWarning: DateTimeField Jobs.job_created_on received a naive datetime (2019-01-17 00:00:00) while time zone support is active. Views.py class JobListView(LoginRequiredMixin, generic.TemplateView): template_name = 'admin/jobs/job.html' def get(self, request, *args, **kwargs): context = super(JobListView, self).get_context_data(**kwargs) if 'status' in request.GET: form = JobSearchForm(request.GET) if form.is_valid(): status = form.cleaned_data['status'] start_date = form.cleaned_data['start_date'] end_date = form.cleaned_data['end_date'] company = self.request.user.userprofile.user_company lookups = (Q(job_company=self.request.user.userprofile.user_company) ) if start_date: lookups = lookups | Q(job_created_on__gte=start_date) if end_date: lookups = lookups | Q(job_created_on__lte=end_date) jobs=Jobs.objects.exclude(job_is_deleted = True).filter(lookups) else: form = JobSearchForm() company_name = self.request.user.userprofile.user_company jobs = Jobs.objects.exclude( job_is_deleted = True ).filter( job_company=self.request.user.userprofile.user_company ) return render(request, self.template_name, {'form': form, 'jobs': jobs}) Forms.py ACTIVE_CHOICES = ( ('AllStatus', 'Select Status'), ('Active', 'Active'), ('InActive', 'Inactive'), ) class JobSearchForm(forms.Form): start_date = forms.DateField(label=False) end_date = forms.DateField(label=False) status = forms.ChoiceField(choices=ACTIVE_CHOICES, label=False, initial="") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['start_date'].widget.attrs['placeholder'] = 'Start Date' self.fields['end_date'].widget.attrs['placeholder'] = 'End Date' # self.fields['status'].initial = 'Select Status' self.fields['start_date'].widget.attrs['class'] = 'job_date' self.fields['end_date'].widget.attrs['class'] = 'job_date' self.fields['start_date'].required=False self.fields['end_date'].required=False Template.html <form action="" method="GET" id="searchForm"> {% crispy form %} </form> -
edit django form with instance always loads with empty form fields
models.py class summary_model(models.Model): username = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) summary=models.TextField(unique=False, blank=False, null=False) numberofprojects=models.CharField(max_length=264, unique=False, blank=False, null=False) numberofinternships=models.CharField(max_length=264, unique=False, blank=False, null=False) numberofjobs=models.CharField(max_length=264, unique=False, blank=False, null=False) def __str__(self): return str(self.username) forms.py class summary_form(forms.ModelForm): #fields from model class Meta: model = summary_model fields = ('summary','numberofprojects','numberofinternships','numberofjobs') views.py def summaryview(request): username=request.user if request.method == 'GET': try: summaryform=summary_form(request.GET or None,instance=summary_model.objects.get(username=username)) print(summaryform) except: summaryform=summary_form(request.GET or None) elif request.method == 'POST': form4=summary_form(request.POST or None,instance=summary_model.objects.get(username=username)) if form4.is_valid(): summary_obj = form4.save(commit=False) summary_obj.username = request.user summary_obj.save() return redirect('#anotherview') else: summaryform=summary_form(instance =summary_model.objects.get(username =username)) return render(request,'app/summary.html',{'summaryform':summary_form,}) template/summary.html {% block content %} <form action="" method="post" novalidate> {% csrf_token %} {{ summaryform.non_field_errors }} <div class="row form-row bg-white has-shadow"> <div class="col-12"> <span class="labelspan">{{ summaryform.summary.label }}</span> {{ summaryform.summary.errors }} <span class="inputfieldspan">{{ summaryform.summary}}</span> </div> <div class="col-6"> <span class="labelspan">{{ summaryform.numberofprojects.label }}</span> {{ summaryform.numberofprojects.errors }} <span class="inputfieldspan">{{ summaryform.numberofprojects}}</span> </div> <div class="col-6"> <span class="labelspan">{{ summaryform.numberofinternships.label }}</span> {{ summaryform.numberofinternships.errors }} <span class="inputfieldspan">{{ summaryform.numberofinternships}}</span> </div> <div class="col-6"> <span class="labelspan">{{ summaryform.numberofjobs.label }}</span> {{ summaryform.numberofjobs.errors }} <span class="inputfieldspan">{{ summaryform.numberofjobs}}</span> </div> </div> {{ summaryform.message.help_text }} <button type="submit" class="btn3">Save and Continue</button></form> {% endblock %} i need to take input in summary form and allow user to edit using the same view.when i save the filled data its updating but the main issue is its not populating data in the … -
get_context_data function doesn't return the 'form'
I have the following Django code (django version 1.11) of a form: class MyDocumentUpdateView(UpdateView): """ We extend UpdateView as we need to pass self.object in context as resource """ model = MyDocument def get_context_data(self, **context): context[self.context_object_name] = self.object context['resource'] = self.object #context['form'] = self.get_form() <-- if I uncomment this it works return context class DocumentUpdateView(MyDocumentUpdateView): form_class = MyDocumentForm def form_valid(self, form): doc = form.save(commit=False) doc.owner = self.request.user updateMyDocument(doc, form) return HttpResponseRedirect( reverse( 'mydocs_detail', args=( self.object.slug, ))) When I run this code, I get an error: 'str' object has no attribute 'fields' I realized that this error related with the return of the context variable. For some reason the context dictionary does not include the 'form'. As indicated in the documentation: get_context_data(**kwargs)¶ Calls get_form() and adds the result to the context data with the name ‘form’. But in my case the context dictionary does not include the 'form'. If I use the get_form() def, then everything works: context['form'] = self.get_form() But this seems like an overkill to me and I want to dig deeper on why this doesn't work. Then I have noticed that in my case I use: def get_context_data(self, **context): instead of: def get_context_data(self, **kwargs): So I defined the … -
mail_admin in Django + Apache2 = wsgi:error <3
I use mail_admin in my Django site but whan I call this in view all is good without that message come no, and this error in error.log of apache2 My view: def order(request): name = request.POST.get('name', '') telephone = request.POST.get('telephone', '') mail = request.POST.get('email', '') date = timezone.now() if name and telephone and mail: try: mail_admins( 'Product', '"New client '+name+' with phone: '+telephone+' and email: '+mail+' ...blah blah blah "', ['<I'm>@gmail.com', '<some>@gmail.com'],) except BadHeaderError: return HttpResponse('Invalid header found.') user = SmartLightUser(SmartLightUser_name=name, telephone=telephone, mail=mail, ord_date=date) user.save(); return HttpResponseRedirect(reverse('SmartLight:ordered', args=())) else: return HttpResponse('Make sure all fields are entered and valid.') apache2 error.log: [Thu Jan 17 14:32:53.511971 2019] [wsgi:error] [pid 27941:tid 140191074412288] [remote 195.135.246.161:6669] Content-Type: text/plain; charset="utf-8" [Thu Jan 17 14:32:53.512078 2019] [wsgi:error] [pid 27941:tid 140191074412288] [remote 195.135.246.161:6669] MIME-Version: 1.0 [Thu Jan 17 14:32:53.512094 2019] [wsgi:error] [pid 27941:tid 140191074412288] [remote 195.135.246.161:6669] Content-Transfer-Encoding: 8bit [Thu Jan 17 14:32:53.512110 2019] [wsgi:error] [pid 27941:tid 140191074412288] [remote 195.135.246.161:6669] Subject: =?utf-8?b?W0RqYW5nb10gRml4ZSBNYXQg0LfQsNC80L7QstC70LXQvdC90Y8=?= [Thu Jan 17 14:32:53.512124 2019] [wsgi:error] [pid 27941:tid 140191074412288] [remote 195.135.246.161:6669] From: <site>@gmail.com [Thu Jan 17 14:32:53.512138 2019] [wsgi:error] [pid 27941:tid 140191074412288] [remote 195.135.246.161:6669] To: <i'm>@gmail.com [Thu Jan 17 14:32:53.512151 2019] [wsgi:error] [pid 27941:tid 140191074412288] [remote 195.135.246.161:6669] Date: Thu, 17 Jan 2019 12:32:53 -0000 [Thu Jan 17 …