Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why we are using @property decorator in Django?
As we know Django provides several decorators that can be applied to views to support various HTTP features. I've seen property but unable to understand why it's needed? class Test(object): @property def hi(self): return "hello" Test().hello # 'Hello, world!' Thanks in advance. -
Does Django multiple database support generate tables for only some specific apps in a database
I aim to store history of tables using django-simple-history library in a seperated database from the main one. When I run migrate --database=the_second_db, django generates all tables for all apps in the second database. How can I make it just generate some specific tables for specific apps that I need in the second database( history tables)? -
Django: Saving in Many To Many Field by adding new data in field
I have a model of Products that can be saved/owned by Users. class Product(models.Model): owner = models.ManyToManyField(User, blank=True) The original owner of the product is Adam. However I would like to allow another user, Eve to own the product as well. def saveProd(request, product_slug): if request.method == "POST": product = Product.objects.get(slug=product_slug) product.owner = request.user ***product.save()*** return redirect('home:saved') But I can't use product.save as it will change the owner in the ManyToMany Field. I just want another user added to the owner. How should I finish the code? Thank you. -
How to modify my poll app models in quiz app?
from django.db import models import time from django.utils import timezone # Create your models here. class Question(models.Model): question_text=models.CharField(max_length=200) pub_date=models.DateTimeField('date published') def __str__(self): return self.question_text # def was_published_recently(self): # return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question=models.ForeignKey(Question, on_delete=models.CASCADE) choice_text=models.CharField(max_length=200) vote=models.IntegerField(default=0) def __str__(self): return self.choice_text Above code is poll app there are a question has multiple choices and a vote field this is countable, but i want to make quiz app since how to modify this models for making quiz app model? -
Django permissions group by model
I want to make structure like below modelName View Add Change Delete Group Y Y Y Y User Y Y Y Y I seeking data by using user = User.objects.get(username='test') perm = Permission.objects.filter(Q(group__user=user)|Q(user=user)).distinct() Now returning Model Permission log entry view_logentry Demo change_demopurpose group add_group group change_group group delete_group But need to grouping -
adding highlighted code snippets into posts in django
I created a blog in django where i upload posts. so , sometimes you need to add code snippet for the better understanding. for that i used some code highlighting techniques like prismjs and markdown. Now i can upload a code snippet using "pre" and "code" tags like this i am using right now. <pre><code class="language-python"> {% autoescape on %} {{ snippet.code }} {% endautoescape %} </code></pre> and look at my post detail file... <div align="left"> <p>{{ obj.content|capfirst|linebreaks }}</p> </div> now what is want is while writing post i should be able to add snippets in between the text content and also should be able to write content afterwards. means a post contains a paragraph and then code snippet and then paragraph again and continue. -
How to call a method from a Django Class Model to a Django field?
I have created the following Django Model and I am trying to initialize one field - points - with the total number of instances of that same model, that is: class Task(models.Model): DEFAULT_VALUE = 5 description = models.CharField(max_length=60) points = self.total() * DEFAULT_VALUE STATUS = (('A', 'Active'), ('C', 'Cancelled'), ('D', 'Done')) status = models.CharField(max_length=1, choices=STATUS, default='A') def total(self): count_active = len(Task.objects.filter(status='A')) return count_active In the python manage.py shell I can create two instances of Task and I can determine the total number of the instances that have been created with len(Task.objects.filter(status='A'))), however, when I try to implement this same code into a function then I encounter that self is an unresolved reference. What did I miss? -
How to display user computer display name in #Djangos, #python
Apologies if its duplicate query, I am not able to find the answer for my question posting here. I have developed a webpage in Djangos hosted in development server. Webpage is accessible for anyone outside the development box. requiremnet: when User access website, top right corener I want to display user computer name.(note: I am not asking users to register). I wrote below code which is fetching user Name, but it alwyas shows admin display name from develoment box. how to get user computer name where ever the webpage is opened in my LAN. ///view.py import ctypes def get_display_name(): GetUserNameEx = ctypes.windll.secur32.GetUserNameExW NameDisplay = 3 size = ctypes.pointer(ctypes.c_ulong(0)) GetUserNameEx(NameDisplay, None, size) nameBuffer = ctypes.create_unicode_buffer(size.contents.value) GetUserNameEx(NameDisplay, nameBuffer, size) return(nameBuffer.value) def home_page(request): context = { "username":request.user.username, } return render(request,"default.html", context) //default.html <div>{{username}}</div> -
django-channels websocket bridge error when trying to connect web socket
Im trying to implement real time notifications in my django app.I have set up signals and consumers . Im getting an error in the javascript side My javascript code: <script> document.addEventListener('DOMContentLoaded', function() { const webSocketBridge = new channels.WebSocketBridge(); const nl = document.querySelector("#nl"); webSocketBridge.connect('student/dashboard/tasks/'); webSocketBridge.listen(function(action, stream) { console.log("RESPONSE:", action); if(action.event == "New Task") { var el = document.createElement("li"); el.innerHTML = ` <b>${action.username}</b> completed Task ${action.title}`; nl.appendChild(el); } }) document.ws = webSocketBridge; /* for debugging */ }) </script> The error shows on the console : TypeError: Invalid WebSocket constructor. Set `options.constructor -
I want to create a signup form to register a user by verifying weather the user is existed or not in the sqlite3 database
I want to create a signup form to register a user by verifying weather the user is existed or not in the sqlite3 database. here is my root urls.py file: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('orphanageoperations.urls')), ] sub url file: from django.urls import path from .import views urlpatterns=[ path('',views.orphanage_main_page,name='orphanage_main_page'), path('signup.html',views.signup,name='signup'), path('login.html',views.login,name='login') ] views.py file from django.shortcuts import render from .forms import SignupForm def signup(request): if request.method=='POST': form=SignupForm(request.POST) if form.is_valid(): form.save(commit=True) else: form=SignupForm() return render(request,'orphanageoperations/signup.html',{}) models.py from django.db import models from django.utils import timezone from django.conf import settings # Create your models here. class Signup(models.Model): username=models.CharField(max_length=20); usermail=models.CharField(max_length=20,primary_key=True); userph=models.CharField(max_length=13); userpwd=models.CharField(max_length=20); def createUser(self): self.username; self.usermail; self.userph; self.userpwd; forms.py from django import forms from .models import Signup class SignupForm(forms.ModelForm): class Meta: model= Signup; fields=('username','usermail','userph','userpwd',); signup.html <!DOCTYPE html> <html> <head> <title>Signup</title> <meta charset="uts-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script> function validate_signup_form(){ var username=document.getElementById("name").value; var mobilenum=document.getElementById("phno").value; var mailid=document.getElementById("userMail").value; var password=document.getElementById("pwd").value; if(username==""){ alert("Please Enter the username"); return false; } if(mobilenum==""){ alert("Please Enter mobile number"); return false; } if(mailid==""){ alert("Plese enter your mail id"); return false; } if(password==""){ alert("Plese enter your password"); return false; } } </script> </head> <body> <div class="container"> <br … -
I am getting an error : rest_framework.request.WrappedAttributeError: 'CSRFCheck' object has no attribute 'process_request'
from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from .views import home from posts.views import PostListView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', PostListView.as_view(), name='home'), url(r'^post/', include('posts.urls', namespace='post')), url(r'^api/post/', include('posts.api.urls', namespace='post-api')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) api/views.py from rest_framework import generics from posts.models import Post from .serializers import PostModelSerializer class PostListAPIView(generics.ListAPIView): serializer_class = PostModelSerializer def get_queryset(self): return Post.objects.all() api/serializers.py from rest_framework import serializers from posts.models import Post class PostModelSerializer(serializers.ModelSerializer): class Meta: model = Post field = [ 'user', 'content' ] api/urls.py from django.conf.urls import url # from django.contrib import admin # from django.conf import settings # from django.conf.urls.static import static # from .views import home from .views import PostListAPIView from django.views.generic.base import RedirectView urlpatterns = [ # url(r'^(?P<pk>\d+)/update/$', PostUpdateView.as_view(), name='update'), # url(r'^(?P<pk>\d+)/delete/$', PostDeleteView.as_view(), name='delete'), # url(r'^(?P<pk>\d+)/$', PostDetailView.as_view(), name='detail'), url(r'^$', PostListAPIView.as_view(), name='list'), #/api/tweet # url(r'^$', RedirectView.as_view(url='/')), # url(r'^create/$', PostCreateView.as_view(), name='create'), ] views.py from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from .views import home from posts.views import PostListView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', PostListView.as_view(), name='home'), url(r'^post/', include('posts.urls', namespace='post')), url(r'^api/post/', include('posts.api.urls', namespace='post-api')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) enter image description here -
Django Throws 500 Internal Server Error instead of 404 on ElasticBeanstalk
I'm running a Django 2.1+ app and having an issue getting the 404 page to show up correctly on in my Elasticbeanstalk Environment. I'm able to get the 404 page to show correctly on my local environment and I believe I'm setting the ALLOWED_HOSTS file correctly according to everything else I've read. But for some reason I continue to get a 500 internal error page. I also have the app setup to email when an internal error occurs that is not caught. The errors that come back don't contain any kind of trace. It more or less just lists out my configuration file and tells me there was a server error. I've read through as many of the other stackoverflow issues related to this, but they all seem to be either missing ALLOWED_HOSTS or missing a 404.html template, but from what I've read I don't need that in Django 2.1+. Also, like I said above I'm able to get this to work locally just fine with Debug=True and Debug=False. Any suggestions would be greatly appreciated. Thank you. -
Django collectstatic does not work on nested directories of assets
I have an HTML template for my website, which has its own directory structure for JavaScript, CSS and images. My directory structure is like this: ِDirectory Structure My_Project/ |-Include/ |-Lib/ |-Scripts/ |-src/ | | | |--static_my_proj/ | | | ---assets/ | | | |----app/ | | | |----demo/ | | | |----snippets/ | | | |----vendors/ | |--templates/ | |--My_Projects/ |-static_cdn/ | |--static_root/ There are some static files under the "app," "demo," "snippets" and "vendors" directories and their sub-directories. My configurations on the "settings.py" are as below: STATICFILES_DIR = [ os.path.join(BASE_DIR, "static_my_proj") ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "static_root") The problem is that when I use "python manage.py collectstatic" command, static files under the sub-directories of "static_my_proj" directory, will not be copied to "static_cdn/static_root/" path. The output on the "static_cdn/static_root" path, only contains "admin" directory and its subsequent "css," "fonts," "img," and "js" directories; there is not any sign that which shows the command ports the statics from the "assets" directory to defined destination. Any idea? -
django-elasticsearch-dsl unable to filter with mulitiple model fields
models.py class PostJob(models.Model): job_title = models.CharField(max_length=256) job_description = models.TextField() key_skills = models.TextField() def __str__(self): return self.job_title documents.py from django_elasticsearch_dsl import DocType, Index from .models import PostJob jobs = Index('jobs') @jobs.doc_type class JobsDocument(DocType): class Meta: model = PostJob fields = [ 'job_title', 'job_description', 'key_skills', ] views.py from .documents import JobsDocument def search_jobs(request): q = request.GET.get('q') if q is None: return JsonResponse({"code":500,"msg":"query sting not found"}) if q: Q = JobsDocument.search().query jobs = Q("match", key_skills=q) or Q("match", job_title=q) lst=[] dict ={} for i in jobs: dict["job_title"] = i.job_title dict["description"] = i.job_description dict["key_skills"] = i.key_skills lst.append(dict.copy()) return JsonResponse(lst,safe=False) in django using 'django-elasticsearch-dsl' i am trying to search with multiple model fields. here i wants to filter with multiple fields with key_skills and job_title but it is coming with only key_skills but doesn't matches with job_description for job_title if my job_title job python developer it is not coming if i am searching only developer. it is coming when i am searching python developer completely with white space Please have a look into it.. -
Change Passwod API using Django Custom user model and serializer
I have a Django application hwere I have extended the User model and created a custom user model for registration/login, now I want to implement a Change Password API which will be used in Android/IOS app development. I would get parameters as: user_id, old_password, new_password Using these paramters and custom user model and serializer is there any way I could achieve this. I have tried a sample example for this, but it failed. Custom Model: class User(AbstractBaseUser, PermissionsMixin): objects = UserManager() name = models.CharField(max_length=100, blank=True, null=True) email = models.EmailField(unique=True) created_at = models.DateField(blank=True, null=True, auto_now=True) phone_no = models.CharField(max_length=14, blank=True, null=True) user_android_id = models.CharField(max_length=255, blank=True, null=True) user_fcm_token = models.CharField(max_length=255, blank=True, null=True) user_social_flag = models.IntegerField(blank=True, null=True) user_fb_id = models.CharField(max_length=255, blank=True, null=True) user_android_app_version = models.CharField(max_length=25, blank=True, null=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) USERNAME_FIELD = 'email' def __str__(self): return self.email User Manager: class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, email, name, phone_no, created_at, user_android_id, user_fcm_token, user_social_flag, user_fb_id, user_android_app_version, password=None): cache.clear() user = self.model( email=self.normalize_email(email), phone_no=phone_no, created_at=created_at, user_android_id=user_android_id, user_fcm_token=user_fcm_token, user_social_flag=user_social_flag, user_fb_id=user_fb_id, user_android_app_version=user_android_app_version, name=name, ) user.is_admin = False user.is_staff = True user.is_superuser = False user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, name, created_at, phone_no, user_android_id, user_fcm_token, user_social_flag, user_fb_id, user_android_app_version, password): … -
Real Time Notifications in django
I have a few types of notifications in my django project and as of now they are worked out using signals and the notifications are displaying correctly but it is not made real time. What is the best way to implement real time notifications in django?I have done a messaging app with django channels.Is django channels the best way to proceed? -
Default children plugins on custom plugin
I have a custom plugin called MultiColumnResponsive that receives the number of columns as parameter and accepts ColumnResponsive plugin only as children. I want to create the ColumnResponsive plugins nested as children by default, but I am not able to do it. Here my current code: cms_plugins.py class MultiColumnResponsivePlugin(CMSPluginBase): name = "Multi Column Responsive" module = _("Containers") model = MultiColumn render_template = "plugin/multi-column-responsive/multi-column-responsive.html" allow_children = True child_classes = ["ColumnResponsivePlugin"] def render(self, context, instance, placeholder): context = super(MultiColumnResponsivePlugin, self).render(context, instance, placeholder) return context class ColumnResponsivePlugin(CMSPluginBase): name = "Column Responsive" module = _("Containers") render_template = "plugin/column-responsive/column-responsive.html" allow_children = True parent_classes = ["MultiColumnResponsivePlugin"] def render(self, context, instance, placeholder): context = super(ColumnResponsivePlugin, self).render(context, instance, placeholder) return context models.py class MultiColumn(CMSPlugin): NUM_OF_COLUMNS = ( (1, '1'), (2, '2'), ) num_of_columns = models.IntegerField(default=1, choices=NUM_OF_COLUMNS) This is the desire result when I add a MultiColumnResponsive plugin with 2 columns: -
How to stop browser caching in Django?
The site i am building is being cached by browser.So when i make any changed in back-end or front-end i need to hard refresh the respective page to see the changes. In order to stop it i used @never_cache as described in django documentation but seems like its not preventing browser to cache page. Then i tried ajax cache false! $.ajax({ url: "/getData", method:"GET", cache: false }).done(function (res) { alert("Success"); }); Still not effective! Can any body help me in solving this problem? -
Django POST request from Postman
I am currently stuck with POST requests in Django. I am trying to send a POST request from an external applications such as smartphones or Postman (not forms) to the rest framework. Get requests work just fine. I went through many posts but couldn't resolve my issue. I tried to use request.body but always get an empty response. I used print(response.body) to print the output to the console and only get b'' back. class anyClass(APIView): def post(self, request): print(request.body) return Response({"id": 'anyClass', "data": '1234', }) How would I get the data from my request? My post request sent with Postman: http://127.0.0.1:8000/test/v2/Api/anyClass?qrcode=100023&date=2018-11-27&time=08:00:00&value_1=17 -
what is the difference between API and Website?
I know this is a very dumb question but i couldn't find any satisfactory answer on this . Let me elaborate to you my problem. I made a simple blogging website with Django. so , should i call this website a web app or API or just a website? Does API's and websites are same ? Is Django app and Django website and Django API same thing ? -
LinkedIn OAuth API version 2 updated in social_core but not working
I am using python-social-auth to let users log in with LinkedIn OAuth2 and updated the url as follows. linkedin.py AUTHORIZATION_URL = 'https://www.linkedin.com/oauth/v2/authorization' And set the redirect url to http://localhost:8000/oauth/complete/linkedin-oauth2/ In settings.py INSTALLED_APPS = [ ... 'social.apps.django_app.default', ...] EMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ ... 'social.apps.django_app.context_processors.backends', 'social.apps.django_app.context_processors.login_redirect', ], }, }, ] Finally, set the redirect urls to http://localhost:8000/oauth/complete/linkedin-oauth2/ What's missing here? -
Displaying all entries of a model that is linked to another model by a foreign key in Django
I'm learning Django and am trying to work through an exercise in making a small app. The requirements are are making an HR app that is supposed to display links on a login landing page to users based on a user's role within the company. My main question is if there is a way in Django to set up the logic in my template to display all the entries that are related between my models. To clarify a little, right now my current thinking is to set up my models like this: class Role(models.Model): title = models.CharField(max_length=200) def __str__(self): return self.title class CustomUser(AbstractUser): role = models.ForeignKey(Role, on_delete=models.DO_NOTHING, null=True) def __str__(self): return self.username class RoleLink(models.Model): role = models.ForeignKey(Role, on_delete=models.CASCADE) title = models.CharField(max_length=200) link = models.URLField() def __str__(self): return self.title Basically, one Role can have many Users, and also one Role can have many different RoleLinks and they can all be edited in the Django admin page. So for example, if I have a user 'PaulAllen1' with a role of 'sys-admin', when PaulAllen1 logs in, the landing page template should display all the links that are related to the 'sys-admin' role that I have set up like this. RoleLink model in the … -
how to implement views for chained dropdown list using djangorestframework
I have three models 1) Programme class Programme(models.Model): name = models.CharField(max_length=50 , unique=True) 2) Branch class Branch(models.Model): name = models.CharField(max_length=50, unique=True) programme = models.ForeignKey( 'Programme', related_name='branches', on_delete=models.CASCADE) 3)Scheme class Scheme(models.Model): name = models.CharField(max_length=50, unique=True) programme = models.ForeignKey('Programme', on_delete=models.CASCADE, related_name='schemes') branch = models.ForeignKey( 'Branch', on_delete=models.CASCADE, related_name='schemes') I want to create a serializer and a viewset for chained drop downlist selection of scheme will depend on filtered selection 1) selection of programme 2) selection of branch 3) selection of scheme anyone know how to do this using Djangorestframework -
Why can I access gdal in my python 3.6 shell but not my django shell
I have a django project that I want to use gdal in. I have installed all the dependencies and it works fine if I do: $ python3.6 Python 3.6.7 (default, Oct 22 2018, 11:32:17) [GCC 8.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from osgeo import gdal >>> gdal <module 'osgeo.gdal' from '/usr/lib/python3/dist-packages/osgeo/gdal.py'> but when I do: $python manage.py shell Python 3.6.7 (default, Oct 22 2018, 11:32:17) [GCC 8.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from osgeo import gdal Traceback (most recent call last): File "<console>", line 1, in <module> ModuleNotFoundError: No module named 'osgeo' It appears both are using the same python so I am not sure what the problem is. Could it be a path problem? -
Django models.py OneToOneField --- help creating a relationship between two models
I am having trouble testing a relationship between two models (CustomUser and Profile) located in different apps. I'm hoping someone can identify where I am going wrong here: Here is my profiles/models.py --- you can see my user field attempting to create a OneToOne with with my users/models.py: from django.db import models from core.models import TimeStampedModel class Profile(TimeStampedModel): user = models.OneToOneField('users.CustomUser', on_delete=models.CASCADE) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) bio = models.TextField(blank=True) image = models.URLField(blank=True) def __str__(self): return self.user.username Here is my users/models.py: class CustomUser(AbstractBaseUser, PermissionsMixin, TimeStampedModel): username = models.CharField(db_index=True, max_length=255, unique=True) email = models.EmailField(db_index=True, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_provider = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = CustomUserManager() def __str__(self): return self.email @property def token(self): return self._generate_jwt_token() def get_short_name(self): return self.username def _generate_jwt_token(self): dt = datetime.now() + timedelta(days=60) token = jwt.encode({ 'id': self.pk, 'exp': int(dt.strftime('%s')) }, settings.SECRET_KEY, algorithm='HS256') return token.decode('utf-8') So the idea is that when I create a new user, a profile is automatically created as well. To do this, I am using a post_save signal in my users app: users/signals.py: from django.db.models.signals import post_save from django.dispatch import receiver from conduit.apps.profiles.models import Profile from .models import User @receiver(post_save, sender=User) def create_related_profile(sender, instance, …