Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I reveal my truncated text in Django?
I am creating a blog app with Django where users can upload articles, and I would like to truncate the users text to a max length of 150 chars, but give readers the option of expanding the text by clicking 'read more'. {% for post in posts %} <p>{{ post.content|truncatechars:150 }}<span>read more</span></p> {% endfor %} I am able to truncate the text but cannot work out how to then expand it on click. I would like the expanded text to be revealed within the same div, and not be redirected to another page. Any help would be much appreciated. Thanks in advance -
How to authenticate websocket with django channels?
The application stack looks like this: Backend: Django DRF + Channels, for authentication i'm using: 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), Frontend (not served by django backend) : Vue JS application, using a generated client (@openapitools/openapi-generator-cli") library to authenticate / execute operations on the backend. I can use the rest based authentication, retrieve a token that I can use for the following rest-api calls, but I would like to use that token as well with the vue websocket <-> django channels communication. The problem is: How do I use authentication on the channels consumer? If I log in to the django admin page, the incoming websocket connection immediately recognized the admin user in the scope, but not if I'm using any other authentication. What I'm seeing here, is using the default admin page login, it will save the sessionid and a csrf token as cookies. When I try to replicate the same authentication behaviour a with client api call, I can see on the browser network traffic that the proper Set-Cookies are sent, containing this info, but it is unreachable for me to set. Should it be set by default? What am I missing? -
nginx with gunicorn and django on centos 7
I'm trying to make my nginx and gunicorn start working... but seemingly trying everything I could do, fails... If I do: systemctl restart nginx systemctl status nginx It shows green, and it works... If I do: systemctl start gunicorn.socket systemctl status gunicorn.socket -l It shows green and works fine... But if I do: systemctl start gunicorn.service systemctl status gunicorn.service -l it shows me the following message: gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: disabled) Active: failed (Result: exit-code) since Thu 2020-09-10 14:17:23 UTC; 15min ago Process: 22145 ExecStart=/home/scorg/pro/sc_project/bin/gunicorn --workers 3 --bind unix:/home/scorg/pro/projects/sc/sc.sock sc.wsgi:application (code=exited, status=3) Main PID: 22145 (code=exited, status=3) Sep 10 14:17:23 gunicorn[22145]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import Sep 10 14:17:23 gunicorn[22145]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load Sep 10 14:17:23 gunicorn[22145]: File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked Sep 10 14:17:23 : ModuleNotFoundError: No module named 'sc' Sep 10 14:17:23 : [2020-09-10 14:17:23 +0000] [22152] [INFO] Worker exiting (pid: 22152) Sep 10 14:17:23 : [2020-09-10 14:17:23 +0000] [22145] [INFO] Shutting down: Master Sep 10 14:17:23 : [2020-09-10 14:17:23 +0000] [22145] [INFO] Reason: Worker failed to boot. Sep 10 14:17:23 : gunicorn.service: main process exited, code=exited, status=3/NOTIMPLEMENTED Sep 10 14:17:23 : Unit gunicorn.service … -
HINT: Add or change a related_name argument to the definition for 'CustomUser.user_permissions' or 'User.user_permissions'
I need help. I´m creating an app in Django and I'm having some trouble making migrations of my custom user's class. The error is: ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'Usuario.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'Usuario.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'Usuario.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'Usuario.user_permissions'. usuarios.Usuario.groups: (fields.E304) Reverse accessor for 'Usuario.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'Usuario.groups' or 'User.groups'. usuarios.Usuario.user_permissions: (fields.E304) Reverse accessor for 'Usuario.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'Usuario.user_permissions' or 'User.user_permissions'. Now, this is my code: My Model: class CustomUser(AbstractUser): email = models.EmailField(unique=True, max_length=80) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['USERNAME'] def __str__(self): return self.email class Perfil(models.Model): user=models.OneToOneField(CustomUser, related_name="usuario_user" , on_delete=models.CASCADE) nacionality= models.ForeignKey(Paises, on_delete=models.DO_NOTHING) rol= models.ForeignKey(Rol, on_delete=models.DO_NOTHING) def str(self): return self.CustomUser birth_date=models.DateField() In my settings.py: AUTH_USER_MODELS= 'users.CustomUser' LOGIN_REDIRECT_URL= reverse_lazy('home') LOGOUT_REDIRECT_URL= reverse_lazy('login') LOGIN_URL = reverse_lazy('login') # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.users', ]``` -
ReactJs 400 (Bad Request)
My django rest framework returns a 400 bad request when sending files across with ReactJs, while postman uploads the same file with same parameter successfully. When I investigated further, I noticed a specific error of "No file was submitted" was what was returned from the API. Submit Handler submitHandler(event){ event.preventDefault() const data = new FormData() data.append('file', this.state.selectedFile) axios .post('http://localhost:8000/files/', data, {}) .then(res => { console.debug(res.statusText) }) .catch(err => { console.debug(err) }) } state: this.state = { selectedFile: null, redirect: false, file_name:'', } -
A website that i uploaded can be accessed by some people and some people are not being able to access it
I uploaded a python/danjo used website (www.shraddhabhattarai.com) from cpanel and was all right when i opened it and also by some other people, it opened up fine. But in some cases, some people are not able to access the website. It says "ip address could not be found". I thought it was due to poor connection but everything else is working fine in their device. The website does not show even after many refresh. -
Django migrate throws AttributeError: 'str' object has no attribute '_meta'
After doing some extensive changes in the DB schema, I ran makemigrations. It created migrations successfully. But then migrate failed with: AttributeError: 'str' object has no attribute '_meta' What went wrong? Somewhat similar to this question: Django makemigrations AttributeError: 'str' object has no attribute '_meta' but my makemigrations went ok and only failed at migrate command. -
Django many to many does not show actual string. Rather save in the integer data so how to rectify?
The same Consumer_order model but create datatable enter image description here Actual have to input requirement Consumer_order Models.py class Consumer_order(models.Model): name = models.ForeignKey(Consumer, on_delete=models.CASCADE) ac_no = models.CharField(max_length=32) newspaper = models.ManyToManyField(Newspaper,related_name="Consumer_ac_no") added_date = models.DateField(max_length=32,auto_now_add=True) -
Django: How to read info from custom radio select in view
So yesterday I spent whole day customizing star-rating ("radio-button-ish"). Now I don't want to abandon my css masterpiece (I am not much of a front-end guy so this was real pain for me), but it looks like that my approach to the problem wasn't correct. Html code is quite simple: <div class="col-md-5 mb-0 mt-3"> <div id="rating"> <input type="radio" name="star" id="star1"><label for="star1"></label> <input type="radio" name="star" id="star2"><label for="star2"></label> <input type="radio" name="star" id="star3"><label for="star3"></label> <input type="radio" name="star" id="star4"><label for="star4"></label> <input type="radio" name="star" id="star5"><label for="star5"></label> </div> </div> Now, is there a way to simply read from this choice and then use it in my view? The situation is, normally I would probably use Field in form with choices but the design would be lost. Do you see a simple solution? Or is there a way of customizing a ChoiceField with widget RadioSelect into the same form, so i can use the name, id just like in above html code? Note: this is my first django project, pardon me if it is a complete nonsense or I missed something basic.. -
DRF Custom permissions for 1 view for auth and non auth users
Idea is non-auth user can only GET(list,retrieve) view. Auth user can GET,POST,PATCH,DELETE. How can i do it in custom permission? my view: class BookViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) serializer_class = serializers.BookSerializer def get_queryset(self): return Book.objects.filter(user=self.request.user) -
How to correctly Validate user entry in Django Generic Views
In my Django app I am trying to validate a form field value entered by the user. I am trying to do the validation in Django generic UpdateView (as I will explain below). The extant field stores various statuses of a transaction document. The change in status happens at update (either by the user manually entering the status code OR based upon certain phase of transaction or the like - not important here). The important thing is that on save the status of the document needs to change. As there are a number of statuses, each of them have been given a numerical value. Wherever the statuses are manually entered, the need is to check if the current status value is less than the entered value. If it is not, the user should get an error message. My views.py looks like this: class ProdDocView(UpdateView, ...): template_name = ... model = ProdLine form_class = ProdLineForm ... def form_valid(self, form): tmp_status = ProdLine.objects.get(prod_doc_id=self.object.pk).prod_doc_status new_status_entered = form.cleaned_data['prod_doc_status'] if tmp_status == new_status_entered: # This is just to check error capture # raise ValidationError('Wrong status code entered!!') return super(ProdDocView, self).form_invalid(form) else: form.instance.approved_by = self.request.user. # This is to save user field on successful save return … -
Django webapp not deploying. Apache2
I want to deploy my django webapp on aws ec2 instance with apache but it is giving error. When I try to access the website is gives the following error. Forbidden You don't have permission to access this resource. My home structure looks like this └── django_test1 ├── auth │ └── mysql.cnf ├── django │ └── mysite └── venv ├── bin ├── lib └── pyvenv.cfg mysite folder has the following structure └── mysite ├── db.sqlite3 ├── manage.py ├── media ├── mysite ├── static ├── tempapp └── templates settings.py file """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 3.1.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') MEDIA_DIR = os.path.join(BASE_DIR,'media') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ' secret key ' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [ IP address ] # … -
How to automatically add slug according to username of a user in models.py
I am new to django. Currenty I am trying to make social network website. Here is my model of profile class. I want to assign value of slug field to the username of the User. But can't find or think of any way to do this. If anyone know any way of doing this I'll be thankfull if you suggest me how to do this from django.contrib.auth.models import User from django_countries.fields import CountryField from django.db import models class Profile(models.Model): GENDER = [ ('NONE', 'none'), ('MALE', 'male'), ('FEMALE', 'female') ] first_name = models.CharField(max_length=100, blank=False) last_name = models.CharField(max_length=100, blank=True) email = models.EmailField(max_length=200, blank = True) bio = models.TextField(default='No bio data', max_length=400) user = models.OneToOneField(User, on_delete = models.CASCADE) gerder = models.CharField(max_length=6, choices=GENDER, default='NONE') country = CountryField() avatar = models.ImageField(default='avatar.png', upload_to='avatars/') friends = models.ManyToManyField(User, blank = True, related_name='friends') slug = models.SlugField(unique = True, blank = True) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) favourite = models.CharField(max_length=300, blank=True) def __str__(self): return f'{self.user.username}-{self.created}' ``` -
'super' object has no attribute 'form_valid' (Django)
I think the reason that I got this error maybe because I didn't use FormMixin and form_class in the detailView. I have tried it but my form will not run without current_class_pk (I added it inside my AttendanceForm using kwargs.pop) so I have to use get_context_data to pass the pk of detailview to the form. How can I fix this? or Are there anyway other ways to pass detailview pk to the form_class? view.py class Class_detailView(LoginRequiredMixin, DetailView): login_url = '/' model = Class template_name = "attendance/content/teacher/class_detail.html" def get_context_data(self, **kwargs): class_pk = self.object.pk print(class_pk) context = super(Class_detailView, self).get_context_data(**kwargs) context['attendance_form'] = AttendanceForm(current_class_pk=class_pk) # pass data to form via kwargs return context def get_success_url(self): return reverse('class_detail', kwargs={'pk': self.object.pk}) def post(self, request, *args, **kwargs): self.object = self.get_object() if request.method == "POST": attendance_form = AttendanceForm(request.POST, current_class_pk=self.kwargs.get('pk')) if attendance_form.is_valid(): return self.form_valid(attendance_form) def form_valid(self, form): form.instance.teacher = self.request.user form.instance.attendance_class = self.object form.save() return super(Class_detailView, self).form_valid(form) forms.py class AttendanceForm(forms.ModelForm): class Meta: model = Attendance fields = ['student',] def __init__(self, *args, **kwargs): current_class_pk = kwargs.pop('current_class_pk') super(AttendanceForm, self).__init__(*args, **kwargs) current_student = Class.objects.get(id=current_class_pk) self.fields['student'].queryset = current_student.student -
Role based access control in Django
I am developing an application for managing employees with Django, and as part of the first steps, I'm trying to get the user model correct. I need to implement some kind of user hierarchy or role based access control. Let me explain: The company will have several levels, in order of hierarchy: Company -> Branch -> Department For each of the above entities, a user will have "owner" permissions, for create, read and update. The different levels of employees are as follows: Company Manager (Company) -> Branch Manager (Branch) -> Department Manager (Department) -> Low privilege user (Standard Employee) Usage case for Company Manager: Can create/update/view branches and departments Can create/update/view users under branches and departments Can grant privileges to Branch Managers and Department Managers Usage case for Branch Manager: Can create/update/view departments Can create/update/view users under departments Can grant privileges to Department Managers Cannot create/update/view other branches Usage case for Department Manager: Can create/view/edit users under his own department, but not others Cannot create/update/view other departments Usage case for Low Privilege user: Can view own profile Cannot view anythings else Now I have looked into Django's default User/Group, and seen that it's not possible as this does not support … -
Not Getting Any Output from Dockerized Celery
I have been working off of two similar tutorials (here and here) trying to create a scheduled task for my Django project, but I can't seem to get any output from the Celery services. I've added Celery and Redis to the requirements.txt. Django==3.0.7 celery==4.4.7 redis==3.5.3 Added the celery, celery-beat, and redis services to the docker-compose.yaml. version: "3.8" services: cache: image: redis:alpine database: image: "postgis/postgis" ports: - "5432:5432" environment: POSTGRES_DB: postgres POSTGRES_USER: ${DATABASE_DEFAULT_USERNAME} POSTGRES_PASSWORD: ${DATABASE_DEFAULT_PASSWORD} web: build: . ports: - "8000:8000" volumes: - .:/app depends_on: - cache - database env_file: - .env queue: build: . command: celery -A api worker -l info volumes: - .:/app links: - cache depends_on: - cache - database scheduler: build: . command: celery -A api beat -l info volumes: - .:/app links: - cache depends_on: - cache - database Added the celery.py file to the api/api/ directory. import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') app = Celery('api') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) Added the following to api/api/__init__.py. from .celery import app as celery_app __all__ = ('celery_app',) Created a task in api/server/tasks.py. import logging from celery import shared_task logger = logging.getLogger(__name__) @shared_task def sample_task(): logger.debug('The sample task just ran.') And added the following … -
django models not accept the email?
trying to setting up a small website,a newbie in django . when i create a newsletter setup in django, but the email not saving the admin panel. here is my codes. take a look . models.py class Newsletter(models.Model): email = models.CharField(max_length=200) def __str__(self): return self.email views.py def Newsletter(request): if request.method=="POST": email = request.POST.get("email") email = email(email=email) email.save() message.success(request, "email Successfully added") return render(request, 'index.html') urls.py path('newsletter', views.Newsletter, name="newsletter"), template <div id="mc_embed_signup" class="subscribe-form subscribe-form-dec subscribe-mrg"> <form id="Newsletter" class="validate subscribe-form-style" novalidate="" name="Newsletter" method="post" action="/Newsletter"> <div id="mc_embed_signup_scroll" class="mc-form"> <input class="email" type="email" required="" placeholder="Your email address…" name="Newsletter" value="" id="Newsletter"> <div class="mc-news" aria-hidden="true"> <input type="text" value="" tabindex="-1" name="Subscribers"> </div> <div class="clear"> {% csrf_token %} <input id="mc-embedded-subscribe" class="button" type="submit" name="subscribe" value="Subscribe"> </div> </div> -
Django cannot find module
I am working on a Django project. I have several apps within the project and everything has been working fine. I recently added a new app called files through django-admin and for some reason, Django cannot find this module. This is my project structure core/ __init__.py settings.py urls.py wsgi.py api/ migrations/ __init__.py admin.py apps.py models.py urls.py views.py files/ __init__.py apps.py forms.py init_s3.py urls.py views.py The apps.py for the files module reads: from django.apps import AppConfig class FilesConfig(AppConfig): name = 'files' Which is almost word-for-word how the AppConfig for the api module is written: from django.apps import AppConfig class ApiConfig(AppConfig): name = 'api' I have the api and files app installed in the INSTALLED_APPS setting: INSTALLED_APPS = [ ...other apps... 'api.apps.ApiConfig', 'files.apps.FilesConfig' ] Django has no problems locating the api app, but cannot find the files app. When I run the server, I get the following error: ModuleNotFoundError: No module named 'files' What's going on here? What am I missing? Any help is appreciated! Thanks! -
How to properly use filter before annotation?
I am trying to get amount of costs per year-month for certain category in DetailView. But the problem is - and it might be foolish - I can't figure out how to get data only for the category that has been chosen in this table by user. Any ideas? def category_summary(): total = Expense.objects.annotate( month=TruncMonth('date')).values('date').annotate( amount=Sum('amount')).order_by() MODELS.PY class Category(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return f'{self.name}' class Expense(models.Model): class Meta: ordering = ('date', '-pk') category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=8, decimal_places=2) date = models.DateField(default=datetime.date.today, db_index=True) def __str__(self): return f'{self.date} {self.name} {self.amount}' -
Get all values of ManyToMany model field
I am making a filter with select dropdown. The filtering is occurring with XHR. I want to get all options through JSON via XHR. The options are the values of the field in my model. The filtering will be according to that values. To be clear, it is more complex project, so I need to get field values through JSON. In order to eliminate complexity, not sharing views.py. It is a function view. Models.py: class Article(models.Model): ... tag = models.ManyToManyField('Tag', related_name='tags') ... class Tag(models.Model): name = models.CharField(("Tag name"), max_length=50) -
How do I validate if a django URLfield is from a specific domain or hostname?
Hi I want to see if a models.URLfield is from youtube or soundcloud. url = models.URLField("URL", max_length=255, unique = True) How do I do this? -
Is there a way in which I can write a path of a div tag of one html file into another html file in django {% url 'file_name' %}
This is the code line of about_us.html <a class="nav-link page-scroll" href="index.html#faq">FAQ</a> How should I create a path for #faq from index.html into about_us.html in Django. -
Django - ListView - list assigned images to the post
Hello I would like to list all images which were added to my post in my Blog application. Models.py class Post(models.Model): title = models.CharField(max_length=100) content = RichTextField(blank=True, null=True) class PostImage(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE, related_name='postimages') image = models.ImageField(upload_to='gallery/') I guess I should override the get_queryset method but dont know how. Any ideas? Thanks. -
Can't populate the dropbox field in Django autocomplete light
I am trying to create a dropbox of countires which can be searchable based on this doc, however almost disappointed to find any solution by googling. I am using django-cities-light package and django-autocomplete-light, and all I need to do is creating a field of countries/cities and populating it in a form and making it searchable, in setting.py and installed apps: INSTALLED_APPS = [ 'dal', 'dal_select2', 'dal_legacy_static', 'app.apps.MyownAppConfig', 'users.apps.UsersConfig', 'crispy_forms', 'tinymce', 'cities_light', 'django.contrib.admin', 'django.contrib.auth', ... ] in models.py: from tinymce.models import HTMLField from cities_light.models import Country class Post(models.Model): ... descript = HTMLField(blank=True, null=True) location = models.ForeignKey(Country, blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) in views.py: class CountryAutocomplete(LoginRequiredMixin, autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): print('not self.request.user') return Country.objects.none() qs = Country.objects.all() if self.q: qs = qs.filter(name__icontains=self.q) | qs.filter(comNumber__icontains=self.q) return qs In forms.py: class postform(forms.ModelForm): class Meta: model = Post fields = ("__all__") exclude = ['date_published'] widgets = { 'location': autocomplete.ModelSelect2(url='country-autocomplete' , attrs={'data-placeholder': 'select location...', 'data-minimum-input-length': 4}) } search_fields = ['name'] and in postform.html: {% extends "app/base.html" %} {% load crispy_forms_tags %} {% load static %} {% block content %} <main> <form id="dropdownForm" method="POST" action="" … -
Running django channels tests
I am writing tests for Django channels but it throws KeyError: path. channel version is 1.1.6 routing.py channel_routing = [ route_class(ChatConsumer), ] consumers.py @channel_session def connect(self, message, **kwargs): message.reply_channel.send({"accept": True}) Group('users').add(message.reply_channel) @channel_session def receive(self, data=None, **kwargs): if data.get('type') == 'typing': self.typing(data) test.py class ChannelTestCases(ChannelTestCase): # def test_a_thing(self): # # This goes onto an in-memory channel, not the real backend. # Channel("some-channel-name").send({"foo": "bar"}) def test_consumer(self): Channel("typing").send({"type": "typing"}) ChatConsumer(self.get_next_message("typing", require=True)) result = self.get_next_message("result", require=True) self.assertEqual(result['value'], 1089) Can anybody help me test this case, please? In general, I am doing it by looking at docs. Am I doing right or not? Any help would be appreciated! Thanks in advance!