Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Remote python debug on vscode got ETIMEDOUT
Hi I want to debug django on remote docker server. Here is my attempt: version: '3' services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver --noreload 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" - "9000:9000" environment: - DJANGO_DEBUG=1 depends_on: - db Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt # COPY . /code/ manage.py { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Remote Django App", "type": "python", "request": "attach", "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/code" } ], "port": 9000, "host": "192.168.2.153" } ] } launch.json { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Remote Django App", "type": "python", "request": "attach", "pathMappings": [ { "localRoot": "${workspaceFolder}", "remoteRoot": "/code" } ], "port": 9000, "host": "192.168.1.15" } ] } Expected: breakpoint hit. Actually happened: ETIMEDOUT 192.168.1.15 9000 I can actually telnet 192.168.1.15 9000 with result: Content-Length: 130 {"type": "event", "seq": … -
Django Admin add/change disable a field based on previews field choice
in my django admin project i have this model: class m_pcontent(models.Model): MY_CHOICES = ( ('T', 'Text'), ('I', 'Image'), ) p_id = models.ForeignKey(m_pages, on_delete=models.CASCADE) p_type = models.CharField(max_length=1, choices=MY_CHOICES) p_content = models.TextField(null=True, blank=True) p_images = models.ForeignKey(m_pimg, on_delete=models.CASCADE, null=True, blank=True) ... and in my admin.py class m_pcontentAdmin(admin.ModelAdmin): list_display = ('p_id', 'p_type', 'p_lang', 'p_dload', 'p_active') list_filter = ('p_id', 'p_type', 'p_lang') ordering = ('p_id', 'p_type') readonly_fields = [...] i would to dinamically make readonly the p_content field or the p_images field based on what user choice in p_type fiels in ADD/change area (if chose Text p_images have to become readonly, otherwise if choose Image p_content have to become Readonly) Someone can elp me? so many thanks in advance -
Auto incrementing field name in Django
I am trying to build an app where you can, among other things, make a meal plan. I'm working on the version where you make a plan for a month. I'm using Django, writing in python, and using SQLite as my database. The problem I have is regarding user input and databases. Instead of making a form with 30 fields, I want to make one with a single field that changes its name for each time the user has entered a response. An example of this would be something like this: The first time the user enters an input: Meal day 1:_______ The second time: Meal day 2:______ In simple terms, I want the integer in the field name to change. Here's some pseudo code, it might be a mix of C# and python atm: "Day " + x x=1 if x < 30 display add button x++ elif x == 30 display add button display the confirm button x++ elif x == 31 display only the confirm button else x > 31 x = 31 Can anyone give me a template for something like this, or point me in the right direction with a function/word I can search for … -
Deleting comments from a post: NoReverseMatch while trying to delete comment of a post
I am quite new to django and web development and trying to delete the comment from posts, and has provided a class based view, but I am getting this error while running the code. Reverse for 'delete_comment' with no arguments not found. 1 pattern(s) tried: ['posts/(?P<slug>[^/]+)/(?P<comment_id>[0-9]+)/delete/$'] I have provided the comment section below and you can find the delete section towards the last. comment-section.html {{ comments.count }} Comment{{ comments|pluralize }} {% for comment in comments %} <blockquote class="blockquote"> <img style="float:left; clear: left;" class="rounded-circle article-img" height="50" width="50" src="{{ comment.user.profile.profile_pic.url }}"><a href="" style="text-decoration: none; color: black;"><h6>{{ comment.user.first_name|capfirst }} {{ comment.user.last_name|capfirst }}</h6></a><br> <p style="font-size: 8px;">{{ comment.timestamp }}</p> <p style="font-size: 14px;" class="mb-3">{{ comment.content }}</p> <a type="button" name="button" class="reply-btn ml-4"><p style="font-size: 13px;"> Reply</p></a> {% if request.user == comment.user %} <a href="{% url 'posts:delete_comment' comment.id %}" style="font-size: 13px;text-decoration: none; color: #000;" hover="background-color:red">Delete</a></td> {% endif %} views.py class DeleteCommentView(BSModalDeleteView, LoginRequiredMixin, UserPassesTestMixin): model = Comment template_name = 'posts/comment_delete.html' success_message = 'Deleted' def get_success_url(self): return reverse_lazy('posts:detail_post') def test_func(self, comment_id): comment = self.get_object(self.comment_id) if self.request.user == comment.user: return True return False urls.py path('<slug>/<int:comment_id>/delete/', DeleteCommentView.as_view(), name='delete_comment'), Please do let me know how can I let users delete their comments from the post. It was easier to delete the whole post. Thanks … -
How to get the url before render it
I would like to build a system which need to detect which urls the user opened and count the opened times. I added a dic in the urls and hope it can return the correct url the user opened to the context1 in Waitviews. But I couldn't find a correct way to obtain the correct url, (I tried to use HttpRequest.get_full_path() but it continues error. "TypeError: get_full_path() missing 1 required positional argument: 'self'") Moreover, I hope the WaitView could received the correct url and count times and then show the times on the opened page.(need the correct url before render it) So I wander if you have some suggestions on this. Really appreciate for your kind help. # urls.py ''' urlpatterns = [ re_path('get_times/.+', WaitView.as_view(), {"url": ***CORRECT_URL***}) ] ''' # views.py ''' class WaitView(TemplateView): template_name = 'wait.html' def get_context_data(self, **kwargs): context1 = kwargs.items() print(context1) ''' -
How to read tables from postgresql in django
In Django(2.2) i have created a html page with a form to collect data from the user and store in database(postgresql),now i want to retrieve the data from database in pandas dataframe format to analyse it. Any command to get the data from postgresql tables in pandas dataframe format in Django framework -
How to prevent 'no username' in django?
[This is what my register form looks like][1[]]1 I want to make it so that if the user doesn't write anything in the given text boxes, a warning sign pops up and say that ' a username must be inputted' or something like that but when i click the submit button, Value error occurs, saying that "The given username must be set" def register(request): context = { 'error_message': None, } if request.method == 'POST': username = request.POST['username'] password1 = request.POST['password1'] password2 = request.POST['password2'] email = request.POST['email'] if password1==password2: if User.objects.filter(username=username).exists() or Person.objects.filter(username=username).exists(): context['error_message'] = '이미 사용중인 아이디입니다.' return render(request, 'UserAdministration/register.html', context) elif User.objects.filter(email=email).exists() or Person.objects.filter(username=username).exists(): context['error_message'] = '이미 사용중인 이메일입니다.' return render(request, 'UserAdministration/register.html ', context) else: user = User.objects.create_user( password=password1, email=email, username=username ) user.save() masked_username = generate_masked_username.generate_masked_username(username) person = Person.objects.create( username=username, masked_username=masked_username, email=email, password=password1 ) person.save() return redirect('login') else: context['error_message'] = '비밀번호가 맞지 않습니다.' return render(request, 'UserAdministration/register.html', context) # return redirect('/') # originally was homepage.html. Doesn't know if this changed anything. just a note else: return render(request, 'UserAdministration/register.html', context) This is my code... anybody know how to prevent this error? -
How HTTP request works in Django?
I have a question about how Django function can work properly and how they accept HTTP request and how function works. @api_view(['GET', 'POST']) @permission_classes((permissions.AllowAny,)) def building_detail(request, pk): try: building = Building.objects.get(pk=pk) except Building.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = BuildingSerializer(building) return Response(serializer.data, status=status.HTTP_201_CREATED) This is one of my code in my django app. When there is request with method 'GET' to the view, there would be only one data, request data from somewhere, when they get the data, but how they can distinguish(or maybe separate) which one is 'pk' and which one is 'request'? -
Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying
Django 3.0.5 class TaggedItem(models.Model): tag = models.ForeignKey(Tag, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') def __str__(self): return self.tag.tag I didn't do save programmatically: t = TaggedItem(content_object=..., tag=...) t.save() But I have just saved TaggedItems in the admin site: Anyway, saving is done. Then I want to select all the tags related to an object. class JumpsuitsDetailView(DetailView): model = Sneakers def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context def dispatch(self, *args, **kwargs): response = super(JumpsuitsDetailView, self).dispatch(*args, **kwargs) tagged_items = TaggedItem.objects.filter(content_object=self.object) And I get this: Internal Server Error: /sneakers/1/ Traceback (most recent call last): File "/home/michael/PycharmProjects/varnish/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/michael/PycharmProjects/varnish/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/michael/PycharmProjects/varnish/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/michael/PycharmProjects/varnish/venv/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/michael/PycharmProjects/varnish/varnish/sneakers/views.py", line 16, in dispatch tagged_items = TaggedItem.objects.filter(content_object=self.object) File "/home/michael/PycharmProjects/varnish/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/michael/PycharmProjects/varnish/venv/lib/python3.6/site-packages/django/db/models/query.py", line 904, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/home/michael/PycharmProjects/varnish/venv/lib/python3.6/site-packages/django/db/models/query.py", line 923, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/home/michael/PycharmProjects/varnish/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1350, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/home/michael/PycharmProjects/varnish/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1381, in _add_q check_filterable=check_filterable, File "/home/michael/PycharmProjects/varnish/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1250, in build_filter lookups, parts, … -
importlib.import_module ignoring re-exports made in __init__.py
(Originally asked on r/learnpython, but figured I'd ask here too.) Since this problem came up while dealing with django, I'll explain in that context. So I have a django project folder, and some internal django apps living in that project folder, like this: project_module ├ apps │ ├ app_module1 │ │ ├ models.py │ │ └ ... │ ├ app_module2 │ └ ... ├ settings.py └ ... now the app_modules are available as project_module.apps.app_module1 and so on, but since there won't be anything colliding with the app names in project_module, I'd like to drop the .apps part so I can just refer to them as project_module.app_module1 and such, consistently. So, I create __init__.py everywhere, and put this into project_module/__init__.py: from .apps import app_module1 And this sort of works, since I can import project_module.app_module1 and it seems to work. BUT, Django internally uses importlib.import_module here and there, and in those cases I encounter ModuleNotFoundError: No module named 'project_module.app_module1'. In those cases I can use the .apps again, but this sort of breaks consistency. A bit of experiment later, I'm convinced import_module ignores re-exports from __init__.py; But why does this happen, and is there a way I can play around this in … -
Django count of sizes in product
I am creating a shop backend. I have product model and each product has many to many field to sizes model. But there is a problem: how to manage count of each size for product? I just want to make request every time when user puts smth in the cart and make increment to count of this size in this product. My models: class Size(models.Model): class Meta: verbose_name = "Размер" verbose_name_plural = "Размеры" size = models.CharField(max_length=255, verbose_name="Размер") def __str__(self): return self.size class Image(models.Model): class Meta: verbose_name = "Фотография" verbose_name_plural = "Фотографии" image = models.ImageField(verbose_name="Фотография", upload_to='product_images/') def __str__(self): return self.image.name class Product(models.Model): class Meta: verbose_name = "Товар" verbose_name_plural = "Товары" title = models.CharField(max_length=255, verbose_name='Название') images = models.ManyToManyField(Image, verbose_name="Фотографии") cost = models.IntegerField(verbose_name='Цена') sizes = models.ManyToManyField(Size, verbose_name='Размеры') description = models.TextField(max_length=2000, verbose_name='Описание') structure = models.CharField(max_length=50, verbose_name="Материал") sizes_image = models.ImageField(verbose_name="Сетка размеров", upload_to='product_sizes/') -
Django template displaying images in wrong position
I'm new to Django so apologies if this one is silly. I have a Django template with three spots for images, and I'm trying to let an admin user choose which image in the database should go in which spot (left, middle or right). However, My model looks like this: from django.db import models from django.urls import reverse from django.utils.text import slugify class Artwork(models.Model): art = models.ImageField(upload_to='artworks/%Y') title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) date = models.DateField(auto_now_add=True) herochoices = [('left', 'left'), ('middle', 'middle'), ('right', 'right')] hero = models.CharField(choices=herochoices, max_length=6, unique=True, null=True, blank=True, error_messages={'unique':'Another artwork already uses this hero position.'}) slug = slugify(title, allow_unicode=False) def get_absolute_urls(self): return reverse('artwork_list', kwargs={'slug': self.slug}) And my template looks like this: {% extends 'base.html' %} {% block content %} <div class="container"> <div class="row"> {% for artwork in object_list %} {% if artwork.hero == 'left' %} <div class="col-sm p-3 align-items-center"> <img class="img-fluid rounded" src="{{ artwork.art.url }}" /> <p>{{ artwork.hero }}</p> <!--for testing--> </div> {% elif artwork.hero == 'middle' %} <div class="col-sm p-3 align-items-center"> <img class="img-fluid rounded" src="{{ artwork.art.url }}" /> <p>{{ artwork.hero }}</p> <!--for testing--> </div> {% elif artwork.hero == 'right' %} <div class="col-sm p-3 align-items-center"> <img class="img-fluid rounded" src="{{ artwork.art.url }}" /> <p>{{ artwork.hero }}</p> <!--for … -
Css file not responding at django project
I am trying to change navbar color through css file at django. But cant. Here is the folders: folders of the project base.html home.html main.css -
Django, how to implement a formfactory in my models structure?
I have the following question for you. I have four models: Informazioni generali, Lavorazione, Costi_materiale and Mod. The first two give me the possibility to register "codice_commesse" and "numero_lavorazione" in this mannner: class Informazioni_Generali(models.Model): codice_commessa= models.CharField() CATEGORY_CHOICES=( ('BOZZA', 'BOZZA'), ('PREVENTIVO', 'PREVENTIVO'), ('COMMESSA', 'COMMESSA') ) status=models.CharField(choices=CATEGORY_CHOICES) nome_cliente=models.CharField() class Lavorazione(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali) numero_lavorazione=models.IntegerField() prodotto=models.ForeignKey() sottoprodotto=models.ForeignKey() note=models.CharField() Once registred these two models, client have the possibility to register Costi_materiale and Mod, related to Lavorazione (itself related to Informazioni generali). class Costi_materiale(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali, on_delete=models.CASCADE, null=True) numero_lavorazione=models.ForeignKey(Lavorazione) conto = models.ForeignKey(Conto) tipologia = models.ForeignKey(Tipologia) sottocategoria = models.ForeignKey(Sottocategoria) quantita=models.DecimalField() prezzo=models.DecimalField() class Mod(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali, on_delete=models.CASCADE, null=True) numero_lavorazione=models.ForeignKey(Lavorazione, on_delete=models.CASCADE, null=True) nome_cognome=models.CharField(') costo_orario=models.DecimalField() monte_ore=models.DecimalField() I have created the model forms for Informazioni_generali and Lavorazioni, but I have problems to implement the form for the last two models. I want to have the following structure, but I don't know how to implement it. I want to fill only one time "codice_commessa" and "numero_lavorazioni" for all models related (Costi_materiale and Mod). And I want to give the possibility to the user to add new form clicking on the "+" button. Do you have some suggestions? -
Need point values after addition in django templates
the problem is when is use add filter i get a raw result or a round off result like say 10 + 0.2 = 10 only (instead i want it to print 10.2). My models.py and templates file below models.py class Shop(models.Model): price = models.FloatField() i filled the value of price in database as 5. home.html {{ object.price }} it prints 5 (good) but when i use filter -> {{ object.price|add:0.2 }} it returns 10 (i want 10.2) on my homepage -
Python and python framework
I have learnt basic of python like list, dictionary, loop, condition.i am PHP developer.next what should be do? Which database is familiar with python? Which framework should be learn for web and which for desktop application? -
Django Custom middleware don't display tags in each page
I am trying to print a add like message using session in each page while user visit my page. And i came out with this code it display my marketing message in index.html. middleware.py--- from .models import MarketingMessage from django.utils.deprecation import MiddlewareMixin class DisplayMarketing(MiddlewareMixin): def __init__(self, get_response): self.get_response = get_response def process_request(self, request): print("something") try: request.session['marketing_message'] = MarketingMessage.objects.all()[0].message except: request.session['marketing_message'] = False my views.py-- def index(request): products = Product.objects.all() marketing_message = MarketingMessage.objects.all()[0] context = {'products':products,'marketing_message':marketing_message} return render(request,'pro/index.html',context) models.py-- from django.db import models class MarketingMessage(models.Model): message = models.CharField(max_length=120) active = models.BooleanField(default=False) featured = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now=False,auto_now_add=True) updated = models.DateTimeField(auto_now_add=False,auto_now=True) start_date = models.DateTimeField(auto_now=False,auto_now_add=False,null=True,blank=True) end_date = models.DateTimeField(auto_now_add=False,auto_now=False,null=True,blank=True) def __str__(self): return str(self.message[:12]) base.html-- {% if marketing_message %} <div class="alert alert-success alert-dismissible alert-top-message" role="alert"> <h3> {{ request.session.marketing_message|safe }} </h3> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {% endif %} -
Reverse for 'evolucion_paciente' with arguments '(5,)' not found. 1 pattern(s) tried: ['evolucion_paciente/(?P<id>[0-9]+)/(?P<id_e>[0-9]+)$']
I have created a view that accepts 3 arguments but I get the following error in the homepage.Reverse for 'evolucion_paciente' with arguments '(5,)' not found. 1 pattern(s) tried: ['evolucion_paciente/(?P[0-9]+)/(?P[0-9]+)$'] Proyect/views.py -- One of my views def VerEvoluciones(request, id): if request.method == 'GET': paciente = Paciente.objects.get(id= id) evoluciones = Evolucion.objects.filter(paciente= id).order_by('-fechaEvolucion') evolucionForm = EvolucionForm() else: return redirect('index') return render(request, 'evoluciones.html', {'evolucionForm': evolucionForm, "Evoluciones": evoluciones, "Paciente": paciente}) Another View, and the one which im having troubles with def VerEvolucion(request, id, id_e): evolucionForm= None evolucion= None try: if request.method == 'GET': paciente = Paciente.objects.get(id= id) evolucion = Evolucion.objects.filter(paciente= id).get(id= id_e) evolucionForm = EvolucionForm(instance= evolucion) else: return redirect('index') except ObjectDoesNotExist as e: error = e return render(request, 'evolucion.html', {'evolucionForm': evolucionForm, 'Evolucion': evolucion, 'Paciente': paciente, 'Ver': True}) In my template, the link that i need to redirect me from my firt view to my second one <a href="{% url 'evolucion_paciente' evolucion.id %}" class="btn btn-warning">Ver</a> -
How can I connect a python application to my Django PostgreSQL database to write data
I have seen many quite similar questions here but nothing quite like it. I would like to write a python(kivy) app with the functionality to add data to the postgreSQL database of my heroku-deployed Django web app. How would I go about approaching this? -
TEARING MY HAIR OUT trying to move databases from SQLite to Postgres
Not sure how/why, but I started out using SQLite in production; now I need to move to Postgres pronto. So I do this: python3 manage.py dumpdata --indent 4 --natural-primary --natural-foreign -e contenttypes -e auth.Permission -e sessions > dumpdata.json No problem so far. Changed my setting.py to point to new postgres db, then run: python3 manage.py migrate --run-syncdb Still no problem. Problem comes here, when I run this command: python3 manage.py loaddata dumpdata.json I get this nasty error: django.core.serializers.base.DeserializationError: Problem installing fixture 'dumpdata.json' Googled this error on Stack Overflow. Seems like it happens when the file isn't valid JSON. I run head -1000 dumpdata.json and tail -1000 dumpdata.json and everything looks good. No trailing commas, no weird strings, nothing. What gives!? -
Which data binding supported by Django? one way, two way or three way binding?
Which data binding supported by Django ? I am planning to develop a web application with django. So in term of developing UI with django which data binding django supports : one way, two way or three way binding ? -
How can i add something to the database with a submit button in Django?
I'm making a grocery list web app in django and i have a page with your groceries list and i have a page with all the products you can add to your list. every product has a button "add to list". The intention is that when you click on that button that that product automatically becomes added to the groceries list. Does someone know how to do that? thank you in advance. The Groceries List page The all products page models.py from django.db import models # Create your models here. class Brand(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class AllProducts(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class ShoppingList(models.Model): product = models.ForeignKey(AllProducts, null=True, on_delete= models.SET_NULL, blank=True) brand = models.ForeignKey(Brand, null=True, on_delete= models.SET_NULL, blank=True) quantity = models.CharField(max_length=200, null=True, blank=True) info = models.TextField(max_length=500, null=True, blank=True) def __str__(self): return self.product The class brand is a class with all the brands of the products. The class All_Products is a class with all the products that you can add to your groceries list. And the class ShoppingList is a class with all the products in the groceries list. Views.py def home(request): products = ShoppingList.objects.all() context = { 'products':products, } return render(request, 'groceries_list/home.html', … -
How to query the following use case in Django?
I have made a game similar to the drinking game piccolo where you have a list of challenges. Each challenges has variables that need to be filled in (e.g: Player X gives four sips to Player Y). Besides that, a challenge consists of rounds, with each round having an index and a description (e.g Round 0: X and Y drink 4 sips. Round 1: X and Y drink 5 sips now), with X and Y being the same names in both rounds. First we made a small console app that had the challenges hardcoded in them. The list of challenges would look like this: challenge_list = [ Challenge(["p(0)", "rand_phone_number()"],[[0, "{d[0]} moet een nummer bellen. Het volgende scherm bepaalt welk nummer"], [1, "Het nummer is {d[1]}"]]), Challenge(["p(0)", "rand(2,5)", "rand_char('a','z')", "rand(2,5)"], [[0, "{d[0]} noemt {d[1]} dieren die beginnen met de letter {d[2]} of drinkt {d[3]} slokken"]]), Challenge([], [[0, "Alle drankjes schuiven een plek naar links"]]), After requests from other friends we decided that it would be educational to migrate the project to Django, since we did not have much experience in web development and we want to learn something new. We came up with the following model to replicate the hardcoded challenges … -
Django save_model doesn't get called
I want to override the save_model(...) method of the django admin. For this I created following class and method in the admin.py file: class ArticleAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): print('IN ADMIN') super().save_model(request, obj, form, change) Now I know this doesn't do anything different but I just wanted to test if this method gets called and it doesn't (print since I got no debugger). According to the official documentation this is the accurate method. Does anybody know what I did wrong? -
how to send emails to all users?
How can I send email to all users whenever I want? I have built a blog app and I want to send some emails about news and updates to all the users and I have no idea how to do it. please help me with the code. I'm using the built in django user model for auth. thanks for the responses