Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When djando DEBUG = False I am always thrown with a 500 server error
I am trying to create an eCommerce app and I still haven't got into the backend part of it but I was testing the Django debug feature when I am already thrown with an error. I am using Heroku as my web hosting provider. I am also using a couple of files from the static folder and have not stored them somewhere on the internet yet. Is that a possible error? This is my settings.py file... import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('EBLOSSOM_SECRET_KEY') # 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', 'django_cleanup', 'crispy_forms', 'storages', 'store.apps.StoreConfig', 'user.apps.UserConfig' ] 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 = 'eblossom.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'eblossom.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': … -
Regex for UnicodeUsernameValidator
In Django I set custom User where I set my own regular expression to valid a registered username field witch should accept 1 space between words and non before and after all name. What I do wrong? In https://regexr.com/ this expression work but in my form is not. username_validator = MyUnicodeUsernameValidator() @deconstructible class MyUnicodeUsernameValidator(validators.RegexValidator): regex = r'^([\w.@+-]+\s?[\w.@+-]*[^\s]){1,}$\Z' message = _( 'Enter a valid username. This value may contain only letters, ' 'numbers, and @/./+/-/_ characters. ' 'Whitespaces before/after the name, as well as two whitespaces between words are incorrect.' ) flags = 0 -
Django - Python - How to include STATUS CODE in response using JsonResponse?
Here is my code, that let users input their ID and Name to check if they are in a list of something. def some_api(requests): try: **do something** return HttpResponse('Your name is in the list') #Response 302 CODE FOUND NOT 202 except: return JsonResponse([{ ID : 123, #Response 203 CODE EMPTY NOT 202 Name : ABC, #with information for users to double check Content : [] #their params }]) As always, when I return HttpResponse and `JsonResponse, it is always the 200 CODE -
APScheduler job not executed as scheduled
I am trying to run apscheduler with gunicorn and supervisord. Without gunicorn, apscheduler is working but sometimes with gunicorn, apscheduler does not work. Except apscheduler, other project is working. I am using following command to run using gunicorn /home/ubuntu/project/project_folder/venv/bin/gunicorn project.wsgi:application --timeout 120 --workers 2 --threads=3 --bind=0.0.0.0:2732 In settings.py file from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.jobstores.redis import RedisJobStore from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor logging.basicConfig(filename='logs/scheduler', level=logging.DEBUG,format='[%(asctime)s]: %(levelname)s : %(message)s') logging.getLogger('apscheduler').setLevel(logging.DEBUG) # scheduler = BackgroundScheduler(misfire_grace_time=20, executors=executors) scheduler = BackgroundScheduler({'apscheduler.timezone': 'Asia/Calcutta'},job_defaults={'misfire_grace_time': None}) scheduler.add_jobstore(RedisJobStore(jobs_key='dev-jobs', run_times_key='dev_all_run_times'), 'redis') scheduler.start() And set the job in views.py file as start_date_of_job = model_object.start_date start_time = dates.strptime(model_object.start_time, '%I.%M %p').time() start_datetime_of_job = dates.combine(start_date_of_job, start_time) settings.scheduler.add_job(function_to_run, 'date', jobstore='redis', replace_existing=True, run_date=start_datetime_of_job, misfire_grace_time=None, id="start-" + str(model_object.id), args=[args list]) Sometimes it works, sometime it does not work. -
How to automatically create relationship between user model and custom group in Django?
As a newbie to Django, all things are still not clear to me. I'm having some issues while working on my project. Whenever I register as a new student, it lets me to login. But I cannot upload profile picture. It throws me an error: ValueError at /account_settings/ The 'profile_pic' attribute has no file associated with it. When I login as an admin and want to see the new student, I just see a blank space, not the new student. Here is the screenshot of my admin view: If I see from admin page, there is also a blank space. Here is admin page view: I have to manually create a student and an user from admin page, and make relationship between them. Please anyone explain me what actually happens behind the scenario. I'm a noob, I'll be grateful if anyone kindly makes it clear for me. Thanks in advance. Here is my models.py: from django.db import models from django.contrib.auth.models import User class Student(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(default= 'default-picture.jpg', null= True, blank= True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return str(self.name) class Tag(models.Model): name … -
DRF class based view parse dataObj ids from datatables
I am using datatables and my goal is to delete the selected rows. I can select the rows and get their IDs. The button #countbuttonids does this perfectly and send me an alert. However, when I try and post this data to my custom DRF endpoint I am having issues deleting the objects with the ID's in the data array. Two attempts below with their relating error messages. views.py 1 # https://www.django-rest-framework.org/tutorial/3-class-based-views/ class APIDeleteEntries(generics.RetrieveUpdateDestroyAPIView): queryset = Entry.objects.all() serializer_class = EntrySerializer def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) Error Message 1 assert lookup_url_kwarg in self.kwargs, ( AssertionError: Expected view APIDeleteEntries to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. [22/Dec/2020 10:11:21] "DELETE /api/delete-entries/ HTTP/1.1" 500 114337 views.py 2 # https://www.django-rest-framework.org/tutorial/3-class-based-views/ class APIDeleteEntries(generics.RetrieveUpdateDestroyAPIView): queryset = Entry.objects.all() serializer_class = EntrySerializer def delete(self, request, *args, **kwargs): entry_ids = self.kwargs['id'] return entry_ids.destroy(request, *args, **kwargs) Error Message 2 entry_ids = self.kwargs['id'] KeyError: 'id' entry_list.html {% extends "dashboard/base.html" %} {% load i18n %} {% block content %} <style> table.dataTable tbody tr.odd.selected { background-color:#acbad4 } table.dataTable tbody tr.even.selected { background-color:#acbad5 } </style> <!-- Page Heading --> <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h2 … -
Django 3.1.4: Get checkbox values in a function in views.py
I successfully did it for input text and now I would like to do it with checkboxes. I don't want to store checkbox values in a database. I just want to get it in a function in views.py I was not able to find how to do it. Thank you for your help! -
Why use Django Rest Framework if I can create an API using Django itself?
I have a Django API which is hosted in Ubuntu EC2 instance using Apache and mod_wsgi. Should I integrate the Django Rest Framework? If yes what are the advantages of using it over normal django API? -
Django template not extending in project
I have two app in Django. Blog and account blog -templates -base.html account -template -signup.html i want to extend base.html to signup.html {% extends 'blog/base.html' %} not working please help -
How to send push notification using django
I want to create a custom notification system using Django and javascript when the user enters his/her requirement and sends it then that will notify the owner. -
Django-Getting error as "self.fail("First argument is not valid JSON: %r" % raw)"
When i am trying to run the below api using unittest , getting error as " self.assertJSONEqual(response_content, {"status": 1}) self.fail("First argument is not valid JSON: %r" % raw)" @csrf_exempt @api_view(['POST']) def AdminLoginView(request): if(request.method=="POST"): admin_email = request.data['admin_email'] password = request.data['password'] res = Admin.objects.filter(admin_email=admin_email, password=password).first() if(res): return Response({'status':1},status=status.HTTP_200_OK) return Response({'status':0},status=status.HTTP_200_OK) UnitTest code for testing the above api: def test_admin_login_view(self): req_data = {"admin_email": "test@admin.com", "password": "password"} response = self.client.post('/admin/login/', req_data) self.assertEqual(response.status_code, 200) response_content = response.content.decode("utf-8") self.assertJSONEqual(response_content, {"status": 1}) Please help me on this. -
Django - Order_by a queryset more than once
I want to re-order my queryset after ordering it once. Is it possible? Here is my get_queryset method: def get_queryset(self): id_ordered_logs = BatchLog.objects.filter(batch__user__isnull=False)\ .order_by('-batch_id').distinct('batch_id') return id_ordered_logs I want to order this list by their created_at fields, this is what I want to do: def get_queryset(self): id_ordered_logs = BatchLog.objects.filter(batch__user__isnull=False)\ .order_by('-batch_id').distinct('batch_id') return id_ordered_logs.order_by('-created_at') I'd like to know if this is possible. Thanks and regards. -
can someone please kindly explain to me this lines of code in Django models
this is the model and I don't get the use of re in it import re from django.db import models class CategoryManager(models.Manager): I read the documentation on managers and I still don't get it def new_category(self, category): new_category = self.create(category=re.sub('\s+', '-', category).lower()) new_category.save() return new_category class Category(models.Model): category = models.CharField( verbose_name=_("Category"), max_length=250, blank=True, unique=True, null=True) objects = CategoryManager() what will the objects do here class Meta: verbose_name = _("Category") verbose_name_plural = _("Categories") def __str__(self): return self.category class Quiz(models.Model): title = models.CharField( verbose_name=_("Title"), max_length=60, blank=False) description = models.TextField( verbose_name=_("Description"), blank=True, help_text=_("a description of the quiz")) url = models.SlugField( max_length=60, blank=False, help_text=_("a user friendly url"), verbose_name=_("user friendly url")) category = models.ForeignKey( Category, null=True, blank=True, verbose_name=_("Category"), on_delete=models.CASCADE) random_order = models.BooleanField( blank=False, default=False, verbose_name=_("Random Order"), help_text=_("Display the questions in " "a random order or as they " "are set?")) max_questions = models.PositiveIntegerField( blank=True, null=True, verbose_name=_("Max Questions"), help_text=_("Number of questions to be answered on each attempt.")) answers_at_end = models.BooleanField( blank=False, default=False, help_text=_("Correct answer is NOT shown after question." " Answers displayed at the end."), verbose_name=_("Answers at end")) exam_paper = models.BooleanField( blank=False, default=False, help_text=_("If yes, the result of each" " attempt by a user will be" " stored. Necessary for marking."), verbose_name=_("Exam Paper")) single_attempt = models.BooleanField( … -
Get a list of users with a permission annotated as boolean
Is there a way to build a query to get a list of users with a boolean stating if they have a specific permission without the need to loop through the users and checking if they have the permission one by one -
Validating Multiple Files in Django forms.py
I am having a multiple file field, I want to validate the files and raise the errors in forms.py before the controls goes to is_valid() in view.py. forms.py class FileForm(forms.Form): filefield = forms.FileField( widget=forms.ClearableFileInput(attrs={'multiple': "true"}), ) def clean(self): print(self.cleaned_data['filefield']) #gives only one file I manage to get it work on view.py like below but I want to validate on forms.py def FileRender(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) if request.FILES.get('filefield') is not None: if form.is_valid(): fs = FileSystemStorage() uploaded_files = request.FILES.getlist('filefield') uploaded_file_url = [] for eachfile in uploaded_files: print(eachfile.name) print(eachfile.size) filename = fs.save(eachfile.name, eachfile) eachurl = fs.url(filename) # get the url of each file uploaded_file_url.append(eachurl) # adding urls to list # write command to save the link to model #allurls = '--'.join(uploaded_file_url) #print(allurls) # can save to db return render(request, 'MyApp/welcome.html', {'form': form, 'uploaded_file_url': uploaded_file_url}) return render(request, 'MyApp/welcome.html', {'form': form}) else: form = FileForm() return render(request, 'MyApp/welcome.html', {'form': form}) How to read all files from multiple input field in form.py and raise the validation error. -
Django-EAV realization for categories
I'm using https://github.com/DanielIndictor/django-eav2 eav repository for my online store. Faced a problem, I can't figure out how to pass attributes to the product depending on the category. When you select a category in the admin panel, the product should have the attributes of this category. Found such a data organization scheme, but I don't know how to implement it using this library. EAV database schema models.py from django.db import models import eav class Category(models.Model): name = models.CharField(max_length=40, verbose_name='Название') def __str__(self): return str(self.name) class Meta: verbose_name = 'Категория' verbose_name_plural = 'Категории' class Product(models.Model): name = models.CharField(max_length=40, verbose_name='Название') category = models.ForeignKey(Category, on_delete=models.PROTECT) def __str__(self): return str(self.name) class Meta: verbose_name = 'Товар' verbose_name_plural = 'Товары' eav.register(Category) eav.register(Product) admin.py from django.contrib import admin from eav.forms import BaseDynamicEntityForm from eav.admin import BaseEntityAdmin from .models import Product, Category # Register your models here. class CategoryAdminForm(BaseDynamicEntityForm): model = Category class CategoryAdmin(BaseEntityAdmin): form = CategoryAdminForm admin.site.register(Category, CategoryAdmin) admin.site.register(Product) -
How to retrive id of recently saved form in different def in django(Not using form)
I'm creating a three-step form and I'm saving on every step in a different model; I want to get an id of step1 data in different def for the second step I am not using form.py only views, HTML, model -
Django: Got got an unexpected keyword argument after Nested serializer
I have been working on RoutePrice Model and I tried to serialize data in nested serializer, before nested serializer it was fine working clean but I got type error after nested serializer. Here is Model and my serializer I have tried so far. class RoutePrice(BaseModel): bus_company_route = models.ForeignKey(BusCompanyRoute, on_delete=models.PROTECT) bus_type = models.ForeignKey(Category, on_delete=models.PROTECT) seat_price_for_travel_agent = AmountField() seat_price_for_user = AmountField() seat_price_for_foreigner = AmountField(null=True, blank=True) class Meta: default_permissions = () verbose_name = 'Route Price' verbose_name_plural = 'Route Prices' constraints = [ models.UniqueConstraint( fields=['bus_company_route', 'bus_type'], name='unique_route_price' ) ] and Here is how is serialized my data class AddRoutePriceSerializers(serializers.ModelSerializer): class Meta: model = RoutePrice fields = ( 'bus_type', 'seat_price_for_travel_agent', 'seat_price_for_user', 'seat_price_for_foreigner', ) class AddMultipleRoutePriceSerializers(serializers.Serializer): data = AddRoutePriceSerializers(many=True) I had my logic in usecases.py and views.py #usecases.py class AddRoutePriceUseCases(BaseUseCase): def __init__(self, serializer: AddMultipleRoutePriceSerializers, bus_company_route: BusCompanyRoute): self._serializer = serializer self._data = serializer.validated_data self._bus_company_route = bus_company_route def execute(self): self._factory() def _factory(self): print(self._data) self.route_price = RoutePrice(**self._data, bus_company_route=self._bus_company_route) try: self.route_price.full_clean() self.route_price.save() except DjangoValidationError as e: raise ValidationError(e.message_dict) #views class AddRoutePriceView(generics.CreateAPIView): """ Use this end-point to add route price to specific bus company route """ serializer_class = route_price_serializers.AddMultipleRoutePriceSerializers def get_bus_company_route(self): return GetBusCompanyRouteUseCase( bus_company_route_id=self.kwargs.get( 'bus_company_route_id' ) ).execute() def perform_create(self, serializer): return AddRoutePriceUseCases(serializer=serializer, bus_company_route=self.get_bus_company_route() ).execute() I got error saying Route RoutePrice() got … -
How to upload both json data and file using django rest framework
I'm making use of django default restapi. [This is the default api] [1]: https://i.stack.imgur.com/FhkuP.png before adding file , I upload the other fields in json format in the content textbox. Now I have file to upload. I've tested my code with postman, it works fine because it has provided file browse option. In api I don't have file browse option, How to add file browse option to default api or is there any way to give file in json itself(this didn't work as I gave file path in json). -
username from User is always giving anonymous
I am working on a website and when I try to access my username, it gives a null value Here's my models: User = get_user_model() class Contact(models.Model): user = models.ForeignKey( User, related_name='friends', on_delete=models.CASCADE) friends = models.ManyToManyField('self', blank=True) def __str__(self): if not self.user.username: return "Anonymous" return self.user.username class Message(models.Model): contact = models.ForeignKey( Contact, null=True, related_name='messages', on_delete=models.CASCADE) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): if not self.contact.user.username: return "Anonymous" return self.contact.user.username when i try to access it in for eg. the profile.js like this const mapStateToProps = state => { console.log(state.username) return { username: state.username } } it prints null this is also preventing me from authenticating cause it throws an error like this: react-dom.development.js:25058 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined I am stuck in this error for many days n would like some help -
How to fix table doesn't exist issue while importing Data from an external Database in Django?
I am creating a Django REST API where I have a read-only access to a particular PostgreSQL DB and I am writing all the Auth and other default tables to a local SQlite3 database. Following are my settings.py DATABASES = { 'prod': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'xx', 'USER': 'xx', 'PASSWORD': 'xx', 'HOST': 'xx', 'PORT': '5432', }, 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'auth.sqlite3', } } After doing this, I imported a table user_master from the external database into models.py and it created the following model: class UserMaster(models.Model): user_id = models.BigAutoField(primary_key=True) mobile_no = models.CharField(max_length=10) is_active = models.BooleanField(blank=True, null=True) access_token = models.CharField(max_length=220, blank=True, null=True) unique_id = models.CharField(unique=True, max_length=9, blank=True, null=True) status = models.BigIntegerField() is_md5_passcode = models.BooleanField(blank=True, null=True) access_code = models.CharField(max_length=200, blank=True, null=True) is_bcrypt_passcode = models.BooleanField(blank=True, null=True) created_date = models.DateTimeField() updated_date = models.DateTimeField() created_by = models.ForeignKey('self', models.DO_NOTHING, db_column='created_by', related_name='+') updated_by = models.ForeignKey('self', models.DO_NOTHING, db_column='updated_by', related_name='+') approved_on = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'user_master' I also created a router to allow read access from my prod db and write access only to me default db: class ProdRouter(object): def db_for_read(self, model, **hints): "Point all operations on prod models to 'proddb'" if model._meta.app_label == 'prod': return 'prod' return 'default' def db_for_write(self, model, **hints): … -
Is there a better way to parse a dynamic value of a Django Template into a Javascript file?
Is there a better method to retrieve the dynamic value 'bar' from the Django Template? index.html: <div id="foo" name="{{bar}}"></div> main.js: const foo = document.getElementById('foo') const bar = foo.name console.log(bar) output: bar -
Django - How to pass multiple selected values from selectpicker from template to views.py
I have a multiselect dropdown (select class="selectpicker" multiple) in my template. I want to transfer the selected values to my search function in views.py so that I can use those parameters to apply queries on my database table and then route the user to Listings page based on search parameters selected. Please see below my code. Can you please assist as to what I am doing wrong: Template file: Colony (All) {% for key,value in colony_choices.items %} {{ value }} {% endfor %} views.py: if 'colony[]' in request.GET: {% for colony in request.GET.getlist('colony[]') %} if colony: str = str + "," + colony {% endfor %} queryset_list = queryset_list.filter(colony__in=[str]) Once queryset_list is formed, I am passing that as context to my Listings page which is working fine. Can someone please suggest what needs to be changes in template or views.py file. -
Using Dropdown values to set user ranks on creation
I have a user creation form in my Django web application. I am able to create a user normally. I have a model in my application called user_type, which has the is_admin field, is_manager field and the user field linked to the User Foreign Key. I have added a dropdown in my user creation form to enable the Admin create a user and as well assign the user_type of the user using the dropdown. I am now confused of how to grab the admin choice and enable the user_type depending on that. models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) # CUSTOM USER FIELDS firstname = models.CharField(max_length=30, blank=True, null=True) lastname = models.CharField(max_length=30, blank=True, null=True) telephone = models.IntegerField(blank=True, null=True) address = models.CharField(max_length=300) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) class user_type(models.Model): is_admin = models.BooleanField(default=False) is_manager = models.BooleanField(default=False) user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): if self.is_manager == True: return User.get_email(self.user) + " - is_manager" else: return User.get_email(self.user) + " - is_admin" views.py def AddUser(request): if … -
How to prevent staff users from editing/deleting superuser in django
I want to be able to allow certain staff users the rights to add other users and staff but what seems weird to me is that 1) a staff member can just change their own privileges to superuser or just make a new user and grant superuser privileges to them. 2) delete a superuser or revoke their superuser status Some staff users should be able to modify/create/delete users but they should not be able to delete super users nor assign permissions to themselves or other users that they do not have the permission themselves. This has always been logic I have incorporated into my user systems that I've written in PHP and I was just wondering if there was a way to change these settings in Django as I really like Python/Django (I'm just beginning to learn it) and can see myself migrating away from PHP. But part of the beauty for me lied in the admin panel and if that is something that cannot be changed, that's kind of cringe-worthy. It reminds me of a restaurant POS system that I used to use when I was a GM. As the GM, I had powers that shift managers did not …