Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I retrieve the Aerodrone model name and code field values correctly?
I'm working on a Django project with two models, Aerodrone and Meteo. I defined a foreign key in the Meteo model to reference the Aerodrone model. However, the foreign key fields in the database are named aerodrone_id and code_aerodrone_id. I want to retrieve the values of the name and aerodrone_code fields from the Aerodrone model in the Meteo model. I wrote the admin part but the code_aerodrone field always retrieves the values of the name field instead of code. Help me solve this problem. Here is the code: class Aerodrone(models.Model): nom = models.CharField(verbose_name="Nom de l'aérodrone", max_length = 150, unique=True) code = models.CharField(verbose_name="Code de l'aérodrone", max_length = 50, unique=True) class Meta: verbose_name_plural = "Aérodromes" def str(self): return self.nom class Meteo(models.Model): id_message = models.ForeignKey(Idmessage,verbose_name="Id du message", on_delete=models.CASCADE) aerodrone = models.ForeignKey(Aerodrone,verbose_name="Nom de l'aérodromes", on_delete=models.CASCADE, to_field="nom", related_name = "meteo_aerodrone_nom") code_aerodrone = models.ForeignKey(Aerodrone,verbose_name="Code de l’aérodromes", on_delete=models.CASCADE, to_field="code", related_name = "meteo_aerodrone_code") id_station = models.CharField(verbose_name="Code de la station", max_length = 50) date_heure = models.DateTimeField(auto_now_add=True, verbose_name="Date et heure") direction_vent = models.CharField(verbose_name="Direction et la force du vent", max_length = 150) visibilite = models.CharField(verbose_name="Visibilité horizontale", max_length = 150) temps_significat = models.CharField(verbose_name="Temps significatif", max_length = 150) nuages_significatif = models.CharField(verbose_name="Nuages significatif", max_length = 150) temperature = models.CharField(verbose_name="Température de l’air sec et du … -
django-telegram-login error username invalid
Im using the module django-telegram-login. I insert the code from documenatation into my project. def index(request): # Initially, the index page may have no get params in URL # For example, if it is a home page, a user should be redirected from the widget if not request.GET.get('hash'): return HttpResponse('Handle the missing Telegram data in the response.') try: result = verify_telegram_authentication( bot_token=bot_token, request_data=request.GET ) except TelegramDataIsOutdatedError: return HttpResponse('Authentication was received more than a day ago.') except NotTelegramDataError: return HttpResponse('The data is not related to Telegram!') # Or handle it like you want. For example, save to DB. :) return HttpResponse('Hello, ' + result['first_name'] + '!') def callback(request): telegram_login_widget = create_callback_login_widget(bot_name, size=SMALL) context = {'telegram_login_widget': telegram_login_widget} return render(request, 'accounts/telegram_auth/callback.html', context) def redirect(request): telegram_login_widget = create_redirect_login_widget( redirect_url, bot_name, size=LARGE, user_photo=DISABLE_USER_PHOTO ) context = {'telegram_login_widget': telegram_login_widget} return render(request, 'accounts/telegram_auth/redirect.html', context) if I've logged into telegram before I got the 'Invalid username' in my page and I coudn't open the page of autorazation in telegram again. If I haven't logged into telegram before I got the 'Inavlid username' in my page and I could open the page of autarazation at once. I haven't errors from the server. The bot is configured correctly. Im using … -
Django: No file was submitted. Check the encoding type on the form
I wanna make a form that allows uploading multiple images by one submit. I already set enctype in my form to "multipart/form-data", my image input contains "multiple" argument and my form initialization contains "request.POST and request.FILES" (form=self.form_class(request.POST, request.FILES) ). So normally It should be working but I'm encountering with this form error: <ul class="errorlist"><li>image<ul class="errorlist"><li>No file was submitted. Check the encoding type on the form.</li></ul></li></ul> My models.py: class Photo(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) image = models.ImageField(upload_to='photos') description = models.TextField(null=True, blank=True) def __str__(self): return self.image.name def save(self, *args, **kwargs): img = Image.open(self.image.name) img.resize(size=(300, 300)) img.save(self.image.name) return super(Photo, self).save(*args, **kwargs) My forms.py: class CustomFileInput(forms.ClearableFileInput): allow_multiple_selected = True class AddPhotoForm(forms.ModelForm): image = forms.ImageField(widget=CustomFileInput(attrs={'multiple': True}), required=True) description = forms.CharField(widget=forms.Textarea(), required=False) class Meta: model = Photo fields = ['image', 'description'] def save(self, commit=True): if commit: photo = Photo.objects.create( user=self.instance, image=self.cleaned_data['image'], description=self.cleaned_data['description'] ) photo.save() return photo My views.py: class AddPhotoView(CreateView): template_name = 'app/add-image.html' form_class = AddPhotoForm success_url = ... def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, context={'form': form}) def post(self, request, *args, **kwargs): form = self.form_class( request.POST, request.FILES, instance=request.user ) if form.is_valid(): form.save() return redirect(self.success_url) return render(request, self.template_name, context={'form': form}) My add-image.html: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="d-flex justify-content-center"> {{ … -
Quick hack to get Google Maps to look good on Mobile, works fine on Desktop for me
I have got a random google map location embedded onto a test location page. It appears fine and looks fine on Desktop. When I test on mobile. The right side of the map is going outside the container while everything else stays inside the container. Is there a way to prevent this? Is the only way to use google api / JS? Is there no sneaky quick little hack to fix this? <div class="container"> <div class="row"> <div class="col-12 col-md-6 contact-1"> <hr> <h2 class="logo-font mb-4 text-center">Contact Drum Loot</h2> <h5 class="text-muted text-center">Complete our Contact Form below!</h5> <hr> </div> <div class="col-12 col-md-6 contact-2"> <hr> <h2 class="logo-font mb-4 text-center ">Contact Information</h2> <h5 class="text-muted text-center">Open 9am-5pm all week!</h5> <hr> </div> <div class="w-100 d-none d-md-block"></div> <div class="col-12 col-md-6 contact-3"> <form method="POST" href="#" class="form mb-2" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} {{ field | as_crispy_field }} {% endfor %} <button class="btn btn-black rounded-0" type="submit">Submit <i class="fab fa-telegram-plane pl-2"></i></button> </form> </div> <div class="col-12 col-md-6 text-center contact-4"> <h5>Email: info@drumloot.com</h5> <h5>Phone: 045 948 4590</h5> <h5>Address: 105 Tilted Towers, California, USA</h5> <div id="map"> <iframe class="googlemap-responsive" src="https://www.google.com/maps/embed?pb=!1m17!1m12!1m3!1d3152.1982920890246!2d-122.28525490832737!3d37.80882413795131!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m2!1m1!2zMzfCsDQ4JzMxLjgiTiAxMjLCsDE2JzQ5LjQiVw!5e0!3m2!1sen!2sie!4v1702042781451!5m2!1sen!2sie" width="600" height="450" style="border:0;" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe> </div> </div> </div> </div> -
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x13f305e90> give this error in django and image path retrive from s3 is
When I open Image url given by django it gives this. This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>SignatureDoesNotMatch</Code> <Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message> <AWSAccessKeyId>AKIAR4APO3UQB6EPRHZK</AWSAccessKeyId> <StringToSign>AWS4-HMAC-SHA256 20231208T141342Z 20231208/eu-north-1/s3/aws4_request 7c1cadaceeabd5fd2551d7de369db9c9b1fdd0741e5077490b8b3f8599a157b4</StringToSign> <SignatureProvided>b9a5a710e118bb6fb3f7d442191a8a5be293fa8a3838465e466063c4b9214635</SignatureProvided> <StringToSignBytes>41 57 53 34 2d 48 4d 41 43 2d 53 48 41 32 35 36 0a 32 30 32 33 31 32 30 38 54 31 34 31 33 34 32 5a 0a 32 30 32 33 31 32 30 38 2f 65 75 2d 6e 6f 72 74 68 2d 31 2f 73 33 2f 61 77 73 34 5f 72 65 71 75 65 73 74 0a 37 63 31 63 61 64 61 63 65 65 61 62 64 35 66 64 32 35 35 31 64 37 64 65 33 36 39 64 62 39 63 39 62 31 66 64 64 30 37 34 31 65 35 30 37 37 34 39 30 62 38 62 33 66 38 35 39 39 61 31 35 37 62 34</StringToSignBytes> <CanonicalRequest>GET /media/images/pexels-jonas-f-13020734.jpg X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAR4APO3UQB6EPRHZK%2F20231208%2Feu-north-1%2Fs3%2Faws4_request&X-Amz-Date=20231208T141342Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host host:captiongenerator.s3.eu-north-1.amazonaws.com host UNSIGNED-PAYLOAD</CanonicalRequest> <CanonicalRequestBytes>47 45 54 … -
hosting django rest dependencies dependencies of Celery, Celery Beat, Redis, and Django Channels using Daphne
I'm currently facing challenges while deploying my Django REST project on AWS EC2. The project has dependencies on Celery, Celery Beat, Redis, and Django Channels using Daphne. If anyone has experience with this pls help me -
Can't connect Conda Psycopg in Django, only system-level python works
I have wanted to switch from using the system-level python packages (arch-linux) to mamba/conda virtual env. Note that postgresql.service is running fine system level. I have installed all the same packages in the virtual environment. It works perfect on main system python but fails in conda. I even set env-variables in zsh shell for postgresql and done chmod 0600 ~/.my_pgpass DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "OPTIONS": { "service": "my_service", // location - /home/zane/.pg_service.conf "passfile": ".my_pgpass", //location is project root "server_side_binding": True, }, } } Without conda virtual env:(works fine) python manage.py migrate Operations to perform: Apply all migrations: admin, auth, business, contenttypes, sessions Running migrations: No migrations to apply. **(All runs fine without virtual enviroment)** with conda virtual env- mamba activate django (django) Django-CRUD main ❯ python manage.py migrate Traceback (most recent call last): django.db.utils.OperationalError: connection is bad: No such file or directory Is the server running locally and accepting connections on that socket? I have also inserted zsh shell variables export PGPASSFILE="/home/zane/projects/Django-CRUD/.my_pgpass" export PGSYSCONFDIR=/home/zane/ export PGSERVICEFILE=/home/zane/.pg_service.conf Please help as none of the above worked -
while routing to "/room/id" page, it is redirecting to two room routes like "/room/room/id", when I should have one room
my home page i.e "/" is listing all the room names with links, which should redirect to that particular room with that name. For example clicking on "Test Room1" should redirect me to "/room/1" with that name. But it is redirecting me to "/room/room/1" and however giving me the room name with id 1. views.py rooms = [ {'id':1, 'name':'Test Room1'}, {'id':2, 'name':'Test Room2'}, {'id':3, 'name':'Test Room3'} ] def home(request) : context = {'rooms':rooms} return render(request, 'base/home.html', context) def room(request, pk) : room = None for i in rooms : if i['id'] == int(pk) : room = i context = {'room':room} return render(request, 'base/room.html', context) urls.py urlpatterns = [ path('', views.home, name='home'), path('room/<str:pk>/', views.room, name='room') ] html template {% for room in rooms %} <div> <h3>{{room.id}} : <a href="{% url 'room' room.id %}">{{room.name}}</a></h3> </div> {% endfor %} -
how to make an imag eand image content responsive in mobile device.now my image width is responsive ,but its height
I am doing a Django website. I am using bootstrap v5.3.2. In my home page there is the main image inside the image welcome to the company and in the next line another text and in next line 3 square shaped cards are placed horizontally .but these portion are not responsive in mobile device. The image width is responsive but the length is not ,the cards are overlaying the image text in mobile screen size, I want the 3 cards are inside the image just after the text in the image on mobile screen device. How to make that I want the 3 cards are inside the image just after the text in the image on mobile screen device. How to make that -
css/js is not working after hosting in aws ec2
settings.py is shown below: '''import os from pathlib import Path from dotenv import load_dotenv Build paths inside the project like this: BASE_DIR/ 'subdir'. BASE_DIR = Path(file).resolve().parent.parent load_dotenv() Quick-start development settings - unsuitable for production See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv("SECRET_KEY") SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['not showing'] ......... Static files (CSS, JavaScript, Images) https://docs.djangoproject.com/en/4.2/howto/static-files/ STATIC_URL = 'static/' STATIC_ROOT = [os.path.join(BASE_DIR, 'static')] Default primary key field type https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' ''' this is setting.py, I don't understand where it is going wrong. I did collectstatic,load static, and also html pages have bootstrap cdns and still CSS /bootstrap is not working. Can somebody help me, I am hosting (aws ec2) for the first time, having trouble. This is the error shown after entering "python manage.py collectstatic" or "python manage.py collectstatic --no-input" in cmd -"TypeError: expected str, bytes or os.PathLike object, not list". -
Show Name instead on Phone Number on Whatsapp
I have successfully integrated Twilio with WhatsApp using Python code, and our system is effectively sending SMS messages to WhatsApp. However, we are currently facing an issue where we want customers to see our company name instead of the WhatsApp application number when receiving messages. Despite searching through the Twilio documentation, I have not found information on how to replace the WhatsApp number with our company name. I need assistance in understanding and implementing the necessary steps to achieve this within the Twilio integration. Tried Twillio documenataion -
Is it possible to extend Django's User model just adding objects to its model form?
I am trying to create users with django's User Model but I want to add to it some extra boolean fields and choice fields. isn't there any way to do it without binding it with one to one field to another model? I tried adding objects straight to User model and when i rendered the form i could see the fields I added but when it comes to admin pannel, I can't see these fields. -
Should I list the contestants according to the selected division?
I'm new to web development and I use the Django framework! I ask you to help or guide me on the right path. It is necessary to implement a selection of contestants according to the division selected from the drop-down list. The contestant model has a secondary key to the division model, the template implements the output of two forms: class divisionForm(ModelForm): # Подразделения class Meta: model = division fields = ['name_division'] widgets = { "name_division": Select(attrs={}), } class contestantForm(ModelForm): # Конкурсанты class Meta: model = contestant fields = ['name_contestant'] widgets = { "name_contestant": Select(attrs={}), } enter image description here As far as I understand, Django acts as a server and when the page loads, it returns the data processed in views.py how to implement the withdrawal of all contestants from the selected division in the template? already on the client side without POST and GET requests. Do you have a javascript example for interacting with Django on a similar topic? -
Concatenate 2 RawQuerySets Django
so i have each entity their and they are from legacy system, thats why i cannot perform migration. For example : Entity1 Blog Entity1 Entry Entity2 Blog Entity2 Entry There are 9 entities, means 18 tables So here is my view.py but i cannot do entity1_data.union(entity2_data). How can i merge these, so i can present it in 1 table? Ps: i would try union SQL, but theres too long. entity1_data = BlogModel.objects.using("bcdb").raw("SELECT blog.id as id, blog.name," + "entry.title, " + "entry.date " + "FROM [Entity1 Blog] as blog " + "INNER JOIN [Entity1 Entry] as entry " + "on blog.id = entry.blog_id") entity2_data = BlogModel.objects.using("bcdb").raw("SELECT blog.id as id, blog.name," + "entry.title, " + "entry.date " + "FROM [Entity2 Blog] as blog " + "INNER JOIN [Entity2 Entry] as entry " + "on blog.id = entry.blog_id") I hope i can do it dynamically using dict of tables name. Merged table | Blog ID | Blog Name | Entry Title | Entry Date | | ------------------ | -------------------- | ---------------------- | --------------------- | | [Entity 1 Blog].ID | [Entity 1 Blog].name | [Entity 1 Entry].title | [Entity 1 Entry].date | | [Entity 2 Blog].ID | [Entity 2 Blog].name | [Entity 2 Entry].title … -
Question about using Group or Role in frontend application to restrict view
I am building an application that comprises a python backend using the django framework and a vue application on the frontend. I am using with success the authorization and permissions framework provided by django. I have created groups that possess a set of permissions and I have assigned users to them. Technically, after reading the docs, it is recommended to use groups to check for permissions and not roles. A problem arises when I need to serialize the user and send it to the frontend. What kind of information should I send to determine permissions on the frontend? Should I serialize all the groups the user belongs to with the respective permissions, or should I create a role field in my database to simplify things out (the roles are quite well defined) and just send that. What is the common solution or what would be reasonable? What kind of questions should be answered when approaching this problem? Thank you for your time. -
while we want to develop a travelling website using react how can we integrate a map api into our project
we need to provide a route map just like the google maps based on the user input that he/she wanted to visit the place, that should display the starting and destination locations of the user along with the type of transport that is available to visit that place. we tried to integrate the google maps API by generating a token but we are unable to integrate it in our project and we suppose that it is also not free of cost.so we need a map API and the process to integrate the API that can take the user input(location that the user wanted to visit). -
Django Project on Heroku
-----> Building on the Heroku-22 stack -----> Using buildpack: heroku/python -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed I have tried to setup a buildpack. Heroku/Python, but yet the error have refused to go. Pls how can i fix this? -
cannot call recv while another coroutine is already waiting for the next message
RuntimeError: cannot call recv while another coroutine is already waiting for the next message hello I wrote a counsumer that acts as a middleware that connects to the server socket, for example X, then receives the data and adds a series of information to the data, then sends it to the clients connected to the consumer. When the first client connects it works fine and when the second client connects it gives the following error: RuntimeError: cannot call recv while another coroutine is already waiting for the next message class ConnectionManager: connection = None connection_lock = asyncio.Lock() @classmethod async def get_connection(cls): async with cls.connection_lock: if cls.connection is None or not cls.connection.open: cls.connection = await cls.create_connection() return cls.connection @classmethod async def create_connection(cls): email = "email" password = "Password" url = "url" session = requests.Session() params = urlencode({"email": email, "password": password}) headers = { "content-type": "application/x-www-form-urlencoded", "accept": "application/json", } session.post(url + "/api/session", data=params, headers=headers) cookies = session.cookies.get_dict() token = cookies["JSESSIONID"] return await websockets.connect( "ws://url", ping_interval=None, extra_headers=(("Cookie", "JSESSIONID=" + token),), ) class WebsocketConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.message_queue = asyncio.Queue() async def connect(self): await self.accept() await self.channel_layer.group_add("group", self.channel_name) asyncio.ensure_future(self.handle_connection()) async def disconnect(self, close_code): await self.channel_layer.group_discard("group", self.channel_name) async def receive(self, text_data): pass … -
Can't add some native django cms plugins in my pages
I am getting the problem of not being able to add some native django cms plugins in my templates. i keep getting the message Please correct the error below. i tried to debug it but i am new to django and i can't see where i went wrong. Can it be a problem with django cms it self? with no errors showing in the form. the errror This is my settings.py from pathlib import Path import os import dj_database_url from django_storage_url import dsn_configured_storage_class from django.utils.translation import gettext_lazy as _ gettext = lambda s: s # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY', '<a string of random characters>') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ.get('DEBUG') == "True" ALLOWED_HOSTS = [os.environ.get('DOMAIN'),] if DEBUG: ALLOWED_HOSTS = ["*",] # Redirect to HTTPS by default, unless explicitly disabled SECURE_SSL_REDIRECT = os.environ.get('SECURE_SSL_REDIRECT') != "False" X_FRAME_OPTIONS = 'SAMEORIGIN' LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "file": { "level": "ERROR", "class": "logging.FileHandler", "filename": "/debug.log", }, "console": { "class": "logging.StreamHandler", }, }, "loggers": { "django": { "handlers": ["file", "console"], "level": … -
django-celery-worker add delay task
my django project, use celery and sent delay task, but callback delay task raise django.db.utils.InterfaceError: (0, '') my code: @celery_app.task def delayTaskTest22222222222222222(index): """ """ print(index) import time time.sleep(15) @celery_app.task def error_handler(request, exc, traceback): # print('Task {0} raised exception: {1!r}\n{2!r}'.format( # request.id, exc, traceback)) # print() from cmdb.models import MyModel aa = MyModel.objects.all().count() print(aa) @celery_app.task def delayTaskEntry(): """""" print('-' * 50) delayTaskTest22222222222222222.apply_async(args=(11111,), time_limit=5, link_error=error_handler.s()) I exec delayTaskEntry method, and celery raise Error: File "/home/my/.pyenv/versions/3.8.8/envs/abc/lib/python3.8/site-packages/pymysql/cursors.py", line 148, in execute result = self._query(query) File "/home/my/.pyenv/versions/3.8.8/envs/abc/lib/python3.8/site-packages/pymysql/cursors.py", line 310, in _query conn.query(q) File "/home/my/.pyenv/versions/3.8.8/envs/abc/lib/python3.8/site-packages/pymysql/connections.py", line 547, in query self._execute_command(COMMAND.COM_QUERY, sql) File "/home/my/.pyenv/versions/3.8.8/envs/abc/lib/python3.8/site-packages/pymysql/connections.py", line 793, in _execute_command raise err.InterfaceError(0, "") django.db.utils.InterfaceError: (0, '') I want set delay task time_limit and get all Error, what should i modify my code. Think you!!!!! -
On-Tick Callback Not Executing in Python Virtual Environment
On-Tick Callback Not Executing in Python Virtual Environment but working in local Environment what was the issue. class Command(BaseCommand): def handle(self, *args: Any, **options: Any): api_key = "" api_secret = "" session_token = "" print("Connecting to Breeze") breeze = BreezeConnect(api_key="") print("WebSocket connected successfully") breeze.generate_session(api_secret="", session_token="") breeze.ws_connect() print("WebSocket connected successfully") def on_ticks(ticks): print("Ticks: {}".format(ticks)) breeze.on_ticks = on_ticks breeze.subscribe_feeds(exchange_code="NFO", stock_code="ADAENT", product_type="options", expiry_date="28-Dec-2023", strike_price="3000", right="Call", get_exchange_quotes=True, get_market_depth=False) print("Subscribed to ADAENT options") breeze.ws_disconnect() print("Disconnected from WebSocket") I have a Django management command located in the management/commands folder. When I run this file using python3 manage.py file_name in my virtual environment, the on_ticks callback function is not getting called, and no data is printed. However, the code works fine in my local environment. The virtual environment is active during the file execution, and all required packages are installed. What could be causing the on_ticks function not to execute in the virtual environment? When i run this script in virtual environment the on_ticks callback function is called and print the on_ticks Data. -
How do I efficiently evaluate and exclude certain values from a Django queryset?
I have a model where I have 4 datetime fields (last_fed is gotten from user input, the others are generated at form creation, not added here for brevity). class EatModel(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) medicine = models.ForeignKey(MedicalInfo, on_delete=models.SET_NULL, null=True) interval = models.IntegerField(default=4) last_fed = models.DateTimeField(default=datetime.now) second_dose = models.DateTimeField(default=None, null=True) third_dose = models.DateTimeField(default=None, null=True) fourth_dose = models.DateTimeField(default=None, null=True) fifth_dose = models.DateTimeField(default=None, null=True) remarks = models.TextField(max_length=140, blank=True) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) I have a generic TemplateView display to output the results to show the various doses. class newlist(LoginRequiredMixin, TemplateView): template_name = 'trackerapp/eatmodel_newlist.html' login_url = 'eatlogin' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['list'] = EatModel.objects.filter(user=self.request.user) return context I want to improve the view so that instead of just displaying all datefields into the template, I want to evaluate if each of them is lesser than localtime() and if so, I want to exclude specifically those values from the queryset (so if we're past the datetime for second dose, it just passes to context third_dose and fourth_dose) I experimented quite a bit with filter, exclude, defer, Q but couldn't get it to still return the row (less unwanted values). One way that I thought could work was to split it into … -
Show 'is_staff' as False in Django template
I am writing a front end admin portal to allow for admins to manage users from a front end perspective. I am trying to get a 'user status' table set up so that admins can get the users current status. I am using the is_staff and is_active within the auth_users table to get the users status. I have tried several ways but for some reason I cannot get is_staff = false to work. Here is my current code. template.py Please note these are two seperate ways and examples of the goal I am trying to get <table class="table table-striped"> <thead> <tr> <th>User</th> <th>Status</th> <th>Title</th> </tr> </thead> <tbody> {% for active_users in active_users %} <tr> <td >{{active_users}}</td> <td> {% if user.is_active %} Active {% else %} Not Active {% endif %} </td> <td> {{get_status}} </td> <td> <a class="btn btn-primary" href="/manage_user/{{active_users.id}}"><i class="bi bi-person-add"></i> Manage User</a> </td> </tr> {% endfor %} </tbody> </table> For the is_active, I tried using the tags and filters. <td> {% if user.is_active %} Active {% else %} Not Active {% endif %} </td> I also tried: <td> {% if user.is_active %} Active {% elif user.is_active == False%} Not Active {% endif %} </td> I tried those two options … -
I have a problem merging navigation bar and footer html file together in my base html
I've been trying to figure out how to include the two templates in my base html and I found no success. I'm not certainly familiar with {% include %} and {% extends %} function and I believe I am not using it correctly to fix problem. With that being said, I added my navigation bar html using {% include %} on my base html along with my footer html also using with {% include %} as shown. The result is only the footer html appeared meanwhile the navigation bar html only resulted to a horizontal line beneath the search bar. {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>home</title> <link rel="stylesheet" href="/static/css/homestyle.css"> </head> <body> {% include 'webapp/templates/pages/navbar.html' %} <!-- navigation bar html --> {% include 'webapp/templates/pages/footer.html' %} <!-- footer html--> </body> </html> <!--navigation bar html --> {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>navbar</title> <link rel="stylesheet" href="/static/css/navbar.css">` ` </head> <body> <nav class="login_nav"> <p> login </p> </nav> <hr class="solid"> <nav> <img src="/static/images/user_logo.png"> <ul class="nav_links"> <li><a href="http://127.0.0.1:8000/artists/"> apple </a></li> <li><a href="http://127.0.0.1:8000/gallery/"> banana </a></li> <li><a href="http://127.0.0.1:8000/about/"> grape </a></li> </ul> </nav> <hr class="solid"> </body> </html> [`<!--footer html --> {% load static %} <!DOCTYPE html> <html lang="en"> <head> … -
How to combine selection and assignment in a single Django ORM query?
I'm trying to avoid race conditions when assigning objects from a pool to another object. meerkat_pool = Meerkat.objects.filter(customer=None) customer.meerkat = meerkat_pool.first() customer.save() Simultaneous requests result in the same meerkat being assigned to two different customers. Is there a way to run this as a single database query? F() expressions would be ideal if I could transform the QuerySet to a single value (e.g. customer.meerkat = F("first_meerkat_in_pool")).