Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Placeholder Image not Loading Correctly Using Django
I'm working on a project which displays several listings created by users. If the user who created the listing uploaded an image, it shows the image uploaded by the user, otherwise it shows a placeholder image indicating there is no image available. This is shown both on the index page which lists the available listings and in the listing itself if the user goes there. When this is done in the index page it works without problems, however, on the listing page, despite being literally the same code, it doesn't work with the placeholder image (if the creator of the listing uploaded an image it shows without problems). The urls in settings.py are: STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') And in urls.py: urlpatterns = [ path("", views.index, name="index"), ... path("listing/<int:listing_id>", views.listing, name="listing"), ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In both cases (from the index page and the listing page) if I inspect the element i'm shown: <img src="media/images/No-Image-Placeholder.png"> However, if I right click the image and choose to open it in a new window, from the index (where it works well) the address will be "http://127.0.0.1:8000/media/images/No-Image-Placeholder.png", meanwhile, from the listing (where it doesn't work) it'll be "http://127.0.0.1:8000/listing/media/images/No-Image-Placeholder.png". … -
django-cms - the pages are visible only to the administrator
The pages are visible only to the administrator. After creating the page, I can only see it if I have administrator rights. If I go to 127.0.0.1:8000 from another browser, I will only see the menu. I installed django-cms using djangocms-installer: $ python3 -m venv env $ source env/bin/activate (env) $ pip install djangocms-installer (env) $ mkdir myproject && cd myproject (env) $ djangocms -f -p . my_demo (env) $ python manage.py runserver What am I doing wrong? -
Can I use a reverse relationship in a django-autocomplete-light search filter?
The field I need to search in belongs to a reverse 'diariaviagem' to 'viagem' relationship class DiariaViagem(models.Model): viagem = models.ForeignKey(Viagem, on_delete=models.CASCADE) fonte_pagamento = models.ForeignKey(FontePagamento, null=True, blank=True, on_delete=models.CASCADE) class ViagemAdmin(admin.ModelAdmin): list_filter = (FonteFilter,) filter class FontePagamentoViagemChangeListAutocomplete(autocomplete.Select2QuerySetView): model = FontePagamento def get_queryset(self): qs = self.model.objects.all() if self.q: qs = qs.filter(Q(diariaviagem__fonte_pagamento__codigo__icontains=self.q) | Q( diariaviagem__fonte_pagamento__descricao__icontains=self.q)) return qs class FonteFilter(FilterSelect2): title = 'Fonte de pagamento' # filter's title field_name = 'diariaviagem_set__fonte_pagamento' # field name - ForeignKey to Country model autocomplete_url = 'fonte_pagamento_viagem_change_list_autocomplete' # url name of Country autocomplete view is_placeholder_title = False widget_attrs = {'data-placeholder': 'Selecione'} The code displays the following error: type object 'Viagem' has no attribute 'diariaviagem_set__fonte_pagamento' If I just pass 'diariaviagem_set' or a property it returns: 'ReverseManyToOneDescriptor' object has no attribute 'get_queryset' Can I do something like this? -
Django postgres unique constraint name generation
When adding a new unique constraint on a django model, this will automatically create a name for this constraint in postgres. Does Postgres generate this name or is it Django? Is it deterministic? for example I use this model class MyModel(Model): field1 = TextField() field2 = IntegerField() class Meta: unique_together = ("field1", "field2") I got the name of the constraint with select constraint_name from information_schema.constraint_column_usage where table_name = 'myapp_mytable' I get a name like field1_field2_d04755de_uniq -
Django 4.0 - Saving Multiple Options using ManyToManyField
I am trying to save Multiple Choices inside my database I have a rough idea of how to do this but I am looking for a complete solution I am also wanting users to select multiple options on the Register page as these values will then be saved into the ManyToManyField I want my users to be able to access blogs for multiple sections (at the moment I can only get this to work for one section only) How can I change my current code to do this? (This is only my 3rd question so any constructive criticism will be appreciated) models.py class User(AbstractBaseUser, PermissionsMixin): # A full User model with admin-compliant permissions that uses a full-length email field as the username # Email and password are required but all other fields are optional email = models.EmailField(_('email address'), max_length=254, unique=True) username = models.CharField(max_length=50, unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) section = models.CharField(max_length=30) # section = models.ManyToManyField('UserSection', related_name='sections') is_active = models.BooleanField(_('active'), default=True, help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.')) is_staff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user can log into this admin site.')) is_executive = … -
Django FileField file does not open correctly
In my django app i create a model with a fiels of type FileField for store some documents: ... device_file = models.FileField(upload_to='uploads/') ... in my settings.py i have: STATIC_URL = 'mqtt_site/static/' MEDIA_ROOT='mqtt_site/static/media/' whell, when i my django admin Add form i save data everything work good, my documents was saved in the right position, but when i click on link the path is not correct: i get 127.0.0.1:8000/uploads/Weekly_Report-2022-01-14_19-07.pdf thet is wrong, instead of the correct 127.0.0.1:8000/mqtt_site/static/media/uploads/Weekly_Report-2022-01-14_19-07.pdf Why djangodont' add the /mqtt_site/static/media path as prefix as defined in my settings.py file? So many thanks in advance Manuel -
How to render html text saved inside a field in the database using django?
Good evening! I created in my model a skeleton for sending personalized e-mails. As code below: class EmailSituacao(models.Model): referencia = models.CharField(blank=False, null=True, unique=True, max_length=255) assunto = models.CharField(blank=True, null=True, max_length=255) remetente= models.EmailField(blank=True, null=True) mensagem = RichTextField(blank=True, null=True) def __str__(self): return self.referencia+'/'+self.assunto I put the following code in the "message" field: <p><span style="color:#e74c3c">Este &eacute; um e-mail autom&aacute;tico. Por favor, n&atilde;o responda este e-mail. Para contato utilize</span></p> <hr /> <p><strong>DADOS DA INSCRI&Ccedil;&Atilde;O</strong></p> <p>Curso: {{curso}}</p> <p>Data do Curso: {{dt_hr_inicio}}&nbsp; - {{dt_hr_fim}}</p> <hr /> <p><strong>INFORMA&Ccedil;&Otilde;ES</strong></p> <p>Informamos que voc&ecirc; foi pr&eacute; inscrito para particicipar do curso descrito acima. clique aqui para acessar o Sistema de Curso.</p> That way I need to render within my view the standard text that comes from the "message" field. I'm trying to do it in the view the same way I do with an html page. Here's the view code: def emailSgc(id_inscricao): inscricao= models.Inscricao.objects.get(pk=id_inscricao) context_email={ 'curso':inscricao.Turma.Curso.Curso, 'dt_hr_inicio':inscricao.Turma.dt_hr_inicio, 'dt_hr_fim':inscricao.Turma.dt_hr_fim } if inscricao.situacao == 'P': textoBase=EmailSituacao.objects.get(referencia='sgc_pre_inscrito') template=get_template(textoBase.mensagem) mensagem = template.render(context_email) try: enviaEmail(textoBase.assunto,textoBase.remetente,inscricao.Aluno.usuario.email,mensagem) except: pass But the line mensagem = template.render(context_email) is not correct. How do I render a standard text with the context stored inside a field in the bank and send it by email replacing the variables with {{course}} -
I'm having trouble implementing configuration for a MySQL connection pool in Django
Before I had a simple connection, but this was closed due to the high volume of traffic that exists in the application, I am trying to configure it like this: from django.conf import settings from mysql.connector import Error from mysql.connector import pooling poolname="mysqlpool" poolsize=3 varHost='localhost', varUser=settings.DATABASES['default']['USER'], varPasswd=settings.DATABASES['default']['PASSWORD'], varDB=settings.DATABASES['default']['NAME'], try: connection_pool = pooling.MySQLConnectionPool( pool_name="pynative_pool", pool_size=5, pool_reset_session=True, host=varHost, database=varDB, user=varUser, password=varPasswd) print("Printing connection pool properties ") print("Connection Pool Name - ", connection_pool.pool_name) print("Connection Pool Size - ", connection_pool.pool_size) connection_object = connection_pool.get_connection() if connection_object.is_connected(): db_Info = connection_object.get_server_info() print("Connected to MySQL database using connection pool ... MySQL Server version on ", db_Info) cursor = connection_object.cursor() cursor.execute("select database();") record = cursor.fetchone() print("Your connected to - ", record) except Error as e: print("Error while connecting to MySQL using Connection pool ", e) finally: if connection_object.is_connected(): db_Info = connection_object.get_server_info() print("Connected to MySQL database using connection pool ... MySQL Server version on ", db_Info) cursor = connection_object.cursor() cursor.execute("select database();") record = cursor.fetchone() print("Your connected to - ", record) and it throws me the following error: connection_pool = pooling.MySQLConnectionPool( File "C:\Users\USUARIO\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\pooling.py", line 156, in __init__ self.set_config(**kwargs) File "C:\Users\USUARIO\AppData\Local\Programs\Python\Python39\lib\site-packages\mysql\connector\pooling.py", line 196, in set_config raise errors.PoolError( mysql.connector.errors.PoolError: Connection configuration not valid: 'tuple' object has no attribute 'strip' Does anyone know how … -
Python, Django: Trying to understand async_views (Django > 3.0)
right now I'm trying to understand how to call two models with python/django async. Therefor I found a explanation online that seems to work but stills throws an error in command. models.py class Movies(models.Model): name = models.CharField(max_length=50, null=False, blank=False, unique=True) class Series(models.Model): name = models.CharField(max_length=50, null=False, blank=False, unique=True) functions.py from .models import Movies, Series import asyncio from asgiref.sync import sync_to_async @sync_to_async def get_movies_async(): asyncio.sleep(2) qs = Movies.objects.all() print(qs) @sync_to_async def get_series_async(): asyncio.sleep(5) qs = Series.objects.all() print(qs) views.py from django.http import HttpResponse import asyncio, time from .functions import get_movies_async, get_series_async async def index(request): start_time = time.perf_counter() await asyncio.gather(get_movies_async(), get_series_async()) print(f"Estimated time: {time.perf_counter() - start_time}") return HttpResponse("Index view") According to the explanation I should receive the data in about 5 seconds, but instead the data loads in way under a second (0.009...something) and I'm getting two RuntimeWarnings: RuntimeWarning: coroutine 'sleep' was never awaited RuntimeWarning: Enable tracemalloc to get the object allocation traceback According to the explanation this shouldn't happen and unfortunately I couldn't find a proper solution online. Can someone tell me what I am missing here? -
IntegrityError when trying to create a one to many relationship in Python Django
I am a beginner developer, working on an app that displays some walks, and each walk should have an option for users to post reviews. I am trying to create a relationship between Walk and Review models. Each Walk should have multiple Reviews, but each Review should only belong to one Walk. I'm trying to create a one-to-many relationship, but keep getting IntegrityError like so: django.db.utils.IntegrityError: The row in table 'walks_walk' with primary key '1' has an invalid foreign key: walks_walk.reviews_id contains a value '2' that does not have a corresponding value in reviews_review.id. Here are my models: Walk from django.db import models from reviews.models import Review class Walk(models.Model): # walk ID automatically generated walk_name = models.CharField(max_length=100) walk_reviews = models.ForeignKey(Review, on_delete=models.CASCADE, default="No reviews yet") Review from datetime import date from operator import mod from statistics import mode from tkinter import CASCADE from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator from django.contrib.auth.models import User # change to updated bespoke User model vs built-in class Review(models.Model): # Review ID auto-created author = models.ForeignKey(User, on_delete=models.CASCADE, default="") title = models.CharField(max_length=100) body = models.TextField(max_length=3000) I have tried several variations and cleared out my test database data, but the issue persists. What can be the … -
How to use queryset with distinct to avoid duplication value in label_from_instance?
I want to use queryset with distinct() to avoid duplication value in label_from_instance. But then I have an error like below. 'str' object has no attribute 'name' How could I use queryset with distinct() in label_from_instance? Here are the code in forms.py: from django.forms import ModelChoiceField class NameChoiceField(ModelChoiceField): def label_from_instance(self, obj): return f'{obj.name}' class MS_KansokujoForm(forms.ModelForm): code = NameChoiceField(queryset=MyModel.objects.all().values_list('name',flat=True).order_by('name').distinct()) python 3.8 Django 3.2 Mysql 5.7 -
CloudCube and Boto3 - list content of the Objects
I am encountering you with the request for help with listing the objects in my CloudCube bucket. I am developing Django application hosted on Heroku. I am using the CloudCube add-on for persistent storage. CloudCube is running on AWS S3 Bucket and CloudCube provides private Key/Namespace in order to access my files. I use the boto3 library to access the bucket and everything works fine when I want to upload/download the file; however, I am struggling with the attempts to list objects in that particular bucket with the CloudCube prefix key. On any request I receive AccessDennied Exception. To access the bucket I use the following implementation: s3_client = boto3.client('s3', aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, endpoint_url=settings.AWS_S3_ENDPOINT_URL, region_name='eu-west-1') s3_result = s3_client.list_objects(Bucket=settings.AWS_STORAGE_BUCKET_NAME, Prefix=settings.CLOUD_CUBE_KEY) if 'Contents' not in s3_result: return [] file_list = [] for key in s3_result['Contents']: if f"{username}/{mode.value}" in key['Key']: file_list.append(key['Key']) Does anyone have clue what do I miss? Thank you in advance! -
Messed up trying to install backports, ending killing dnf and yum
so everything is in the title, im working on fedora30 os, on a django project, and for no reason i couldnt start another one with django-admin startproject. 1 - i got a message telling me backports need to be installed, 2- i did the command to instal it, got a error telling me its not possible for whatever reason. 3 (where the fun begins) - got tired of it, proceded to do a rm-rf on python2.7 and 3.4 folder in order to keep only python 3.9 4 - reinstalling python 5 - dnf and yum missing, and now im starting to think i really messed up all of this i dont mind if someone can help me fixing this problem what i got in the command prompt right after using any dnf or yum command : Traceback (most recent call last): File "/usr/bin/yum-config-manager", line 75, in <module> from dnf.cli import main ModuleNotFoundError: No module named 'dnf' -
how to use a models and create a form to save in the data_base
so, i created this models, like person and the text, i want to create a form in html and call these models and save then in the data base. Note: every text must have the person ID, the person ID is like the author, you know? from django.db import models from django.utils import timezone #onde é trabalhado a parte de dados # Create your models here. from django.utils import timezone # class Text(models.Model): title = models.CharField(max_length=255) description = models.TextField() datesss = models.DateTimeField(default=timezone.now) Person = models.ForeignKey(Person, on_delete=models.DO_NOTHING) def __str__(self): return self.description class Person(models.Model): name = models.CharField(max_length=255)# charfiel é STR surname = models.CharField(max_lenght=255) user = models.CharField(max_lenght=255) #telefone = models.CharField(max_length=255, blank=True)#blank se torna opcional email = models.CharField(max_length=255) password = models.CharField(max_length=255) #description = models.TextField(blank=True) photo = models.ImageField(blank=True, upload_to='pictures/%Y/%m/%d') #criar pasta pelo dia mês ano def __str__(self): return self.name -
how to find a way for a continuous cycle? using django?
new price is the price taken from the marketcapapi. I would like that every time the user buys coins, the coins are transferred to the ALGO_wallet leaving n_ALGO_coin at zero (= 0). The first time the user buys, everything is ok, the transfer is done, while the second time the data remains both in n_ALGO_coin and also in ALGO_wallet. I tried with a for loop but it tells me that the object is no interable def buyalgomkt(request): new_price = algoValue() if request.method == "POST": form = PurchaseForm(request.POST) if form.is_valid(): form.save(commit=False) profile = Profile.objects.get(user=request.user) if profile.USD_wallet > 0 and form.instance.max_spend_usd < profile.USD_wallet: form.instance.purchased_coin = form.instance.max_spend_usd / form.instance.price_mkt profile.n_ALGO_coin += form.instance.purchased_coin profile.USD_wallet -= form.instance.max_spend_usd profile.ALGO_Wallet += profile.n_ALGO_coin profile.n_ALGO_coin = profile.ALGO_Wallet - profile.n_ALGO_coin form.save() profile.save() name = request.user name.save() messages.success(request, 'Your order has been placed and processed') else: messages.warning(request, 'You do not have enough money') return redirect('purchase') else: return HttpResponseBadRequest() else: form = PurchaseForm() return render(request, 'coinmarketalgo/purchase.html', {'form': form, 'new_price': new_price}) .. how can I do? class Profile(models.Model): _id = ObjectIdField() user = models.ForeignKey(User, on_delete=models.CASCADE) ips = models.Field(default=[]) subprofiles = models.Field(default={}) n = random.randint(1, 10) n_ALGO_coin = models.FloatField(default=algoValue() * n) ALGO_Wallet = models.FloatField(default=0) purchased_coin = models.FloatField(default=0) USD_wallet = models.FloatField(default=10000) profit = models.FloatField(default=0) class … -
Attribute Error 'list' object has no attribute 'get' in Django
I'm facing a issue while getting the data from the 'POST' method I'm getting an error as Attribute Error at api/Data/SaveUserResponse/ 'list' object has no attribute 'get' Django . The response which I get in the payload [{"AuditorId":10,"Agents":"sa","Supervisor":"sa","TicketId":"58742","QId":150,"Answer":"Yes","TypeSelected":"CMT Mails","Comments":"na","TicketType":"Regularticket","Action":"na","AuditSubFunction":"na","AuditRegion":"na"},{"AuditorId":10,"Agents":"sa","Supervisor":"sa","TicketId":"58742","QId":151,"Answer":"Yes","TypeSelected":"CMT Mails","Comments":"na","TicketType":"Regularticket","Action":"na","AuditSubFunction":"na","AuditRegion":"na"}] Views.py: @api_view(['POST',]) def SaveUserResponse(request): if request.method == 'POST': auditorid = request.data.get('AuditorId') print('auditorid---', auditorid) ticketid = request.data.get('TicketId') qid = request.data.get('QId') answer = request.data.get('Answer') sid = '0' TicketType = request.data.get('TicketType') TypeSelected = request.data.get('TypeSelected') agents = request.data.get('Agents') supervisor = request.data.get('Supervisor') Comments = request.data.get('Comments') action = request.data.get('Action') subfunction = request.data.get('AuditSubFunction') region = request.data.get('AuditRegion') print('Region---', region) cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_SaveAuditResponse] @auditorid=%s,@ticketid=%s,@qid=%s,@answer=%s,@sid=%s,@TicketType=%s,@TypeSelected=%s,@agents=%s, @supervisor =%s, @Comments=%s, @action=%s, @subfunction=%s, @region=%s', (auditorid,ticketid,qid,answer, sid,TicketType, TypeSelected, agents, supervisor, Comments, action, subfunction,region)) return Response(True) urls.py: path('Data/SaveUserResponse/', SaveUserResponse, name='SaveUserResponse'), -
Apply django migration if constraint doesn't exist yet
I want to add a constraint to my django model. I want this migration to do nothing if the constraint has already been added (manually in sql, not by django). I know how to check if constraint is already applied thanks to this question. However, how could I skip the "add constraint" operation in my migration file based on this condition? Do I need to create a RunPython operation or can I rely on django migration objects? I am using postgres. -
how to apply constraints on Django field within the instances associated with the user
I am a django beginner and making a todo app for practice, the functionality I want to achieve is that, when a user create a task,Only the time field should be unique about all of his tasks, I have done (unique=True) In the time field in model but that make it unique all over the database, but I want it to be unique only with the tasks associated with the user. the view is below: @login_required(login_url='login') def home(request): tasks = Task.objects.filter(name__username=request.user.username) form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.name = request.user obj.save() return redirect('home') else: print(request.POST) print(request.user.username) messages.warning(request, 'Invalid Data!') return redirect('home') context = {'tasks' : tasks} return render(request, 'task/home.html', context) task model: class Task(models.Model): choices = ( ('Completed', 'Completed'), ('In Complete', 'In Complete'), ) name = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) task = models.CharField(max_length=200, null=False, blank=False) time = models.TimeField(auto_now_add=False, blank=True) status = models.CharField(max_length=200, choices=choices, null=True, blank=False) def __str__(self): return self.task def get_task_author_profile(self): return reverse('profile') as you can see, I want to show the task that the logged in user has added. the form is: class TaskForm(ModelForm): class Meta: model = Task fields = '__all__' exclude = ['name'] the functionality I talked about … -
Bootstrap CDN overrides custom CSS in Django
I have tried everything mentioned on the internet but yet bootstrap CDN overrides the custom CSS file. The HTML file: {%extends 'movies/base.html'%} {%block content%} {% load static %} <!DOCTYPE HTML> <html lang="en" dir="ltr"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700;800&display=swap" rel="stylesheet"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> <body> <div class="section"> <h1>Recommend Me:</h1> <form action="recommendation" method="post"> {% csrf_token %} <input type="text" name="emotion" /> <button type="submit" name="button">Find</button> </form> <div class="video-container"> <div class="color-overlay"></div> <video autoplay loop muted > <source src="{% static 'movies/intro.mp4' %}" type="video/mp4"> </video> </div> </div> <div class="shows"> <h2 class="mt-5">Shows you might like:</h2> <br> <div class="row"> {%for tvshow in tvshows%} <div class="col-lg-5 col-md-6"> <a href="{{ tvshow.url }}"> <img src="{{ tvshow.image.url }}" class="img-fluid mb-2"> </a> <h3>{{ tvshow.title }}</h3> </div> {% endfor %} </div> </div> </body> </html> {%endblock%} I tried adding the attribute !important in CSS but yet it didn't work. CSS file: *{ box-sizing: border-box; margin: 0; padding: 0; font-family: 'Poppins'; } .video-container video{ position: absolute; top: 0; left: 0; width: 100%; height: 570px; object-fit: cover; z-index: 1; opacity: 0.8; } .section h1{ position: relative; text-align: center; font-size: 4rem; padding: 20px; margin: 15px; top: 100px; z-index: 2; opacity: 0.6; } .section form{ position: relative; … -
Django admin count numbers of rows before adding a new data in StackedInline mode
In my django project i have a model related to a main model like this one: class Device_Docs(models.Model): id = models.AutoField(primary_key=True) master_id = models.ForeignKey(Device, on_delete=models.CASCADE) device_file = models.FileField(upload_to='uploads/', validators=[FileExtensionValidator(['pdf', 'jpg', 'txt', 'png', 'jpeg']), validate_fsize], verbose_name="Select File", help_text='Allowed formats are PDF, JPG, JPEG, TXT, PNG, max size 3Mb') title = models.CharField(max_length=250, help_text='Document title') description = models.TextField(default='', verbose_name="Descrizione", null=True, blank=True) load_data = models.DateField(default=datetime.now(roma).strftime("%Y-%m-%d %H:%M:%S.%f"), verbose_name="Load data") owner = models.ForeignKey('accounts.CustomUser', related_name='odevdocs', on_delete=models.CASCADE) ... Now i would to show in my admin, for the Device model (main model) using StackedInline option both models data: class DocsInline(admin.StackedInline): model = Device_Docs extra = 1 @admin.register(Device) class DeviceModelAdmin(admin.ModelAdmin): list_display = ('mac_id', 'short_name', 'proj_type', 'polling_interval', 'active', 'autoupdate', 'save_date') list_filter = ('polling_interval','proj_type', 'active', 'autoupdate') search_fields = ('short_name', 'save_date' ) ordering = ('-save_date', 'mac_id') readonly_fields = ('mac_id', ) inlines = [PortinInline, DocsInline] def has_delete_permission(self, request, obj=None): return False def get_form(self, request, obj=None, **kwargs): self.exclude = ("owner", "save_date") form = super(DeviceModelAdmin, self).get_form(request, obj, **kwargs) return form Ok all works good, now my question is, how can i control the numbers ofrows already entered about Device_Docs data before save? For exmple i would block the possibility about insert data if in model there are more then 5 records with the same master_id … -
Django run a command once the server starts [duplicate]
I have a setup function which can only be run once the app has started and is answering requests, but which I would like to run only once when the server starts. Is there a hook or other way to run a setup function after Django has completed the "peforming system checks..." and gotten to the point where it has emitted "Quit the server with CONTROL-C."? -
Django model tab-complete in ipython
I wish to use ipython to create a custom command-line interface to query Django model objects. So for example I'd like to type: my_models.MyModelClass.h <TAB> And have all of the elements of the MyModelClass table that start with "h" be used as the tab complete. I could achieve this by creating a startup script and creating an object heirachy which matches the table structure, however that will be slow, and I'd prefer to only create the request on demand. Is there a more direct way to use ipython's tab complete, for example a function which is called to get the tab complete list when tab is invoked? -
docker-compose can't find django-admin in $PATH, but I can run django-admin commands separately
I'm trying to test a django app in a docker image. I have followed the tutorial until the it starts the django project. When I run, docker-compose run web django-admin startproject composeexample . I get Error response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "django-admin": executable file not found in $PATH: unknown ERROR: 1 It's weird because I can run django-admin createproject ... seperately. Any thoughts? I have added the ..\python39\scripts in the path. Also I have python 3.9.10 from the windows store. -
Django-CMS slug in if statement in HTML
I am trying to write an if statement to change what the link links to, based on the slug URL. I get an error in the if_statement. Shouldn't this work? <div> {% if page_attribute "slug" == 'hjem' or page_attribute "slug" == 'home' %} <a href="/no/">NO</a> / <a href="/en/">EN</a> {% else %} <a href="/no/{% page_attribute 'slug' %}">NO</a> / <a href="/en/{% page_attribute 'slug' %}">EN</a> {% endif %} </div> -
Django admin login wont respect custom next param
I want to redirect to a custom page (next='reports/fooreport') after Django admin login. I have a page in Django to be accessed by authenticated users. If I hit the URL let's say /reports/fooreport and I am redirecting the user to admin login with next='/reports/fooreport' using HttpResponseRedirect('%s?next=%s' % (reverse('admin:index'), '/reports/fooreport')) After successful login, Django is not redirecting to the next URL. However, it works pretty well for its internal apps like if I hit any admin page without login it appends in URL with next param and post login it redirects to this URL. Is there anything we can do to make it work?