Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating a webclient to send and receive emails
I have to create a webclient to send and receive emails from gmail and outlook accounts. It should be able to run directly in a browser with any setup on the computer. Here are the important details: I have planned to use imaplib and smtp library in python. It will be a django project. I will use react for the frontend. And mondodb to store some data in a database. And aws for deployment. The webclient will be used by approximately 10 people. The webclient will have many functionalities not available in other clients. So my question is, Is it possible to create such webclient or am i missing anything like protocols, security or hardware requirements? You might find this question as not exactly related to programming, but it is important for me to get an answer. As I am new to djando and mongodb, i want to make sure that I don't waste my time trying to create something which is not possible. -
Django: How can I create a group in django similar to a Facebook group?
Hello guys I am quite new to django. I am thinking of creating a group like feature where a user can create a group and be an admin and can add other users to the group similar to a facebook group. How to do this with django? any leads or a rough idea to start with will be much appreciated. Thanks -
Ajax POST request 200 but Form is not valid
I am working to add comments and replies via Ajax and the POST.request is ok however the form itself is not valid hence no data is being saved in the DB. Please see below some of my code: Views def view_post(request, slug): post = Post.objects.get(slug=slug) comments = post.comments.filter(approved_comment=True, reply=None).order_by('-date_posted') form = CommentForm() if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) reply_id = request.POST.get('comment_id') data = None if reply_id: data = Comment.objects.get(id=reply_id) comment.author = request.user comment.post = post comment.reply = data comment.save() else: print('form not valid') else: form = CommentForm() context = { 'post' : post, 'comments' : comments, 'form' : form } if request.is_ajax(): html = render_to_string('blog/comments.html', context, request=request) return JsonResponse({ 'form' : html }) return render(request, 'blog/post.html', context) and here is the Ajax request $.ajax({ method: 'POST', url: `/post/${slug}/`, data: $(this).serialize(), dataType: 'json', success: function(response) { $(event.target).parents('.reply-form').hide() $('main-comment-section').html(response['form']); $('textarea').val(''); }, error: function(rs, e) { console.log(rs.responseText); }, }) event.preventDefault(); }) I would appreciate any guidance. Thanks! -
How can I position an icon next to a label in a crispy modelform?
I have a modelform and append a font awesome icon next to the first_name field: class StudentForm(forms.ModelForm): class Meta: model = Student fields = ['first_name',] def __init__(self, *args, **kwargs): ... self.helper.layout = Layout( AppendedText('first name', mark_safe('<span class="fas fa-user"></span>')), } How can I appen an icon to the fields label? I want to append a help icon which the user can click on to get hints on the field. -
Handling multiple types of users in Django
I am building a django app that will need to have two types of accounts (Merchant and Buyer), not that it matters but just to provide more context, on my sign up page, I have a radio button to let the user choose if they want to register as a Merchant account or as Buyer account, and each account type will have a separate sign in page to login to the website. I was thinking of using this approach. Please ignore discrepancies in the code, it was simplified just for the question. class User(AbstractBaseUser): first_name = models.CharField() last_name = models.CharField() date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) class Merchant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(unique=True) ph_number = models.CharField() class Buyer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(unique=True) As you can see each account can have unique fields like the ph_number so I came up with this approach after some research. Question 1 While inheriting AbstractBaseUser I need to have a uniquely identifiable field to assign to USERNAME_FIELD, in my case I don't really have one for the User, so what do I use here? I intend to have two custom authentication back-ends to use the email field from the Merchant … -
How to send request ` update view` from django rest_framwork
I'm doing a project - where the front-end vuejs and back-end drf - It works after I request a gate on my api, but when someone clicks on my content, there will be one view count and the property name of my api's view account will change one by one - but it doesn't move. Because the post method is the second time that the value is not updated - What can be done for this -
ImportError: cannot import name 'cmdoptions' from 'pip._internal.cli'
Has anyone seen this particular error, "ImportError: cannot import name 'cmdoptions' from 'pip._internal.cli'"? This preventing any pip installs. Is there a fix for this. I am currently running python 3.8. Thanks!! -
Changing property on model when all foreign key objects have property set to true
I am just starting with django, django rest api. And I created first easy Todo app in django rest API. I was wondering how i would achieve changing Task Complete status to true automatically if all subtasks are completed Thanks in Advance for all answers -
how to insert in parent model if i add in chield model in django using django admin
i have 3 Models as the follwing: 1- parent models "Batches" contain id & tabel name class Batch(models.Model): table_name = models.CharField(max_length=255) 2- Chield model 1 "Table 1" class Table1(models.Model): text = models.CharField(max_length=255) batch_num = models.ForeignKey(Batch, on_delete=models.CASCADE) 3- Chield model 1 "Table2" class Table2(models.Model): text = models.CharField(max_length=255) batch_num = models.ForeignKey(Batch, on_delete=models.CASCADE) i need if add any transaction in table1 or table2 cereat transaction in parent model "Batch" and fill class name in parent table. is there any good idea to make this throug django admin note: i tried TabularInline but this is work when i add parent frist then allocate chield to parent. -
Change default permissions for Users
I want to change the default permissions for Users so that they are only permitted to delete other objects that they created themselves. Currently, they are permitted to delete anything. How do I change the model so that they are only permitted to delete only the objects they created and not objects that other Users created? -
Access Nested Data from JSONField in Django
I have the following model: class BaseTransaction(models.Model): """Model to store JSON data""" name = models.CharField(max_length=255) json_data = JSONField(null=True) If I create an instance with the following data: base_transaction = models.BaseTransaction.objects.create( name="Test Transaction", json_data={{"sales": 3.24, "date": "2020-06-05"}, {"sales": 5.50, "date": "2020-06-04"}, {"sales": 256.53, "date": "2020-06-02"}} ) How would I access the second row of data without a key? Or is this the wrong format for JSON? I am using this format because the original data is from a CSV and this is how it converts to JSON. -
how to deploy a system built with angular and django on Centos7?
I'm trying to deploy an application that I built using AngularJS for frontend and Django for backend on Centos7, but when I get both, frontend and backend, on the server, I can only connect to angular page, but it do not make the request to the django API endpoint. On development environment both work correctly, angular running on localhost:4200 and django on localhost:8000 but when on server they do not comunicate. How should I deploy both of them to make they communicate? -
autocomplete fields in Django
Trying to set up autocomplete_fields in django. I have following model: from django.db import models class Genre(models.Model): title = models.CharField(max_length=255) class Movie(models.Model): title = models.CharField(max_length=255) year = models.IntegerField() time = models.CharField(max_length=255) director = models.CharField(max_length=255) genre = models.ManyToManyField(Genre) image = models.ImageField(upload_to='images/') actors = models.TextField() summary = models.TextField() admin.py: from django.contrib import admin from .models import Movie, Genre class SettingAdmin(admin.ModelAdmin): search_fields = ['genre'] class MovieAdmin(admin.ModelAdmin): autocomplete_fields = ['genre'] admin.site.register(Movie, MovieAdmin) admin.site.register(Genre) Error Message: Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\ali\appdata\local\programs\python\python38\lib\threading.py", line 932, in _ bootstrap_inner self.run() File "c:\users\ali\appdata\local\programs\python\python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Ali\Desktop\cinemaEnv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Ali\Desktop\cinemaEnv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Ali\Desktop\cinemaEnv\lib\site-packages\django\core\management\base.py", line 441, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: <class 'movies.admin.MovieAdmin'>: (admin.E040) ModelAdmin must define "search_fields", because it's referenced by MovieAdmin.autocomplete_fields. i try this code with User model from django.contrib.auth.models and it worked. i try this code with User model from django.contrib.auth.models and it worked. -
How to implement download data option for web app
I am developing a feature to a web app ( dictionary-like app ) - a download option. It means that a user can request to download data ( of certain models ). As a reference I can mention the download button here https://wals.info/languoid. I want to keep the files that I want to download up to date and it consists of millions of record. Example... I want to download all the words of English language in some format (word, csv etc). Querying everything from the db would be impossible as it would take a lot of time. I am using Django framework with a postgreDB. Can you suggest me some efficient way of approaching that. -
How do i specify the version of a module(django) on atom?
I'm trying to run a code I imported from github on my laptop. I think i know where the problem is; as the code is using django v2, and when I do : python -m django --version on my laptop it tells me I'm running on django v1. I installed django v2 but can't "connect it". I guess my problem is in the path taken, could anyone help? -
Getting Forbidden (CSRF token missing or incorrect.): /accounts/login while making post request through postman
I am trying to login to my user model in django using postman views.py from django.shortcuts import render from rest_framework.viewsets import ModelViewSet from useraccount.serializer import UserSerializer from useraccount.models import User class UserViewSet(ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() urls.py from django.urls import path,include from rest_framework.routers import DefaultRouter from useraccount.views import UserCreateViewSet from django.contrib.auth.views import LoginView user_router = DefaultRouter(trailing_slash=False) user_router.register('user',UserCreateViewSet) user_router.register('signup',UserCreateViewSet) urlpatterns = [ path('',include(user_router.urls)), path('login',LoginView.as_view()), ] when trying using postman providing the username and password i am getting Forbidden (CSRF token missing or incorrect.): /accounts/login i am using default auth.view to login like LoginView i am not using any kind of authentication method like basicauth,tokenauth or session auth while working with django rest framework please tell me if while dealing with rest framework i have to use one of the above three method of auth or if not necessary then how to deal with this problem in postman -
Creating a List of forgein keys in django model
I'm trying to make 2 models in Django that are interconnected one called pathways and one called courses. I wrote a Json file, that I was hoping to use load data on, where the tables are set up like this courses: "code": 1964, #primary key "name": "Documentary in the 21st Century", "category": "IHSS", and pathways: "id": 1, #primary key "name": "Arts", "inquiries": [ 1080, 1300, 1170, 1700 ] As you can see I want the model pathways to contain a list of foreign keys pointing to several different courses, but I'm new to Django and can't find anything helpful online. -
Filtering many-to-many in materialized view in Django?
I'm building a Django application which requires creating and filtering a materialized view. I'm having trouble understanding what's the best way to create the materialized view. As an example, I have two tables related with a many-to-many relationship. class Company(models.Model): name = models.CharField(max_length=255) ... class Person(models.Model): name = models.CharField(max_length=255) age = models.PositiveIntegerField() ... places_worked_at = models.ManyToManyField(Company) I'm going to be grouping by persons and would like to implement a materialized view following something like the model below. However, I'm stuck and unsure about how to not only create the materialized view, but how I would store the multiple company ids and names that a person might have in the model. class PersonCompanyMV(models.Model): person_id = models.IntegerField() person_name = models.CharField(max_length=255) person_age = models.PositiveIntegerField() company_ids = ??? company_names = ??? class Meta: managed = False db_table = 'person_company_mv' I'd imagine there's a simple way to implement something like this that allows for easily filtering like PersonCompanyMV.objects.filter(company_id=1)? Any help or links to documentation would be appreciated. -
Django - I don't manage to pass a dataframe or dictionary from views.py to template home.html
Struggling already 5 days with this, appreciate all the help on this . I want to learn how to pull data from database (sqllite) , do some python stuff and pass the result in a dataframe or dictionary from views.py to html template. I'm building django ecommerce webshop with bootstrap template (starting from djecommerce project) . The model 'Item' is a table of products with item.price, item.description, item.etc... in the 'home.html' products cards are constructed with a for loop '{% for item in object_list%} -> card. In this problem , users should search for a product (example 'bike helmet') , after which we pull all the items (Item.objects.all()) , do some python stuff and it should return a dataframe/dictionary/whatever so that I can loop it through in the template. Currently I transform the primary keys back into a list and then do Item.objects.filter(pk=[list of id's]) but I really want to learn to do it properly. I tried so many variations on whatever I have found on the internet so forgive me the current solution below. Thanks already for the feedback and support. I'm sure I'm missing something 'easy' and not understanding it right.. VIEWS.PY ''' class HomeView(ListView): model = Item … -
I just need to redirect vote to details,every things work fine except the last line of vote
strong text[enter image description here][1] [1]: https://i.stack.imgur.com/z1OAJ.jpgemphasized text -
Updating extending user form
I have a CustomUserModel within my models.py class UserManager(BaseUserManager): def create_user(self, email, password=None,is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("Users must have email address") user_obj = self.model(email = self.normalize_email(email)) if not password: raise ValueError("Users must have a password") user_obj.set_password(password) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_staffuser(self,email,password=None): user = self.create_user(email, password=password,is_staff=True) return user def create_superuser(self, email, password=None): user = self.create_user(email, password=password, is_staff=True, is_admin=True) return user class User(AbstractBaseUser): email = models.EmailField(max_length=255,unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' # email and password are required by default REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active class Customer(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) TITLE = ( ('Mr', 'Mr'), ('Mrs', 'Mrs'), ('Miss', 'Miss'), ('Ms', 'Ms'), ('Dr', 'Dr'), ('Sir', 'Sir'), ('Madam', 'Madam'), ) user = models.OneToOneField(User,on_delete=models.CASCADE) title = models.CharField(max_length=200, null=True, choices=TITLE) first_name = models.CharField(max_length=200, null=True) middle_name = models.CharField(max_length=200, blank=True,default='') last_name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) country = CountryField() birth_year = models.CharField(max_length=4, null=True) gender … -
How to create folder by coding in django view on AWS?
I'm very new with AWS and I have a django application which is been deployed to AWS. I have to create a folder for each user and save their machine learning models in these folders. When i try to get home path and create the folders in there, i get an error such as [Errno 13] Permission denied: '/home/wsgi'. How can i fix this? -
Django 3 error: No installed apps with label 'app_name'
I am currently learning how to use Django 3 (and Python 3.8) and I am following a tutorial to create a simple blog. I am getting a good grasp of the basic concepts so far but I am stuck at creating a migrations file. When I enter the python manage.py makemigrations blog command into Windows Powershell, I get the error message: No installed app with label 'blog'. I have searched high and lo for an answer but I am still scratching my head. I am wondering if you lovely people would be able to offer any advice on the matter. Here's my settings.py file: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print("BASE_DIR = ", BASE_DIR) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', '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 = 'django_project.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', … -
what should i do if my css is not working while i am using django framework?
in main html document: {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="{{STATIC_URL}}sgbit/style.css" media="screen" > <title>sgbit</title> </head> <body> {% block content %}{% endblock %} </body> </html> in settings.py file: STATIC_URL = '/static/' STATIC os.path.join(BASE_DIR , 'static'), ] im trying basic background color change to confirm css is working on my document, but nothing i try seems to work. ive watched a lot of youtube videos and also read the documents several times. can you please tell me the issues in my code. thank you. -
Dependent/Chained Drop down List is not working in modal
I am trying to use dependant/chained dropdown list in Django with the help of ajax (https://cutt.ly/MyVQE74) like if i select a company then only then that company department will show up in the modal. it worked in main page for the search function but not working in the modal part while posting data. model_part class Item(models.Model): item_name = models.CharField(max_length=255, blank =True) description = models.CharField(max_length=255, blank=True, null=True) company = models.ForeignKey(Company, on_delete = models.CASCADE) department = models.ForeignKey(Department, on_delete = models.CASCADE) employee = models.ForeignKey(Employee, on_delete = models.CASCADE) view_part def save_item_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True items = Item.objects.all() data['html_item_list'] = render_to_string('item/includes/partial_item_list.html', { 'items': items }) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string( template_name, context, request=request) return JsonResponse(data) def item_create(request): if request.method == 'POST': form = ItemForm(request.POST) else: form = ItemForm() return save_item_form(request, form, 'item/includes/partial_item_create.html') def load_department(request): company_id = request.GET.get('company') departments= Department.objects.filter(company_id=company_id).order_by('name') context={'departments':departments} return render(request,'item/department_drop_down.html',context) def load_employees(request): department_id =request.GET.get('department') employees = Employee.objects.filter(department_id=department_id).order_by('name') context={'employees':employees} return render(request,'item/employee_drop_down.html',context) Templates view (using modal): name: partial_create_form.html <form method="post" action="{% url 'item_create' %}" class="js-item-create-form" id="itemForm" data-departments-url="{% url 'ajax_load_departments'%}" data-employees-url="{% url 'ajax_load_employees'%}" > {% csrf_token %} <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 …