Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you handle anonymous users ,
How do you handle anonymous users , i have used a loginrequiredmixin but i would like for my create view and list view , to have signup link and some texat instead of being forced to goto the sign up page which loginrequiredmixin does , I want to understand how to hand anonymous users and setting user group permissions in django. Also i had to use getattribute in my post model, how do you use a success url in create view , I need answers for Django 2.0 , as i would like anonymous users to be able to access parts of the website. Thanks , -
Add Comment In Django
I have code but when I write comment not write it , and error "POST /post_list HTTP/1.1" 405 0 in views.py : class AddPost(View): def get(self,request): form = AddPostForm() context = {'form':form} return render(request,'add_post.html',context) def post(self,request): form = AddPostForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: context = {'form':form} return render(request,'add_post.html',context) in forms.py class AddCommentForm(ModelForm): def __init__(self,*args,**kwargs): super(AddCommentForm,self).__init__(*args,**kwargs) self.helper = FormHelper(self) self.helper.layout.append(Submit('submit','Add')) class Meta: model = Comment exclude = ['post'] labels = { 'name' : 'Nickname', 'comment' : '', } error_messages = { 'name':{ 'unique' : 'This Title has been used !' } } in post_content.html {% extends 'base.html' %} {% load static %} {% block title %} {{ post.title }} {% endblock %} {% block content %} <div align="center" class="divtw" style="width: 50%"> <h1>{{ post.title }}</h1> <h2>{{ post.text }}</h2> <h5>{{ post.author }}</h5> <hr> {% for comments in post.comment_set.all %} <div align="left"> <h5>{{ comments.name }}</h5> <p>{{ comments.comment }}</p> </div> <hr> {% endfor %} </div> <div align="left"> {% include 'add_comment.html' %} </div> {% endblock %} in add_comment.html {% load crispy_forms_tags %} <form method="post" action="/post_list"> {% csrf_token %} {% crispy form %} </form> when I add comment by admin page it comes with out error for more info this is link for download tutorial … -
Can't load URL: The domain of this URL isn't included in the app's domains. Django Facebook Auth
I have been using facebook login for my Django App. Recently facebook had updated its security feature, by enabling Strict Mode for all apps. After this change users are not able to login into site as it says below error Can't load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and sub-domains of your app to the App Domains field in your app setting But the domain name in App domain setting is fine. I think i am doing mistake in redirct_uri setting. I read lot of discussion on Facebook Developers group , but couldn't found the solution. Can anyone please help me out -
Django Broken on MacOS
I am working on a project on Django and I am facing an issue with it. I have done some migration wrong and decided to delete them from the project folder and rebuilt them. Since I did that Django is acting "like deleted one of its source files". The error occurs on every project I try to migrate, makemigration, runserver. I tried to reinstall django with pip but it does not help at all. I also delete the .pyc files but it did not help at all. I even generated new project but still ran on the same issue. I do think that is helpful but I have to mention that shell launches OK. The error Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x1049a38c8> Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 123, in inner_run self.check_migrations() File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 427, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/usr/local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 267, in build_graph raise exc File "/usr/local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 241, in build_graph self.graph.validate_consistency() File "/usr/local/lib/python3.6/site-packages/django/db/migrations/graph.py", line 243, … -
Define API for Django-Templates?
I think a template is comparable to a method. It does IPO (input-processing-output): it takes some input. it does some processing it outputs something. Most likely HTML. In Python a method has required and optional arguments (with default values). Is there a way to define (I call it) API for Django-templates? I want some arguments to be required. I want some arguments to have defaults. Use case: The customer can edit templates via a web interface. I want to tell the customer if is change to the template is valid or not. I could render the template see if an error happens, but this does not cover this case: The template should render the value "foo_needs_to_get_rendered". In this case validating the template by rendering (and discarding the result) does not show an error. Related: I would like to show the customer who edits the template a help message. I want to list all available variables of the context. Example: "You can use these variables: {{foo}}, {{bar}}, {{blue}} ..." -
How to either Create (if user commits input the first time) or update a ModelFormset in the same view
i am trying to let people submit their Availability times through a web form in Django. I am using a ModelFormSet for this. forms.py class AvailabilityForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['day'].initial = 'override' self.fields['shift'].initial = 'override' self.fields["available"].initial = 'override' self.fields["preference"].initial = 'override' self.fields["checker"].initial = 'override' shift = forms.CharField(max_length = 120,widget= forms.HiddenInput()) day = forms.CharField(max_length=120,widget= forms.HiddenInput()) available = forms.BooleanField(required = False) preference = forms.BooleanField(required = False) checker = forms.BooleanField() class Meta: model = Availability fields = ["day","shift","available","preference"] class AvailabilityFormset(BaseModelFormSet): def __init__(self,*args,**kwargs): super(AvailabilityFormset, self).__init__(*args,**kwargs) self.queryset = Availability.objects.none() AvailabilityFormSet = modelformset_factory(Availability, form=AvailabilityForm,formset=AvailabilityFormset, extra = 42,max_num=42) models.py class Availability(models.Model): employee = models.ForeignKey(to=User,on_delete=models.CASCADE) shift = models.CharField(max_length = 120) day = models.CharField(max_length=120) available = models.BooleanField(default=0) preference = models.BooleanField(default=0) checker = models.BooleanField(default=0) views.py @ login_required(login_url="/login/") def add_avail(request): formset = AvailabilityFormSet(request.POST or None, initial=availlist) if request.method =="POST": if formset.is_valid(): for form in formset: if form.is_valid(): instance = form.save(commit=False) instance.employee = request.user instance.save() context = {"formset": formset } return render(request,"addtimes.html",context) This setup works in that sense, that it does save the input and all the initial data. The problem is that it does create new entries, inistead of updating the already existing ones for that user. When i change the query set to filter for the logged … -
Could not perform concurrent requests using django
I've a django app which fetches data from mysql db whenever a request is received.This works fine when request is processed by one user but, when more than user send request, I get a error message saying "InterfaceError at url (0, '')". I'm using Django version 1.9. As per my research , I included CONN_MAX_AGE in my settings.py but still I got the same error. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), **'CONN_MAX_AGE': None** } } my models.py connection = pymysql.connect(host='localhost',user='user',password='password',db='db_name',port=3306,charset='utf8',cursorclass=pymysql.cursors.DictCursor) def execute(query): cur = connection.cursor() cur.execute(query) data = cur.fetchall() connection.commit() cur.close() return data def trending_assets(): sql = "select * from media_recommendation_engine.content_table t1 inner join (SELECT movieId,rank from" \ " media_recommendation_engine.asset_ranks limit 10) t2 on t1.movieId = " \ "t2.movieId order by t2.rank asc ;;" data = execute(sql) return data -
TypeError: Unicode-objects must be encoded before hashing What is wrong?
I got an error,TypeError: Unicode-objects must be encoded before hashing. I wrote codes, user = Data() passwd = request.data['password'] md5 = hashlib.md5() md5.update(passwd) user.password = md5.hexdigest() print(user.password) user.save() Traceback says Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/rest_framework/viewsets.py", line 95, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 494, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 454, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 491, in dispatch response = handler(request, *args, **kwargs) File "/opt/project/app/views.py", line 27, in create md5.update(passwd) I added #coding:utf-8 to top of the code,but same error happens.What is wrong in my codes?How should I fix this? -
Is it possible to return JSON data to django admin template
I want to change the data which get render to django admin template by json data. Is it possible? -
In Django's cache framework, is it possible to obtain the server's location of a given cache instance?
In the Django documentation, it is specified that a cache can be shared over multiple servers specified in the LOCATIONS option of the CACHES setting, as in the following example: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': [ '172.19.26.240:11211', '172.19.26.242:11212', '172.19.26.244:11213', ] }} My question is, if an exception occurs in the cache due to a problem in one of those servers, is there any way to retrieve the corresponding IP address of the server in which the exception happened? Thanks in advance -
Domain Driven Design Onion Architecture with Django Rest Framework
I have been reading recently about Domain Driven Design (DDD), I like the concept and especially the idea of Onion architecture goes with it (https://www.youtube.com/watch?v=pL9XeNjy_z4). I am quite curious to understand how such an architecture we can implement with Django Rest Framework or in other words can we do DDD with Django rest framework in Onion arch style? Is it possible to map the concepts in Onion architecture to DRF? As frameworks like Apache isis (https://isis.apache.org/) do DDD by building Object Oriented UIs where users can directly interact with domain entities, how DRF can possibly do such things? As an example I have writing DRF Code in following fashion: In models.py I would have my models defined: class Library(models.Model): library_id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) ... #This helps to print in admin interface def __str__(self): return u"%s" % (self.name) In serializers.py I would have my model serializers: class LibrarySerializer(serializers.ModelSerializer): class Meta: model = Library fields = '__all__' I will have corresponding url in urls.py: router.register(r'libraries', LibraryViewSet) and in views.py performing CRUD operations: class LibraryViewSet(viewsets.ModelViewSet): queryset = Library.objects.all() serializer_class = LibrarySerializer How would that relate to (perhaps with appropriate modifications) to DDD/Onion architecture? -
What are the advantages of using SendGrid Web API instead of SMTP as the transport mechanism for sending emails in Django?
In the Django Docs for SendGrid, it says: You may also send emails with Django by using the django-sendgrid-v5 library, which utilizes the Web API instead of SMTP as the transport mechanism. The use-case for my emails are simply verifying emails when users sign up for an account. -
How can I sandbox the JavaScript code for my ACE code editor? Django project
I'm making a website that allows the users to write HTML of JavaScript code (the website is made with Django). I'm using the ACE-editor. The ACE-editor is written in JavaScript. But now I have this problem: The JavaScript code, that is made by the user, effects the JavaScript code of the ACE editor. This often leads to crashing the website. I've heard about Sandboxing, but I don't really know how that works. Can someone tell me what possible solutions are for my problem? -
How can i display pdf in django which is stored in mysql database as blob?
In my web application, user can upload a pdf file and the same is stored in the mysql database itself. The file is stored in database using following codes. data=request.FILES['file'].read() fcursor = db.cursor() fcursor.execute("INSERT INTO REPORTS(DOC,id) VALUES(%s,%s)",(data,id)) db.commit() fcursor.close() db.close() User has provision to view this pdf. Now i transfer the pdf to template with the help of temporary files. c = db.cursor() c.execute("SELECT DOC FROM REPORTS WHERE id=%s",(id,)) file = c.fetchone()[0] c.close() f=tempfile.NamedTemporaryFile(dir='/tmp/',suffix='.pdf') f.write(filename) f.seek(0) response = HttpResponse(f, content_type='application/pdf') response['Content-Disposition'] = 'inline; filename="machsensor_report.pdf"' return response But actually, i wanna display pdf directly from the database, without using the temporary file. -
How to print dynamic content in Django template
I am new to python and django, Ian using paramiko module to get server cpu utilisation and I want to render that output in my html template. I can print output for a single server in html . But I am not able to print multiple servers output in html template. Example:- I have 100 servers I want to get all the servers cpu utilisation once I logind in my webpage. I am using CSV file with hostname and IP. In my views.py i am using for looop to read ips in CSV file . By using paramiko module I am getting output . I am using below request. Views.py For loop return render(request, 'personal/welcome.html', {'host':[hostname],'cpu':[cpu]} ) In my html template {{host}} {{cpu}} but I am able to print only last sever output which is last in CSV file. Please tell me is there any other way to print all servers output or can I save all server output in text file. and print it on same webpage. -
Django 1.11 template inheritance {% extends 'base.html' %} display error
Beforehand, thanks to everyone who could help. I'm having some strange behavior of the Django "template inheritance" - the main problem is {% extends 'base.html' %} in (menu.html) displays nothing in the target (base.html) document. And on the contrary - Django takes the header from base.html and loads it in the (menu.html), that is rather strange, taking into account the logic of inheritance. I've read all the similar questions, tried different approaches, but nothing... Anyway - the "include" tag works perfectly with all the templates. I'm having the Django 1.11.11 with python 3.6.4 on windows 10. Let me list the documents itself: menu.html: {% extends 'base.html' %} {% block title %} Some text {% endblock %} base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% block title %} {% endblock %} </body> </html> Urls.py from django.conf.urls import url from django.contrib import admin from linguistic import views from linguistic.views import index, menu, about, contact urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index), url(r'^menu/$', views.menu), url(r'^about/$', views.about), url(r'^contact/$', views.contact), ] Views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request, 'base.html', {'foo':'bar'}) def about(request): return render(request, 'about.html') def contact(request): return render(request, 'contact.html') def menu(request): return render(request, 'menu.html', … -
Getting Import Error for _ARC4.so: undefined symbol: PyUnicodeUCS2_FromString
I have configured my django with apache and all the configurations seems to be ok. Ubuntu system 14.04(server). While i am getting the import error as shown in below. Please help to sort out issue. Django Version: 1.10.7 Exception Type: ImportError Exception Value: /usr/local/lib/python2.7/site-packages/Crypto/Cipher/_ARC4.so: undefined symbol: PyUnicodeUCS2_FromString Exception Location: /usr/local/lib/python2.7/site-packages/Crypto/Cipher/ARC4.py in , line 66 Python Executable: /usr/local/bin/python -
django-widget-tweaks with django custom tags
I am using django-widget-tweaks to render my django form fields. Now I need to show the return value of a custom django tag as the value of my render field. This is my template tag from forex_python.bitcoin import BtcConverter @register.simple_tag def btc_price_in_sgd(): coin_obj = BtcConverter() price = coin_obj.get_latest_price('SGD') return price I used the return value of this filter as my form input field here is the code I used to show in template {% render_field exchange_form.price class="form-control" value=btc_price_in_sgd %} but this is not working -
How to get fname and lname in a custom Model after Extending it from django's User Model
I have User model class which is in accounts.models. I have then created an Employee class in hr.models and I have added user as a ForeignKeyField. How do I make it possible to implement a method in Employee class to view both first and last name? class User(AbstractUser): additional_info = models.CharField(max_length=100, null=True, blank=True) provider = models.ManyToManyField('self', related_name='rel_doc') def __str__(self): return "%s %s (%s)" % (self.first_name, self.last_name, self.username) In hr.models: class Employee(models.Model): user = models.ForeignKey(User, related_name='users', on_delete=models.CASCADE) gender = models.ForeignKey(Sex) dob = models.DateField(blank=True, null=True) company = models.ForeignKey( 'hr.Company', verbose_name='Company', related_name='companies', null=True, blank=True, ) def __str__(self): return str(self.user) -
using Angular4 post image in Django API get error data was not file
This is my angular front-end using this i try to send image in Django API this Is my Home.component.ts import { Component, OnInit } from '@angular/core'; import { Http, Response, Headers} from '@angular/http'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { constructor(private http: Http) { } homeObj:object = {}; image = []; addSaveData = function(home){ this.homeObj = { "image" : home.image } let _url:string = 'http://127.0.0.1:8000/Home/Homemodel/'; this.http.post(_url, this.homeObj).subscribe(( res:Response) =>{ console.log(res); }) } ngOnInit() { } } this is my home.component.html this is my simple form design and create function addSaveData using this function i try to post image <div id="headder" class="container"><h3>POST METHOD</h3></div> <form class="container" id="formNewPost" name="formNewPost" #postData = "ngForm" (ngSubmit) = "addSaveData(postData.value)"> <input type="file" name="image" id="image" ngModel> <input class="btn btn-primary" style="float: right;margin-bottom:15px;" type="submit" value="POST"> </form> -
Django: How to access a file uploaded from another function?
I am totally newbie to Django and Web development, please help me. I have two functions: def uploadFile(request): """ this function submits an upload request from the page, and store the upload file to the database. """ def DoSomething(request): """ this function parse the file uploaded from the function above. """ I think in the first function, the uploaded file is a local variable, but which will be used in the second function immediately. Both functions bind to a button. Here comes the problem, how should the file be passed from the first function to the second function? Thanks for the help in advance, any suggestion or hints are appreciated. -
Django want Google O-Auth2 put in redis
i used redis 4.0.8 , mac 10.13 , django 2.0.2 , social-auth-app-django urls.py from django.contrib import admin from django.urls import path from django.conf.urls import url, include from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), url(r'', include('blog.urls')), url('', include('social_django.urls', namespace='social')), ] settings.py import os import json from django.core.exceptions import ImproperlyConfigured BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = "mykey" SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = "mysecret" SOCIAL_AUTH_URL_NAMESPACE = 'social' SECRET_KEY = 'secret' 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', 'social_django', 'blog', ] 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 = 'authtest.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'authtest.wsgi.application' TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.static', 'django.core.context_processors.tz', 'django.contrib.messages.context_processors.messages', 'social.apps.django_app.context_processors.backends', 'social.apps.django_app.context_processors.login_redirect', ) AUTHENTICATION_BACKENDS = [ 'social_core.backends.google.GoogleOAuth2', # Google 'django.contrib.auth.backends.ModelBackend', # Django ] LOGIN_REDIRECT_URL='/' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Seoul' … -
Read Javascript date input in Django
I have a calendar/datepicker done in Javascript that creates an input of the following format "Thu Mar 29 2018" On submit, I want to read the date in a Django date field, but it fails. What solutions do I have ? -
ImportError: No module named urls, django 1.8
Main urls.py urlpatterns += [ #url(r'', include('apps.api.urls')), url(r'^api/core/', include('core.urls')), ] core/urls.py urlpatterns=[ url(r'^/users/', core_view.userlist), ] url i am trying to hit http://localhost:8000/api/core/users For this i am getting 'ImportError' as ImportError at /api/core/users No module named urls Request Method: GET Request URL: http://localhost:8000/api/core/users Django Version: 1.8 Exception Type: ImportError Exception Value: No module named urls Exception Location: /usr/local/lib/python2.7/dist-packages/rest_framework/compat.py in <module>, line 26 Python Executable: /usr/bin/python Python Version: 2.7.12 what is wrong in conf? -
How can I change password into hash?
I am making Django applications.I am using Django Rest Framework.models.py is class Info(models.Model): username = custom_fields.NotEmptyCharField(max_length=100, unique=True) email = models.EmailField() password = custom_fields.NotEmptyCharField(max_length=100) serializers.py is class InfoSerializer(serializers.ModelSerializer): created_time = serializers.DateTimeField(required=False) updated_time = serializers.DateTimeField(required=False) views.py is class InfoViews(viewsets.ModelViewSet): queryset = Info.objects.all() serializer_class = InfoSerializer def create(self, validated_data): user = get_user_model(**validated_data) user.set_password(validated_data['password']) user.save() urls.py is urlpatterns = [ path('users/', views.InfoViews.as_view({ 'get': 'list', 'post': 'create' })), ] When I post new user data, user = get_user_model(**validated_data) TypeError: get_user_model() argument after ** must be a mapping, not Request error happens.I searched s://stackoverflow.com/questions/33205045/create-argument-after-must-be-a-mapping-not-unicode ,so I found maybe necessary thing is not in serializer.py but I really cannot understand how to fix this.What is wrong in my code?How should I fix this?