Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
users can not login by custom login model django
i am going to use a dual authentication system (email, username). when i create users by "createsuperuser" users can login but when i create users inside admin panel of django user can not login and also i noticed the user's password which is made in admin panel is not hashed in DB! backend.py: class EmailBackend(backends.ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): if username is None: username = kwargs.get(UserModel.USERNAME_FIELD) try: user = UserModel.objects.get(Q(username__iexact=username) | Q(email__iexact=username)) except UserModel.DoesNotExist: UserModel().set_password(password) else: if user.check_password(password) and self.user_can_authenticate(user): return user return super().authenticate(request, username, password, **kwargs) models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ class User(AbstractUser): email = models.EmailField(_('email address'), unique=True, null=False, blank=False) def __str__(self): return self.email -
How to solve Django custom admin site NoReverseMatch when registering models?
I want to create a custom Admin site for one of the apps in my Django project. This app has a couple of models that I want to register on the admin site. The thing is that if I register all the models of the app in this custom Admin site, I get the following error: NoReverseMatch at /admin/auto-harvest/ Reverse for 'app_list' with keyword arguments '{'app_label': 'my_app'}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>auth|django_mfa|axes)/$'] However, if I register all models but except the last one, I don't get the error, and the admin site loads successfully with the exception that one of the models is not registered. I found this behavior very peculiar and can't figure out the reason. Below is my admin.py and the urls.py class MyAdminSite(AdminSite): site_header = "My Admin" site_title = "My Admin Site" my_admin_site = MyAdminSite(name='auto_harvest') Registering models: @admin.register(MyModel1, site=my_admin_site) class MyModel1Admin(VersionAdmin): ... @admin.register(MyModel2, site=my_admin_site) class MyModel2Admin(VersionAdmin): ... In the project urls I have: urlpatterns = [ path('admin/my-site/', include(myapp.urls)), ] In myapp.urls I have: urlpatterns = [ path('', my_admin_site.urls), ] -
Multiple like feature in django
I want to create a like feature for the posts and comments in which the number of likes increases each time when a user hits the end point. I have used the Generic Foreign Key for linking and want to override the create function as post request is not idempotent and does not allow to create an identical request for the like from the same user. here, it's the create method in my Like serializer: def create(self, validated_data): like = validated_data.get("like") if user: main_user = user else: main_user = User.objects.all().first() model_type = self.model_type like = Like.objects.create_by_model_type( model_type,obj_id, like, main_user, ) return like views.py: class LikeCreateAPIView(CreateAPIView): queryset = Like.objects.all() permission_classes = [IsAuthenticated] def get_serializer_class(self): model_type = self.request.GET.get("type") obj_id = self.request.GET.get("obj_id") return create_like_serializer( model_type=model_type, obj_id=obj_id, user=self.request.user ) -
How to match field of different table in Django
I'm using Django as backend, PostgresSQL as DB, and HTML, CSS, and Javascript as frontend. I got stuck to match the field and retrieve specific data in Django. class Motor(models.Model): . . code = models.CharField(max_length=100) . . class Drum(models.Model): . . code = models.CharField(max_length=100) . . class Cart(models.Model): . . motor = models.ForeignKey(Motor, on_delete=models.CASCADE,null=True, blank=True) drum = models.ForeignKey(Drum, on_delete=models.CASCADE,null=True, blank=True) . . Now in the Above model, there is the cart Model which saves the data of the Motor Model or else saves the data of the Drum Model or both. So for example If the user saves the data of the Motor Model in the Cart Model. The data which is saved in the Cart model should match the code field with model Drum and should filter the data accordingly. So, I have done something like this. views.py def Drum(request): drum_filter = Drum.objects.filter(code__in=Cart.objects.all().values_list('code', flat = True)) return render(request, 'list/drum.html', {'drum_filter':drum_filter} ) But now the problem is: The code field in Cart goes as child table and my parent table is Motor. something like this: [ { "id": 4, "quantity": 1, "user": { "id": 4, }, "motor": { "id": 9, "name": "...", "title": "....", . . . "code": "DD1" }, … -
Is it possible to store some HTML code in "context" and then make it work on one of the templates?
My goal is to get this table's code from another website using selenium, store it in the context dictionary to then place it in one of the templates in a way that it won't show the code as text but it will make it part of the page's code itself. tab = driver.find_element_by_class_name("table-responsive") tab = tab.get_attribute("outerHTML") context = {'tab': tab, } This way I already managed to store the code in the context dictionary and then I used the Django built-in function to pass the context keys to templates {{ tab }}. I'm trying to understand if it's possible to make it work as proper HTML code in a template even if it's just a key in a dictionary. -
Functions inside a Django model
Is it possible to write custom functions inside a Django model? And if it is, how can I do it properly. I'm currently doing a practice project of an ecommerce, and I want to change a boolean field value based on the value of an integer field. I currently have this: class Product(Model): name = CharField(max_length=64) desc = CharField(max_length=256) price = DecimalField(decimal_places=2, max_digits=6) available = BooleanField(default=True) quantity = IntegerField() category = ManyToManyField(Category) def availability(self): if self.quantity == 0: self.available = False self.save() return self.available def __str__(self): return self.name I know that I'm not calling the function, but I want that to be called once the product is updated even on the admin panel, is that possible to do? And I'm not really confident about that return in the function, I don't feel like that is correct. Thanks in advance. -
Tailwindcss LSP for Neovim root_dir issue
I am having an issue with the Tailwind LSP in Neovim 0.5 where the language server running however I get no intellisense when defining a class. I am working on a django project and tailwind is all setup with the following structure. . ├── .git/ ├── .venv/ ├── node_modules/ ├── src/ └── static/ ├── package.json ├── postcss.config.js └── tailwind.config.js I have set the "root_dir" setting in the tailwind lsp setup to: lsp.util.root_pattern('tailwind.config.js') orlsp.util.root_pattern('tailwind.config.js', '.git', 'postcss.config.js')etc, but with no success. The only way I can get intellisense is if I place a html file right in the root next to the tailwind.config.js and edit it. Has anyone else come across this and might know where I am going wrong. Appreciate any help, thanks -
How to cache class based view and objects separately in django
Currently i am caching the django class based view as shown below. views.py @method_decorator([vary_on_cookie, cache_page(86400)], name='dispatch') class itemviewset(viewsets.ModelViewSet): serializer_class = ItemtSerializer # is a ModelSerializer def get_queryset(self): if self.request.method=="GET": cart_name=self.request.query_params.get('cart') return item.objects.filter(cart_name=cart_name).order_by("-created_at") else: return item.objects.all().order_by("-created_at") @auth def dispatch(self,request,*args,**kwargs): return super(itemviewset,self).dispatch(request,*args,**kwargs) settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'product_cache', } } There are other views cached as well. The above cache configuration impacts /item and /item/{id}/ paths. Below are the implementation i'm looking for : cache to be impacting only /item and for every items (objects) in path /item/{id}/ new cache has to be created changes to individual item i.e /item/{id}/ should not alter the /item path cache if new item is added or old item is deleted i.e post,delete call to /item/, it should update or (delete and set) the /item cache. whole cache should not be deleted as i have other views cached as well. Is it possible to do the above operation in django? could some one help me out to implement this? -
Django Efficiency For Data Manipulation
I am doing some data changes in a django app with a large amount of data and would like to know if there is a way to make this more efficient. It's currently taking a really long time. I have a model that used to look like this (simplified and changed names): class Thing(models.Model): ... some fields... stuff = models.JSONField(encoder=DjangoJSONEncoder, default=list, blank=True) I need to split the list up based on a new model. class Tag(models.Model): name = models.CharField(max_length=200) class Thing(models.Model): .... some fields ... stuff = models.JSONField(encoder=DjangoJSONEncoder, default=list, blank=True) other_stuff = models.JSONField(encoder=DjangoJSONEncoder, default=list, blank=True) tags = models.Many2ManyField(Tag) What I need to do is take the list that is currently in stuff, and split it up. For items that have a tag in the Tag model, add it to the Many2Many. For things that don't have a Tag, I add it to other_stuff. Then in the end, the stuff field should contain of the items that were saved in tags. I start by looping through the Tags to make a dict that maps the string version that would be in the stuff list to the tag object so I don't have to keep querying the Tag model. Then I loop … -
Django: Browser button for accessing previous web page is not working
I have a Django view A and a Django view B. A button is displayed on A so that you can go to B. Then when you are viewing B, the previous-web-page browser button does not do anything at all. Do you know about any configuration so as to check what the URL is when using browser buttons? Or in general, is there any way to set to where the previous-web-page browser button is going to redirect the user? -
Django filling dropdown in html from database
I am learning Django. I want to make manual add form for person model but this person model has relations with 2 another model. I couldn't figure out how to solve when I want to add person how to fill another related fields from other models. This is my person model class Patient (models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=256) data = models.JSONField() intensivecare_forms_data_id = models.OneToOneField( Intensivecare_Forms_Data, on_delete=models.CASCADE) Intensivecare_form = models.ManyToManyField(Intensivecare_Form) def __str__(self): return f'Id = {self.id}, name = {self.name}' I want to make a form that has name field, data field, icformsdataid field and i.._form field but those related fields must be dropdown. This is my view def addPatient(request): if request.method == 'POST': icareform = Intensivecare_Form.objects.filter() patient = Patient(name=request.POST.get("fname"), data=request.POST.get("lname"), Intensivecare_Form=request.POST.get("cform")) try: patient.full_clean() patient.save() except ValidationError as e: # Do something based on the errors contained in e.message_dict. # Display them to a user, or handle them programmatically. return HttpResponse("Your form is wrong, try again") return render(request, {'item':icareform}, 'index.html') And this is html page. <form action="" method="post"> {% csrf_token %} <label for="fname">First nddame:</label><br> <input type="text" id="fname" name="fname"><br> <label for="lname">Data:</label><br> <input type="text" id="lname" name="lname" value='{"test":"test"}'><br><br> <label for="care-form">Care Form:</label><br> <input type="text" id="care-form" name="cfrom"><br><br> {{item}} <input type="submit" value="Submit"> </form> -
Unit testing error in django rest frameframework
I am getting following error while running unit test but while posting from postman it works fine. {'users': [ErrorDetail(string='This field is required.', code='required')]} My serializer.py: class UserSerializer(serializers.Serializer): first_name = serializers.CharField(max_length=60, allow_blank=False) last_name = serializers.CharField(max_length=60, allow_blank=False) email = serializers.EmailField(max_length=100, allow_blank=False) class CompanySerializer(serializers.Serializer): users = UserSerializer(many=True, write_only=True) class Meta: model = Company fields = '__all__' extra_kwargs = { 'tech_tags': {'required': False} } Here is my unit test. tech_tags is not required in serializer but it shows tech_tags required error during test.Users data also shows required error even though users data is sent in request payload. def test_create_company(self): request_data = { "name": "Test Company", "users": [ { "first_name": "Test Name.", "last_name": "Test Name.", "email": "email", } ] } request = self.factory.post('/api/company', request_data) view = CompanyViewSet.as_view({'post':'create'}) force_authenticate(request, user=self.admin_user) response = view(request) self.assertEqual(response.status_code, 201) Here even though users is sent in payload but it show error: {'users': [ErrorDetail(string='This field is required.', code='required')]} -
How to send email when save method is triggered in django admin panel
I have used the default Django admin panel as my backend. I have a Blogpost model. What I am trying to do is whenever an admin user saves a blogpost object on Django admin, I need to send an email to the newsletter subscribers notifying them that there is a new blog on the website. Since Django admin automatically saves the blog by calling the save function, I don't know where to write send email api logic. Hope I have explained it well. My Blogpost: class BlogPost(models.Model): author = models.CharField(max_length=64, default='Admin') CATEGORY_CHOICES = ( ('travel_news', 'Travel News',), ('travel_tips', 'Travel Tips',), ('things_to_do', 'Things to Do',), ('places_to_go', 'Places to Go'), ) image = models.ImageField(blank=True, null=True) title = models.CharField(max_length=255) categories = models.CharField(max_length=64, choices=CATEGORY_CHOICES, default='travel_news') caption = models.CharField(max_length=500) content = RichTextUploadingField() # todo support for tags # tags = models.CharField(max_length=255, default='travel') #todo tag = models.ManyToManyField(Tag) date_created = models.DateField() I have overwritten the Django admin form by my model form like this. class BlogForm(forms.ModelForm): CATEGORY_CHOICES = ( ('travel_news', 'Travel News',), ('travel_tips', 'Travel Tips',), ('things_to_do', 'Things to Do',), ('places_to_go', 'Places to Go'), ) # categories = forms.MultipleChoiceField(choices = CATEGORY_CHOICES) class Meta: model = BlogPost fields = ['author','image', 'title','categories', 'caption','content','tag','date_created'] @register(BlogPost) class BlogPostAdmin(ModelAdmin): # autocomplete_fields = ['author'] … -
How to achieve row num functionality in Django?
I need only 5th and 30th record (from top) in the below query set? qs=Posts.objects.filter().orderby('-date') is there any rownum functionality available in django to achieve this in a single query like rownum=5 ??. Note: I am using Postgres -
Django mixin returning old value
I wrote a mixin with some properties - submit url and redirect url. which is being inherited in two different classes. But i observed class FormSubmissionMixin: success_url = None success_url_kwargs = {} success_url_params = {} submit_url = None submit_url_kwargs = {} submit_url_params = {} def get_success_params(self): return self.success_url_params def get_success_kwargs(self): return self.success_url_kwargs # get_success_url is not overridden, so using another name as aux function def get_redirect_url(self): kwargs = self.get_success_kwargs() return afl_reverse(self.success_url, self.request, kwargs=kwargs) def get_submit_params(self): return self.submit_url_params def get_submit_kwargs(self): return self.submit_url_kwargs def get_submit_url(self): kwargs = self.get_submit_kwargs() return afl_reverse(self.submit_url, self.request, kwargs=kwargs) then I used it in a create view as well as update view class CustomCreateView(generic.CreateView, FormSubmissionMixin): model = None form_class = None template_name = 'create_form.html' success_msg = "Created Successfully" fail_msg = "Submission Failed" def get_success_url(self): return self.get_redirect_url() def get_form(self): form = super().get_form() form.action = self.get_submit_url() form.method = 'POST' return form class CustomUpdateView(generic.UpdateView, FormSubmissionMixin): param = 'pk' model = None form_class = None template_name = 'update_form.html' success_msg = "Updated Successfully" fail_msg = "Update Failed" def get_success_url(self): return self.get_redirect_url() def get_submit_kwargs(self): urlKwargs = super().get_submit_kwargs() urlKwargs[self.param] = self.kwargs.get(self.param) return urlKwargs def get_form(self, *args, **kwargs): form = super().get_form() form.action = self.get_submit_url() form.method = 'POST' return form Then i have two views for them as … -
Save invoice formset by peaking main form foreign key in django
Please help am a beginner on django, i want to save my invoice in database, the problem i facing is when i want to save formset i cant peak foreign key from main form View.py def createInvoice(request):` if request.method == 'GET':` formset = LineItemForm(request.POST or None)` form = InvoiceForm(request.GET or None) if request.method == 'POST': formset = LineItemForm(request.POST) form = InvoiceForm(request.POST) if form.is_valid(): invoice = Invoice.objects.create(customer = form.data["customer"], customer_email = form.data["customer_email"], message = form.data["message"], date = form.data["date"], due_date = form.data["due_date"], ) if formset.is_valid(): for form in formset: service = form.cleaned_data.get('service') description = form.cleaned_data.get('description') quantity = form.cleaned_data.get('quantity') rate = form.cleaned_data.get('rate') LineItem(customer=invoice, service=service, description=description, quantity=quantity, rate=rate, amount=amount).save() invoice.save() return redirect('/') context = {"title" : "Invoice Generator","formset":formset, "form": form} return render(request, 'home/invoice.html', context) Here is my Model.py class Invoice(models.Model): customer = models.CharField(max_length=100) customer_email = models.EmailField(null=True, blank=True) message = models.TextField(default= "this is a default message.") date = models.DateField() due_date = models.DateField() def __str__(self): return str(self.customer) class LineItem(models.Model): customer = models.ForeignKey(Invoice, on_delete=models.CASCADE) service = models.TextField(max_length=100) description = models.TextField(max_length=100) quantity = models.IntegerField(max_length=10) rate = models.DecimalField(max_digits=9, decimal_places=2) amount = models.DecimalField(max_digits=9, decimal_places=2) def __str__(self): return str(self.customer) This is my invoice create template without main form. Main form does not have any problem invoce.html <table class="table is-fullwidth is-bordered is-hoverable … -
psycopg2.errors.UndefinedColumn: column "category_id" of relation "libman_books" does not exist
I don't know what mistake occurred. I added a model to my system, created a relation to another model. When I deployed, an error was experienced. This is a system that already has user data and therefore interfering with the database will be a disaster. Here is the log. Applying libman.0004_auto_20210711_2242...Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column "category_id" of relation "libman_books" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/migrations/operations/fields.py", line 166, in database_forwards schema_editor.remove_field(from_model, from_model._meta.get_field(self.name)) … -
Unable to Apply CSS on my HTML file Django
I have seen alot of solutions here regarding this issue but unable to resolve my problem, I am trying to apply my style.css present on this path \...\static\css I have following directory structure as can be seen in image below: My settings.py is as follows: from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-......' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bar_chart', 'line_chart', 'Aqi_dash.core', 'crispy_forms', ] CRISPY_TEMPLATE_PACK = 'bootstrap4' 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 = 'Aqi_dash.urls' TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates') TEMPLATES_DIR_2= os.path.join(BASE_DIR,'Aqi_dash/templates') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ TEMPLATES_DIR,TEMPLATES_DIR_2, ], 'APP_DIRS': True, 'OPTIONS': { ], }, }, ] WSGI_APPLICATION = 'Aqi_dash.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE':'django.db.backends.postgresql_psycopg2', 'NAME':'db_sensors', 'USER':'postgres', 'PASSWORD':'....', 'HOST':'....', 'POST':'5432', 'ATOMATIC_REQUESTS':True, } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' #EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "css"), 'static',] #print(STATIC_DIR) While my index.html which … -
Django Ulrs matched path but still 404
I have a bug and not sure how to fix it, I've been writing an e-comm site and all of a sudden I'm getting a 404 page, Everything was working fine. The bug report tells me that the path matched the last one, but still getting 404. It's not only one app, it's all of them. I just have on Clue how to fix this? Please can a fresh set of eyes help me. Thank you in advance. Here is everything. Settings: from pathlib import Path import environ import os import dj_database_url env = environ.Env() # read the .env file environ.Env.read_env() BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = env('SECRET_KEY') DEBUG = True ALLOWED_HOSTS = ['*'] TAX_RATE_PERCENTAGE = 23 FREE_DELIVERY_THRESHOLD = 200 # Application definition INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', 'django.contrib.sites', 'cloudinary_storage', 'cloudinary', 'allauth', 'allauth.account', 'allauth.socialaccount', 'mathfilters', 'crispy_forms', 'ckeditor', 'home', 'boutique', 'bag', 'checkout', 'profiles' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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 = 'IMC.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [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', 'django.template.context_processors.media', 'bag.contexts.bag_contents', ], 'builtins': [ 'crispy_forms.templatetags.crispy_forms_tags', 'crispy_forms.templatetags.crispy_forms_field', ] }, }, ] AUTHENTICATION_BACKENDS = [ # Needed to … -
YouTube Downloader without using any inbuilt libraries
I just want to build a web application to download YouTube videos either in Django or using Node JS. But I don't want to use the inbuilt libraries like pytube or node-ytdl-core. can anyone help me out -
How in Django filter queryset by related objects
For example i have such models: class Sale(models.Model): name = models.CharField(max_length=100) some fields ... class Book(models.Model): some fields ... class BookInSale(models.Model): name = models.CharField(max_length=100) sale = models.ForeignKey(Sale, on_delete=models.CASCADE, related_name='books') So i want take that objects of Sale model which contains BookInSale objects with some name. For example there is 3 objects of Sale with related BookInSale: Sale1 - BookInsale[name='Book1'], BookInSale[name='Book2']; Sale2 - BookInsale[name='Book1']; Sale3 - BookInsale[name='Book2'], BookInSale[name='Book3']. And i whant to take only that Sale objects which has BooksInSale object with name 'Book1' -
how to change language in django-ckeditor-5
hello I'm working on a django project. I want to change language of django-ckeditor-5 How should I do this? and is django-ckeditor-5 package same as django-ckeditor package ? -
How to check if image exists
I have run into trouble trying to show an image in my web app. I would like to show an image and if that image for certain variable doesn't exist, I would like to show a default image. My code looks like this: <div class="re-img"> {% if url_for('static', filename='img/' + data.UNIQUE_RE_NUMBER[i].replace('/', '-') + '.jpg') %} <image class="re-img-unique" src="{{url_for('static', filename='img/' + data.UNIQUE_RE_NUMBER[i].replace('/', '-') + '.jpg')}}"> {% else %} <image class="re-img-unique" src="{{url_for('static', filename='img/default.jpg')}}"> {% endif %} </div> This way it doesn't show my default image and the whole if statement doesn't work. Its obvious, but I can't think of anything that would work in this scenario. -
Is Django Framework the right choice?
I have used the Django framework for small projects. Recently I am developing a career portal. I also might have to build Android and IOS apps for the same in future. I am confused about whether I have to use Django Framework for the web portal and later create a separate Rest framework for the apps. Or should I use Django Rest API now itself? Also, this project has some modern yet complex front-end UI. Will I be able to implement this in Django templating system or should I use front-end frameworks like AngularJs or ReactJs for the frontend and Django Rest API for the backend? Please guide me in the right direction. -
Django serializer Field for Multiple inputs
"document_no": "PS-31015,PS-31016" document_no = serializers.CharField(max_length=200) Want to have a Django serializer with field 'document_no' which could recognize PS-31015 and PS-31016 as 2 inputs.