Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django keeps logging me out from dev server when changing my codebase
In my Django app I have a lot of if request.user.is_authenticated logic and once I change some code other than in templates (like forms, models, views, etc.) I get logged out from the development server which makes it quite annoying to always have to re-login in the frontend to test my prior code changes again. Is there any way to stay logged in when in Debug = True (or other) mode? # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.getenv("DEBUG", "False") == "True" # Add s.th. here to keep me logged in? -
django-taggit similar_objects(): how to specify a model in the queryset
I use django-taggit on my site across several applications. The package uses a generic foreign key (by default), which allows it to work with many models, which is very convenient when working with tags and displaying different objects filtered by certain tags. But this default behaviour doesn't satisfy me when I try to find similar objects for example: # news/views.py class NewsDetailView(TagMixin, FormMixin, DetailView): model = News ... def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) related_items = self.object.tags.similar_objects()[:4] context['related_items'] = related_items return context In this case, I want to select similar news, but instead I get similar objects of all types, including articles or shop goods. Please tell me how can I specify my model in this command: related_items = self.object.tags.similar_objects()[:4] I want it to be News only. -
How to display an image from an external API as part of a response in Django
I have an external API that returns images and it requires a private key in order to access it. The content type it returns is 'image/jpeg'. I am creating an API with the Django Rest Framework that uses this API. I also have a model with some basic char entries, and I want to return both those model entries as well as the image in a response, with the goal of making AJAX calls to it in JS and displaying both the data and the image in HTML. I'm not exactly sure if I need to use Django forms? or if I can just make a call to the API in a plain js file hosted in my project? the latter would be ideal if I am able to send the image as part of the response... but ofcourse I don't want to expose the API key, which is part of the URL I am making a request to to get the image. I just want to essentially download the image and send it as a response. This is the current code I have been testing out: @api_view(['GET']) def random_image(request): response = requests.get('api url with secret key') if request.method == … -
Django migration error when using queryset in a Modelform
I use a queryset in a modelform instance to populate choices. However, when I now want to run the initial project db migration it returns django.db.utils.ProgrammingError: relation "core_category" does not exist LINE 1: ..._category"."name", "core_category"."fa_icon" FROM "core_cate... I tried to use a try - except block to work-around this but it didn't change the situation. So how to overcome this? As of course the categories table will be empty when migrating initially. class PollerForm(ModelForm): """ A form to create new Pollers """ # Get categories as choices, use try except # for initial migrations if no categories are available yet try: CHOICES = Category.objects.all() except (OperationalError, ProgrammingError) as e: CHOICES = [] # User instance will be passed in the view class Meta: model = Poller exclude = ('created_by',) category = forms.Select(choices=CHOICES) -
Reverse for 'products-by-sub-category' with arguments '('fantasy-fiction',)' not found
When I am using the get_url function in the SubCategroy model it gives an error like this. NoReverseMatch at /products/category/fiction/ Reverse for 'products-by-sub-category' with arguments '('fantasy-fiction',)' not found. 1 pattern(s) tried: ['products/\^category/\(\?P(?P<category_slug>[-a-zA-Z0-9_]+)\[\-\\W\]\+\)/\(\?P(?P<sub_category_slug>[-a-zA-Z0-9_]+)\[\-\\w\]\+\)/\$\Z'] there are no errors when I am not using {{sub_category.get_url }} in my HTML. but I want to use the URLs of each sub-category in the HTML. what did I do wrong? the way I used sub-categories maybe not be a good idea. if there are any good suggestions please add to your answer. also, I want to use language as also another categorizing criterion. is there a better or alternate way to implement this? My html {% if category_links %} {% for category in category_links %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle active" href="" data-bs-toggle="dropdown">{{ category.category_name }}</a> <ul class="dropdown-menu list-unstyled category-list "> {% if sub_category_links %} {% for sub_category in sub_category_links %} {% if sub_category.category_id == category.pk %} <li><a class="dropdown-item" href="{{ sub_category.get_url }}"> {{ sub_category.subcategory_name }} </a></li> {% endif %} {% endfor %} {% endif %} <li><a class="dropdown-item" href="{{ category.get_url }}"> View All </a></li> </ul> </li> {% endfor %} {% endif %} urls.py urlpatterns = [ path('', views.products, name="products"), path('category/<slug:category_slug>/', views.products, name='products-by-category'), path('category/<slug:category_slug>/<slug:sub_category_slug>/', views.products, name='products-by-sub-category'), path('language/<slug:language_slug>/', views.products_by_language, … -
Django form success messages on an HTML page with multiple forms
I am trying to display 2 forms in my contact.html page in a Django project. Each form needs to display a success message when being successfully submitted by users. The problem is that both forms in the page show the same success message when either of them being submitted. How can I tie the success message to the submitted form on my HTML page? forms.py from dataclasses import field, fields from logging import PlaceHolder from socket import fromshare from django import forms from .models import ServiceRequest, Contact, Newsletter class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ['name','email','phone','message'] class NewsletterForm(forms.ModelForm): class Meta: model = Newsletter fields = ['name','email'] views.py from http.client import HTTPResponse from multiprocessing import context from django.shortcuts import render from django.views.generic import TemplateView from .forms import ContactForm, NewsletterForm, ServiceRequest, ServiceRequestForm from django.http import HttpResponseRedirect from django.contrib import messages from django.urls import reverse def Contact(request): contact_form = ContactForm(request.POST or None) newsletter_form = NewsletterForm(request.POST or None) if request.method == 'POST' and contact_form.is_valid(): contact_form.save() messages.success(request, "Thanks for contacting us!") return HttpResponseRedirect(request.path_info) elif request.method == 'POST' and newsletter_form.is_valid(): newsletter_form.save() messages.success(request, "Thanks for joining our newsletter!") return HttpResponseRedirect(request.path_info) context = { "contact_form":contact_form, "newsletter_form":newsletter_form, } return render(request, "main/contact.html", context) contact.html {% extends "blog/base.html" %} … -
Django allauth Microsoft SSO
I'm having trouble configuring my SSO options for my Django project that I'm working on. I'm hoping to make it so that only those users in my organization are able to sign into the application but I keep getting the following error: AADSTS50194: Application 'Azure: Application (client) ID'(DjangoAppSSO) is not configured as a multi-tenant application. Usage of the /common endpoint is not supported for such applications created after '10/15/2018'. Use a tenant-specific endpoint or configure the application to be multi-tenant. I have gone in and populated the admin console with my Client ID being the same as above from the Azure account. I also created a Client Secret with my Value and Secret ID and put those in the admin console as well. I populated the Value as the "Key" in admin and Secret ID as the "Secret Key". All the required imports are done for settings.py and I believe the issue is in what I am giving the SOCIALACCOUNT_PROVIDERS possibly. settings.py: SOCIALACCOUNT_PROVIDERS = { 'microsoft': { 'APP': { 'tenant': 'organization', 'client_id': 'Azure: Application (client) ID', } } } Just for clarification sake, anywhere it says "Azure: Application (client) ID" is the actual value from there, I just don't want … -
I can't open my dashboard page in login Buttton? Why?
enter image description here I can't open my dashboard page in login button, I don't understand where is my fault. Please someone help me -
Why do we use underscore "_" in this python function using django?
_, filenames = default_storage.listdir("entries") return list(sorted(re.sub(r"\.md$", "", filename) for filename in filenames if filename.endswith(".md"))) So here is a function that returns a list of names. I am trying to understand how this function works but I don't understand what that underscore at the beginning is doing there. Thank you! -
Django signals weak=False
If I use Debug=false, the django signals stop working and I have to use week=false. I can't figure out why the default is week=true. I just figured out that it has something to do with the garbage collector. From the fact that I use week=false, does the garbage collector not run? Will the memory fill up with garbage over time and start a memory leak? Example use: @receiver(post_save, sender=sender, weak=False) def define_status(sender, instance, created, **kwargs): ..... -
django terminate adding any input to the database from the form
In an auction web. I'm trying to terminate adding any input (bids, comments and add to watchlist) by any user to the database if the owner of the product press on 'close ' button so I tried to implement this pseudo code: in views.py function listing: t = 1 if == 1: if owner clicks on the close button: ... t = 2 if the user adds a comment: ... if the user adds a bid: ... if user clicks on add to watchlist button: ... else: return message ('Auction has ended') I have implemented this code and the listing page accepted entries and inputs after the owner of the listing clicked on the 'close' button. I also tried to change the value of t to a boolean value ( t = True, if t == True, if user clicked: return t = False) but it didn't work. so what is the problem. def entry(request, name): enter = listing.objects.get(title = name) f= bids.objects.filter(product_id = enter) x = 0 z = "" last = None ended = None like = "k" l = 0 if request.method == 'POST' and request.POST.get("bid"): biddd = int(request.POST['bid']) user = request.user if biddd > x: bids.objects.create(bid= … -
I have a problem the form works but it does not send me the emails could you help me It is my first publication,
I have a problem the form works but it does not send me the emails could you help me It is my first publication, I honestly have no idea what it could be [CODE SETTINGS] EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST='smtp.gmail.com' EMAIL_USE_TLS=True EMAIL_PORT=587 EMAIL_HOST_USER='xxxxx@gmail.com' EMAIL_HOST_PASSWORD='xxxxxxxxxxxxxxxxx'** [** CODE VIEWS **] from django.shortcuts import render, redirect from .forms import FormularioContacto from django.conf import settings from django.core.mail import EmailMessage # Create your views here. def contacto(request): form=FormularioContacto() if request.method == "POST": form=FormularioContacto(data=request.POST) if form.is_valid(): nombre=request.POST.get("nombre") email=request.POST.get("email") contenido=request.POST.get("contenido") email= EmailMessage(f"Alguien quiere contactarse desde la WEB,El Usuario: {nombre} con el email: {email} por el asunto: {contenido}","",["torresfdev@gmail.com"],reply_to=[email]) email.send() try: return redirect("/contacto/?Enviadoconexito") except: return redirect ("/contacto/?NO_se_pudo_enviar") return render (request,"contactoapp/contacto.html", {"form":form}) -
how to create file txt and download using html in django
i have encrypt text and i want to create file txt which contains encrypt text and can be download the file via html. the encrypt file was in the function variable, how to get the result encrypt? and i don't know how to create file txt from another variable function. please help me with it. here's my encrypt code: def encrypt(key, pt): plaintext = read_file(pt) if isinstance(plaintext, str): pt= plaintext.encode("utf-8") print(pt) if len(key) <= key_bytes: for x in range(len(key),key_bytes): key = key + "0" print(key) assert len(key) == key_bytes # Choose a random, 16-byte IV. iv = Random.new().read(AES.block_size) # Convert the IV to a Python integer. iv_int = int(binascii.hexlify(iv), 16) # Create a new Counter object with IV = iv_int. ctr = Counter.new(AES.block_size * 8, initial_value=iv_int) # Create AES-CTR cipher. aes = AES.new(key.encode('utf8'), AES.MODE_CTR, counter=ctr) # Encrypt and return IV and ciphertext. ciphertext = aes.encrypt(pt) print(ciphertext) return (iv, ciphertext) #what i want to keep in new file is ciphertext and here's how i called that func: def homepage(request): form = AudioForm() if request.method == "POST": form = AudioForm(request.POST, request.FILES) if form.is_valid(): form.save() last_audio = Audio_store.objects.all().last() plaintext = Audio_store.objects.all().values_list('password').last() key = Audio_store.objects.all().values_list('key').last() pt = plaintext[0] ky = key[0] print(pt) print(ky) context={'form':form, … -
Django redirect another view from another app form
contact/views.py from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from .forms import ContactForm def contactView(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') # return redirect('success') return redirect('PostList') #another view from another app return render(request, "contact.html", {'form': form}) # def successView(request): # return HttpResponse('Success! Thank you for your message.') contact/urls.py from django.contrib import admin from django.urls import path from .views import contactView urlpatterns = [ path('contact/', contactView, name='contact'), # path('success/', successView, name='success'), ] blog/views.py from django.views import generic from .models import Post, PostImage # Create your views here. class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' class PostDetail(generic.DetailView): model = Post template_name = 'post_detail.html' def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet of all the books # context['image_list'] = PostImage.objects.all() # context['image_list'] = self.get_object().postimage_set.all() context['image_list'] = PostImage.objects.filter(post__slug=self.kwargs.get('slug')) return context blog/urls.py from . import views from django.urls import path urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), ] I need the following in the SIMPLEST … -
How to filter liked posts by User? (Django)
I'm trying to list all posts that are liked by userself. This is what i'm trying to code (likeapp/models.py) class LikeRecord(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='like_record') article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='like_record') class Meta: unique_together = ('user', 'article') (likeapp/views.py) @transaction.atomic def db_transaction(user, article): article.like += 1 article.save() # like_count = LikeRecord.objects.filter(article=article).count() if LikeRecord.objects.filter(user=user, article=article).exists(): raise ValidationError('Like already exists') else: LikeRecord(user=user, article=article).save() @method_decorator(login_required, 'get') class LikeArticleView(RedirectView): def get_redirect_url(self, *args, **kwargs): return reverse('articleapp:detail', kwargs={'pk': kwargs['pk']}) def get(self, *args, **kwargs): user = self.request.user article = get_object_or_404(Article, pk=kwargs['pk']) try: db_transaction(user, article) messages.add_message(self.request, messages.SUCCESS, '좋아요가 반영되었습니다') except ValidationError: messages.add_message(self.request, messages.ERROR, '좋아요는 한번만 가능합니다.') return HttpResponseRedirect(reverse('articleapp:detail', kwargs={'pk': kwargs['pk']})) return super(LikeArticleView, self).get(self.request, *args, **kwargs) (articleapp/models.py) class Article(models.Model): writer = models.ForeignKey(User, on_delete = models.SET_NULL, related_name = 'article', null = True) project = models.ForeignKey(Project, on_delete = models.SET_NULL, related_name = 'article', null = True) title = models.CharField(max_length=200, null=True) image = models.ImageField(upload_to='article/', null=False) content = models.TextField(null=True) price = models.IntegerField(default=0) amount = models.CharField(max_length=200, null=True) created_at = models.DateField(auto_now_add=True, null=True) like = models.IntegerField(default=0) (articleapp/views.py) class ArticleLikeListView(ListView): model = Article context_object_name = 'article_like_list' template_name = 'articleapp/likelist.html' def get_queryset(self): user = self.request.user queryset = LikeRecord.objects.filter() return queryset I'm trying to use filter() function to distinct liked posts by userself. How can I fix this code? Thank You! -
Get informations for each x seconds
I would like to know if there is a way to check every x seconds a value in a database table in django, and if it is the desired value, the user is redirected to another page. what i tried: I tried to use a form and it posts every 3 seconds and as soon as it makes the post it would check the table (model), but the page doesn't even load, because of sleep (it's worth mentioning that I tried SetTimeout and SetInterval) def wait(request, slug): form = MatchForm() if request.method == 'POST': roomName = Match.objects.get(roomname = slug) if (int(roomName.num_players) > 1): return redirect(f'../play/{slug}') return render (request, 'chess/waiting_room.html', {'slug':slug, 'form':form}) waiting_room.html - javascript function sleep(milliseconds) { const date = Date.now(); let currentDate = null; do { currentDate = Date.now(); } while (currentDate - date < milliseconds); } subm_form() function subm_form(){ var form = $("#form") form.submit(); sleep(3000) subm_form() }; -
Use django formset for only a few specific fields
I am relatively new to django (about 3 months using it) and ran into the following problem at work. I have a model with several fields, and they asked me that of those fields, 4 specifically should be able to dynamically add another register, that is, if i register something in one of those fields, there should be the option to do it again indefinitely. I understand that this can be achieved using formset but all the examples I find are using all the fields of the model and not just a few. Any ideas on what I can do? this is the model class Mercancia(SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE id = models.AutoField(primary_key=True) factura = models.ForeignKey("Factura", on_delete=models.CASCADE) desc_mercancia = models.CharField(max_length=256, validators=[RegexValidator(r'^[0-9a-zA-Z\s]*$', 'La descripción de la mercancia no acepta caracteres especiales.')]) comercio = models.ForeignKey("ClaveComercio", on_delete=models.CASCADE) tipo_moneda = models.ForeignKey("Moneda", on_delete=models.CASCADE) cantidad_comerc = models.DecimalField(max_digits=30, decimal_places=0) valor_unitario = models.DecimalField(max_digits=22, decimal_places=6, validators=[MinValueValidator(0)]) valor_total = models.DecimalField(max_digits=22, decimal_places=6, validators=[MinValueValidator(0)]) valor_total_dolares = models.DecimalField(max_digits=20, decimal_places=4, validators=[MinValueValidator(0)]) marca = models.CharField(blank = True, max_length=35, validators=[RegexValidator(r'^[0-9a-zA-Z\s]*$', 'El modelo solo permite valores alfanuméricos.')]) modelo = models.CharField(blank = True, max_length=50, validators=[RegexValidator(r'^[0-9a-zA-Z\s]*$', 'El modelo solo permite valores alfanuméricos.')]) submodelo = models.CharField(blank=True, max_length=50, validators=[RegexValidator(r'^[0-9a-zA-Z\s]*$', 'El submodelo solo permite valores alfanuméricos.')]) numero_serie = models.CharField(blank = True, max_length=25, validators=[RegexValidator(r'^[0-9a-zA-Z\s]*$', … -
ModuleNotFoundError: No module named 'django' after adding specific path into the global .bashrc file
I am getting this weird messages: it says Couldn't import Django when I type this on command line: python3 manage.py startapp engine I have found out that the Django is located in: /home/h/hswong00/miniconda3/lib/python3.9/site-packages But the way I found out where it is located is by loading python, not python 3. But I need python3, not python for my work. So when I typed: in linux terminal: python after loading python in terminal: import sys : sys.path that's how I found out where Django is installed. So I googled for some solution here, and I found that I could tried edit the bashrc file by adding: export PYTHONPATH="${PYTHONPATH}:/home/h/hswong00/miniconda3/lib/python3.9/site-packages" to the .bashrc file. But still when I type: python3 manage.py startapp engine it still produces the same error message. And indeed after loading python3 and typing sys.path, I also don't see the path: /home/h/hswong00/miniconda3/lib/python3.9/site-packages I am just wondering did I not edit the .bashrc file correctly so that python3 will search for that directory (python3.9/site-packages)? if I have done it correctly, how come that path doesn't show up when sys.path after loading python3? could someone points out where my error is? I have searched for many of the previous posts regarding this … -
How to access MTM field with through setting to template
price = models.ManyToManyField("price.Price", verbose_name='Ціни', through='services_count', through_fields=('service','price'), blank=True) and through model class services_count(models.Model): quantity = models.IntegerField(verbose_name='Кількість цієї послуги у сервісі', null=True) service = models.ForeignKey("medservices.Medservices", verbose_name='Послуга або акція', on_delete=models.CASCADE,default=None) price = models.ForeignKey("price.Price", verbose_name='Ціна яка', on_delete=models.CASCADE, default=None) views.py def service_page(request, post_slug): post_content = Medservices.price.through.objects.all() post = get_object_or_404(Medservices, slug=post_slug) post_dict = {'post_rows':post , 'post_alt':post_content,} return render(request, 'medservices/service.html', context=post_dict) So i want to have oportunity to access service_count model through model with MTM field -
Dificuldade em salvar Mater/Detail com Django REST framework
Estou tentando salvar os dados em uma API Django REST framework, mas mesmo depois de muitas mudanças no código sempre retorna a mensagem de que o objeto pai não existe quando tenta adcionar os objetos filho. Não tenho muita experiencia com Django Rest e consegui chegar até esse ponto com alguns posts aqui mesmo do stackoverflow: Toda ajuda é bem vinda e desde ja agradeço. JSON enviado pelo app: { "unity": "PL20220831T143756903", "pallet": 2, "employee": 1, "quantity": 3, "variety": 2, "maturation": 1, "box": 2, "producer": 1, "processed": false, "packers": [ { "unity": "PL20220831T143756903", "packer": "E0001B0000000001F", "packing_date": "2022-08-31T14:38:23.017756-03:00" } { "unity": "PL20220831T143756903", "packer": "E0001B0000000002F", "packing_date": "2022-09-01T13:00:23.016766-03:00" } ] } Serializer que recebe os dados: class PendingPalletDetailSerializer(serializers.ModelSerializer): """ API Pallets Pendentes Detalhes """ class Meta: model = PendingPalletDetail fields = ( 'unity', 'packer', 'packing_date', ) class PendingPalletTotSerializer(serializers.ModelSerializer): """ API Pallets Pendentes """ packers = PendingPalletDetailSerializer(many=True) class Meta: model = PendingPallet fields = ( 'unity', 'pallet', 'employee', 'quantity', 'variety', 'maturation', 'box', 'producer', 'person', 'date_in_cold_chamber', 'date_out_cold_chamber', 'processed', 'packers', ) def create(self, validated_data): details_data = validated_data.pop('packers') # grab the data on details pendingpallet = PendingPallet.objects.create(**validated_data) # create the master reservation object for reservation_detail in details_data: # create a details_reservation referencing the master reservation PendingPalletDetail.objects.create(**reservation_detail) return … -
django add pdf to a request value
in the following request I receive a total of 10 pdfs which I must combine in one document once this is done I have to upload it to the client model which stores the files in aws s3, once I pass the file with all the pdfs together it gives me the following error { "error": true, "message": { "documents": [ "The submitted data was not a file. Check the encoding type on the form." ] } } this is mi code merger = PdfFileMerger() for x in request.FILES: print(request.FILES[x]) merger.append(request.FILES[x]) merger.write(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'media/' + str(getUser.id) + '.pdf')) merger.close() pdf = open(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'media/' + str(getUser.id) + '.pdf'), 'rb') # set the client Data clientData = { 'type_client': request.data['type_client'], 'type_identity': request.data['type_identity'], 'document_number': request.data['document_number'], 'first_name': request.data['first_name'] if 'first_name' in request.data else None, 'last_name': request.data['last_name'] if 'last_name' in request.data else None, 'social_reason': request.data['social_reason'] if 'social_reason' in request.data else None, 'address': request.data['address'], 'city': request.data['city'], 'email': request.data['email'], 'phone_number': request.data['phone_number'], 'ciiu': request.data['ciiu'], 'broker': request.data['broker'], 'user': getUser.id, 'documents': pdf, 'status': 0, 'income': request.data['income'], 'entered_by': request.user.id } # Create a new client client = ClientSerializer(data=clientData) this is my model from django.db import models # Relations from apps.misc.models import City, TypeIdentity, TypeCLient, CIIU from apps.clients.api.models.broker.index import Broker from apps.authentication.api.models.user.index import … -
Where Can I Find the The Setting.py File For PostgreSQL?
I am trying to install PostgreSQL to work with Django. I searched my hard drive for the PostgreSQL settings.py file but could not find what I was looking for. I found one under the PgAdmin folder (C:/Program Files/PostgreSQL/14/pgAdmin 4/python/Lib/site-packages/azure/core/settings.py), but it does not appear to be what I'm looking for. All of the documentation that I find says that I have to have the following in my settings.py file for PostgreSQL to work with Django: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'db_name', 'USER': 'db_user', 'PASSWORD': 'db_user_password', 'HOST': '', 'PORT': 'db_port_number', } } I cannot find the file to place the setting in it. Where should I be able to find it, or where should I create it? What else should be in the file? -
I want to get the top 8 latest products of each category in django
This is my product_views.py This is serializers.py While printing products in terminal everything looks good, but after serializing product attributes becomes null -
Django test to check for pending migrations
Django has a --check argument that let's you check if migrations need to be created for your project. This is relatively easy to add in CI, but that won't perform the check on developer computers. I want to add this check as a unit test in my Django project, so that it is covered when developers run our test suite. What is a good way to accomplish that? -
problem after moving from sqllite3 to postgresql database in django
enter image description hereI have changed an existing database for a Django project from SQLite3 to PostgreSQL. As presently i am in development environment, and was carrying some dummy data in my SQlite3 so do not need that data. After changing the database from sqlite3 to PostgreSQL, I run the makemigrations, and migrate commands, and then created a super user. Now when i try to access the admin panel, by http://127.0.0.1:8000/admin/ django is showing me the following error. I have search a lot for the solution, but failed. I would be grateful, if you could please help me in this. errorerror2