Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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! -
django.contrib.gis.geos throws SegFault
Following the example code snippet from the django-documentation https://docs.djangoproject.com/en/3.1/ref/contrib/gis/geos/#django.contrib.gis.geos.Polygon, I get a Segfault when iterating over the LinearRing of a Polygon. >>> from django.contrib.gis.geos import Polygon, LinearRing >>> ext_coords = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)) >>> int_coords = ((0.4, 0.4), (0.4, 0.6), (0.6, 0.6), (0.6, 0.4), (0.4, 0.4)) >>> poly = Polygon(ext_coords, int_coords) >>> [c for c in poly] [<LinearRing object at 0x7fa81326d610>, <LinearRing object at 0x7fa81326d810>] >>> [c for c in poly[0]] Segmentation fault (core dumped) Why does this code throw a segfault? How can I get the code to run? Originally, I got this error with Python 3.6.7 and Django 3.0.9. I upgraded to Python 3.8.2 in the hope that this is just a compatibility issue between Python 3.6.7 and Django 3.0.9: But upgrading and setting up a new virtualenv did not solve the error. Since the crash happens when iterating over a LinearRing of a Polygon, I tested if looping through just a LinearRing throws an error: >>> from django.contrib.gis.geos import Polygon, LinearRing >>> ext_coords = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)) >>> int_coords = ((0.4, 0.4), (0.4, 0.6), (0.6, 0.6), (0.6, 0.4), (0.4, 0.4)) >>> ls1 = … -
Deployment of Django on Heroku Server Error (500) - Static file problem supposedly
I have deployed my django project on Heroku (a very basic project without database). The homepage is working but I have a Server Error (500) when I ask for a page with an imag from my Django project. When I ask a page with an image from internet, it is working fine. So my deduction is that the static files are not properly served but I don't find what it is wrong in my coding. Heroku log : 2020-09-10T04:31:02.719831+00:00 app[web.1]: 10.63.145.103 - - [10/Sep/2020:04:31:02 +0000] "GET /ES-home HTTP/1.1" 500 145 "https://hamaktest.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36" 2020-09-10T04:31:02.720549+00:00 heroku[router]: at=info method=GET path="/ES-home" host=hamaktest.herokuapp.com request_id=f9cc73c5-b170-4853-9ca7-368255259a52 fwd="117.196.158.121" dyno=web.1 connect=0ms service=60ms status=500 bytes=410 protocol=https In the Heroku build : Installing collected packages: asgiref, pytz, sqlparse, Django, gunicorn, whitenoise remote: Successfully installed Django-3.1.1 asgiref-3.2.10 gunicorn-20.0.4 pytz-2020.1 sqlparse-0.3.1 whitenoise-5.2.0 remote: -----> $ python manage.py collectstatic --noinput remote: 204 static files copied to '/tmp/build_72d0a30f/staticfiles', 481 post-processed. Any idea is welcome. Thank you. Jytar My settings.py file : ALLOWED_HOSTS = ['.hamaktest.herokuapp.com', '127.0.0.1'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website' ] 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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'hamak.urls' TEMPLATES = [ … -
Is there a specific way of adding apps in Django
I read from a post that Django uses INSTALLED_APPS as a list of all of the places to look for models, management commands, tests, and other utilities. Say I have an app called blog which I would like to add to INSTALLED_APPS, which of these two is advisable: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog.apps.BlogConfig', ] OR INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] Both method seems to work fine for me as a beginner. -
Change user type and delete user
I'm currently building a rental system in Python using Django but I have no idea how to change their type(e.g from normal user to Premium User) or delete them as an admin Here's what i've tried so far for changing status/type: def admin_changeuserstat(request): if request.method == 'POST': if request.COOKIES.get("session_adminId"): if User.isNormalUser: # Here's what I'm stuck where I wanna change to Premium user else: #do anything else: return HttpResponse(json.dumps({"error": "please login as admin"})) else: return HttpResponse(json.dumps({"error": "require POST"})) Here's what i've tried for deleting user: def admin_userdelete(request,username): if request.method == 'POST': user = User.objects.get(username=username) if request.user == user: logout(request) user.delete() return redirect("/") else: return HttpResponse(json.dumps({"error": "Only admin can do so"})) else: return HttpResponse(json.dumps({"error": "require POST"})) -
SMTPServerDisconnected at /resetpassword/ Connection unexpectedly closed in Django
I am trying to setup my smtp configuration to work with reset password builtin in Django. I works fine with google smtp, but when i tried to add an email from my domain server i got this error after taking too mush time. SMTPServerDisconnected at /resetpassword/ Connection unexpectedly closed -
Django , How to create a csv file from django model's data and upload it to another model in django
Currently I am working on project in which I need to calculate all the payment methods of complete event by using django model's field, I have to calculate the data and convert it into file which I need to upload into another table. My project is configured by Amazon S3. I need to show the file path in API, so my file will be stored in my model and when I hit API my updated report's path come as Response I see many solutions, but still can't fulfill my requirement. for example: My Model: class foo(models.Model): .... .... another model in which I want to save: class Report(models.Model): report =models.FileField(..) My API: class fooAPIView(ListCreateApiView): foo_queryset = foo.objects.all() report = Report.objects.create(report= foo_queryset) return Response(report.url) Whats the best practice and way to create the file and saved in django models