Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i add am option box into my Folium Draw Toolbar?
I'm working on a proyect where i use Folium and plugin.drawn in order to handle markers and polygons, The idea it is simple, save all markers en polygons created on the map. It is a collaborative map On the map I have three layers (layer 1: Ubicacion de mujeres, layer 2: Zona de Violencia and layer 3: Poblaciones diversas). What i need is to add markers for any layer the user choose so i would like to add an option box with those layers as options as you can see in the image my options example here it is my map too current map At the moment i'm making a deep research about it. I tried to add macros like this {% macro script(this, kwargs) %} but i don't get to know how to do it correctly Any idea that you recommend me is going to be so helpful Thank you guys PD: I'm new in this -
Flexible Django Filter (django-filter package)
I'm currently implementing some filters and I'm facing multiple problems. First of all my checkboxes don't work, as in I can't select them: this is my .html code: <form method="get"> <div class="toggle-list product-categories"> <h6 class="title">Sorteer</h6> <div class="shop-submenu"> <ul> {{ filter.form.order_by }} </ul> </div> </div> <div class="toggle-list product-categories"> <h6 class="title">Merk(en)</h6> <div class="shop-submenu"> <ul> {% for f in filter.form.brand %} <li> <input type="checkbox"> <label>{{ f }}</label> </li> {% endfor %} </ul> </div> </div> <input type="submit" value="Filter"> </form> my filter in filters.py: class SortFilter(django_filters.FilterSet): ORDER_BY_CHOICES = ( ('-discount_sort', 'Hoogste korting'), ('-new_price', 'Hoogste prijs'), ('new_price', 'Laagste prijs'), ) order_by = django_filters.ChoiceFilter(label='Sorteer op', choices=ORDER_BY_CHOICES, method='filter_by_order', empty_label=None) brand = django_filters.ModelMultipleChoiceFilter(queryset=Product.objects .order_by('brand') .filter(categorie='eiwitten') .values_list('brand', flat=True).distinct() , widget=forms.CheckboxSelectMultiple, required=False) class Meta: model = Product fields = ['brand'] def filter_by_order(self, queryset, name, value): return queryset.order_by(value) view function for this certain page: def eiwit(request): # filter alleen eiwitproducten eiwit_list = ['eiwitten'] eiwit_filter = Q() for item in eiwit_list: eiwit_filter = eiwit_filter | Q(categorie=item) products = models.Product.objects.filter(eiwit_filter) product_amount = len(products) # sorteer filter filtered = SortFilter( request.GET, queryset=products ) # paginator paginator = Paginator(filtered.qs, 12) page = request.GET.get('page') try: response = paginator.page(page) except PageNotAnInteger: response = paginator.page(1) except EmptyPage: response = paginator.page(paginator.num_pages) product_front_end = { 'final_products': response, 'filter': filtered, 'count': product_amount, … -
Return all values to Map To Model Serializer
I have the following JSON jsonData = {'CompanyId': '320193', 'CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents': [{'decimals': '-6', 'unitRef': 'usd', 'period': {'instant': '2020-09-26'}, 'value': '39789000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'instant': '2019-09-28'}, 'value': '50224000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'instant': '2018-09-29'}, 'value': '25913000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'instant': '2021-09-25'}, 'value': '35929000000'}], 'NetIncomeLoss': [{'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2020-09-27', 'endDate': '2021-09-25'}, 'value': '94680000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2019-09-29', 'endDate': '2020-09-26'}, 'value': '57411000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2018-09-30', 'endDate': '2019-09-28'}, 'value': '55256000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2020-09-27', 'endDate': '2021-09-25'}, 'segment': {'dimension': 'us-gaap:StatementEquityComponentsAxis', 'value': 'us-gaap:RetainedEarningsMember'}, 'value': '94680000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2019-09-29', 'endDate': '2020-09-26'}, 'segment': {'dimension': 'us-gaap:StatementEquityComponentsAxis', 'value': 'us-gaap:RetainedEarningsMember'}, 'value': '57411000000'}, {'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2018-09-30', 'endDate': '2019-09-28'}, 'segment': {'dimension': 'us-gaap:StatementEquityComponentsAxis', 'value': 'us-gaap:RetainedEarningsMember'}, 'value': '55256000000'}]} Model: class CashFlow(models.Model): Id = models.AutoField(primary_key=True) Decimal = models.TextField(null=True) UnitRef = models.TextField(null=True) Period = models.TextField(null=True) Value = models.TextField(null=True) CompanyId = models.TextField(null=True) CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents = models.TextField( null=True) NetIncomeLoss = models.TextField(null=True) Serializer: class CashFlowSerializer(serializers.ModelSerializer): CompanyId = serializers.CharField() PeriodInstant = serializers.CharField() PeriodStartDate = serializers.CharField() PeriodEndDate = serializers.CharField() Decimal = serializers.CharField() UnitRef = serializers.CharField() Value = serializers.CharField() CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents = serializers.CharField() NetIncomeLoss = serializers.CharField() class Meta: model = CashFlowTable fields = "__all__" def create(self, validated_data): print(**validated_data) CashFlowTable.objects.create(**validated_data) View: … -
Uploading images with TinyMCE
I'm trying to install TinyMCE to my django project for blog posts, I have the initial content block working but It isn't allowing me to upload images with the following errors: Forbidden (CSRF token missing.): /admin/mhpapp/testmodel/add/static/images/images I have the app added in my settings.py Settings.py: urlpatterns = [ path('tinymce/', include('tinymce.urls')), TINYMCE_DEFAULT_CONFIG = { "height": "320px", "width": "960px", "menubar": "file edit view insert format tools table help", "plugins": "advlist autolink lists link image charmap print preview anchor searchreplace visualblocks code " "fullscreen insertdatetime media table paste code help wordcount spellchecker", "toolbar": "undo redo | bold italic underline strikethrough | fontselect fontsizeselect formatselect | alignleft " "aligncenter alignright alignjustify | outdent indent | numlist bullist checklist | forecolor " "backcolor casechange permanentpen formatpainter removeformat | pagebreak | charmap emoticons | " "fullscreen preview save print | insertfile image media pageembed template link anchor codesample | " "a11ycheck ltr rtl | showcomments addcomment code", "custom_undo_redo_levels": 10, "images_upload_url": 'static/images/images', "images_upload_handler": "tinymce_image_upload_handler" } TINYMCE_EXTRA_MEDIA = { 'css': { 'all': [ ], }, 'js': [ "https://cdn.jsdelivr.net/npm/js-cookie@3.0.1/dist/js.cookie.min.js", "admin/js/tinymce-upload.js", ], } Any help would be greatly appreciated. -
Django, sqlite to mysql migration, json decoder issue with migrated pages
I have an early and simple django project, to get things started we were using a sqlite database during setup. Someone else created some django pages with various plugins, but since these are actual pages and not templates, they are stored in the database. We realized that we should've migrated to mysql before making these pages and now we have 2 options. 1, we migrate and he builds the pages again which is time consuming, or 2, we find a way to migrate the sqlite database contents to mysql. I've been trying to figure out the second option, migrating our sqlite db to mysql. I've scoured google and nothing has been as simple as I would like, but I've been able to create as sql dump file, follow some steps to alter the format of said file, and dump said file into the new mysql database. However, while the data is there and I can access the admin and new pages, the migrated pages all run into an error when I try to view the pages or copy & paste them in the django admin. And for clarity, I created an almost blank page before the migration (tried this a … -
how to make auto logout using ajax and django
I would like to write js function for auto logout using ajax and django. Actually i did and succeded. it works fine. but i do not know is it a proper way to do it. i post my code and i need your reviews and revised or improved code or proper way to implement the auto logout funtion. Here my code. views.py def user_logout(request): logout(request) is_ajax = request.headers.get("X-Requested-With") == "XMLHttpRequest" if is_ajax: print("auto logout works") return JsonResponse({"redirect_link":"/login"},status=200) else: print("manuel logout works") return redirect("/login") ajax <script language="javascript"> jQuery(document).ready(function(){ function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== "") { const cookies = document.cookie.split(";"); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + "=")) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } setInterval(function(){ jQuery.ajax({ url: "{% url 'user-logout' %}", headers: {"X-Requested-With": "XMLHttpRequest","X-CSRFToken": getCookie("csrftoken"),}, type: 'GET', dataType: 'json', success:function(response){ window.location.href="{% url 'user-login' %}" alert("You are logged out"); } }); }, 5000); }); </script> -
How to access child model from a parent model using Django ORM?
Here are my models: class Collection(models.Model): title = models.CharField(max_length=255) featured_product = models.ForeignKey( 'Product', on_delete=models.SET_NULL, null=True, related_name='+') class Product(models.Model): description = models.TextField() unit_price = models.DecimalField(max_digits=6, decimal_places=2) inventory = models.IntegerField() collection = models.ForeignKey(Collection, on_delete=models.PROTECT) I have two models here, one of which is the parent (Collection), and the other is the child (Product). So if I need to filter the queryset based on the title attribute of the Collection class, I can type a queryset like this. query_set = Product.objects.filter(collection__title = 'beauty') Notice: Here I am accessing the parent using the child; the question is, how can I do the opposite? I tried this line of code but i got an error saying:Cannot resolve keyword 'product_set' into field. query_set = Collection.objects.filter(product_set__inventory__lt=10) -
Django Model Choice Field select not working
I have the following form: forms.py class TipoDePagoForm(forms.Form): tipo_de_pago = forms.ChoiceField(widget=forms.RadioSelect, choices=FORMAS_PAGO, required=True) folio = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Folio', 'aria-describedby': 'basic-addon2' }), required= False) medio_venta = forms.ModelChoiceField(queryset= MediosVenta.objects.all()) the ModelChoiceField in HTML is represented like this: <div class="d-block my-3"> <select name="{{ tipodepagoform.medio_venta.nombre }}" id="{{ tipodepagoform.medio_venta.id_for_label }}"> {% for value, name in tipodepagoform.fields.medio_venta.choices %} <option value="{{ value }}" {% if value == tipodepagoform.medio_venta.value %} selected {% endif %}>{{ name }}</option> {% endfor %} </select> </div> when doing the POST in the view (part of the view): def post(self, *args, **kwargs): today = date.today() tipodepagoform = TipoDePagoForm(self.request.POST or None) if tipodepagoform.is_valid(): tipo_de_pago = tipodepagoform.cleaned_data.get('tipo_de_pago') folio = tipodepagoform.cleaned_data.get('folio') medio_venta = tipodepagoform.cleaned_data.get('medio_venta') print(medio_venta) the form_is is not valid and is giving me the following error: <ul class="errorlist"><li>medio_venta<ul class="errorlist"><li>This field is required.</li></ul></li></ul> printing the form I see that is selecting the None value: <tr><th><label for="id_medio_venta">Medio venta:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><select name="medio_venta" required id="id_medio_venta"> <option value="" selected>---------</option> <option value="1">Gimnasio</option> <option value="2">Marketplace</option> <option value="3">Membresías</option> </select></td></tr> I don´t know why even if I select any option with a value it does not actually select. -
Webhooks from Azure to Django. Validation problems
I am super stuck trying to validate (I think) the Azure end of my webhook. I have an Event Grid System Topic that is successfully updating (POST) to a dummy webhook site. The problem is when I try to use this webhook in a view I receive this error in Azure. If anyone has any ideas of what I am doing wrong it would be great because I have gone through 50+ stack overflow questions trying to figure it out. -
So I'm learning to create a confirmation email address while registering an account using Django
This is urls.py `from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.home, name="home"), path('signup', views.signup, name="signup"), path('activate/<uidb64>/<token>', views.activate, name="activate"), path('signin', views.signin, name="signin"), path('signout', views.signout, name="signout"), ]` This is views.py myuser = User.objects.create_user(username, email, pass1) myuser.first_name = fname myuser.last_name = lname myuser.is_active = False myuser.save() messages.success(request, "Hey, Your Account has been successfully created. We have sent you a confirmation email. Please confirm your email in order to activate your account.") #welcome email subject = "Welcome to Django Login Project!!" message = "Hello" + myuser.first_name + " !! \n" + "Welcome to Django Login Project!! \n Thank You for visiting our website \n We have sent you a confirmation email, Please confirm your email address in order to activate your account. \n\n Thanking You\n Shalini Singh" from_email = settings.EMAIL_HOST_USER to_list = [myuser.email] send_mail(subject, message, from_email, to_list, fail_silently= True ) #email address confirmation current_site = get_current_site(request) email_subject = "Confirm your email @ Login Django Project!!" message2 = render_to_string('email_confirmation.html',{ 'name' : myuser.first_name, 'domain' : current_site.domain, 'uid' : urlsafe_base64_encode(force_bytes(myuser.pk)), 'token' : generate_token.make_token(myuser) }) email = EmailMessage( email_subject, message2, settings.EMAIL_HOST_USER, [myuser.email], ) email.fail_silently = True email.send() return redirect('signin') return render(request, "authentication/signup.html") def activate(request, uidb64, token): try: uid … -
How to execute a value from coroutine object in sync celery task?
I have 2 functions - async, which returns the coroutine object with int value, and the sync function, whic is the @shared_task, where the variable must stores the value from the async function (int) My async function, that returns the coroutine with int in it: async def club_count(club_id): return get_number_of_club(club_id).get_clients_in_club_count(club_id) There is my sync function that shared_task with making a record into the Django admin Problem with the variable "club_load" that must stores the value from my async function But when I try to run the celery, I get the error of operation between coroutine and int in "procent_club_load" @shared_task def get_club_load(): all_clubs = Club.objects.all() for club in all_clubs: if club.monitoring_club_load == True: club_load = club_load_json(club.id) club_capacity = club.club_load procent_club_load = None if club_capacity: procent_club_load = int((club_load / club_capacity)*100) club_load_record = ClubLoadModel( club_id = club.id, created_at = timezone.now(), weekday = timezone.localtime().weekday() + 1, club_load = club_load, procent_club_load = procent_club_load ) club_load_record.save() else: pass What the solution that I can execute the value from coroutine object into the variable of sync function that a shared task? I'm trying to store a value from my async function in the variable of sync celery task Problem is that celery couldn't make operations with … -
FastAPI + pytest unable to clean Django ORM
I'm creating a FastAPI project that integrates with the Django ORM. When running pytest though, the PostgreSQL database is not rolling back the transactions. Switching to SQLite, the SQLite database is not clearing the transactions, but it is tearing down the db (probably because SQLite uses in-memory db). I believe pytest-django is not calling the rollback method to clear the database. In my pytest.ini, I have the --reuse-db flag on. Here's the repo: https://github.com/Andrew-Chen-Wang/fastapi-django-orm which includes pytest-django and pytest-asyncio Assuming you have PostgreSQL: Steps to reproduce: sh bin/create_db.sh which creates a new database called testorm pip install -r requirements/local.txt pytest tests/ The test is calling a view that creates a new record in the database tables and tests whether there is an increment in the number of rows in the table: # In app/core/api/a_view.py @router.get("/hello") async def hello(): await User.objects.acreate(name="random") return {"message": f"Hello World, count: {await User.objects.acount()}"} # In tests/conftest.py import pytest from httpx import AsyncClient from app.main import fast @pytest.fixture() def client() -> AsyncClient: return AsyncClient(app=fast, base_url="http://test") # In tests/test_default.py async def test_get_hello_view(client): """Tests whether the view can use a Django model""" old_count = await User.objects.acount() assert old_count == 0 async with client as ac: response = await ac.get("/hello") … -
how to access 2 models attributes through foreignkey in django
Django learner here, I am trying to build a simple blog website in which i have created two models: one is Post: class Post(models.Model): title = models.CharField(max_length=255) author= models.ForeignKey(User, null=True, blank=True , on_delete=models.CASCADE) article = models.TextField() created_on = models.DateTimeField(auto_now_add=True) slug = AutoSlugField(populate_from='title', unique=True, null=True, default=None) category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE ) def __str__(self): return self.title second is category: class Category(models.Model): categories = models.CharField(max_length=24, blank=True) def __str__(self): return self.categories all i am trying to do is to show Category on home page, and when someone click on any category it will open up all the post related to that category. This is home.html : {% extends 'blog_pages/base.html' %} {% block content %} <div class = "container p-3"> <h3> This is your home page</h3> </div> <div class = "container p-1"> <table class="table table-hover table-bordered"> <thead> <tr> <th scope="col">Categories</th> <th scope="col">About</th> </tr> </thead> <tbody> {% for c in cat %} <tr> <th scope="row"><a href="{% url 'all_articles' c %}" ><p> {{c}}</P></a></th> <td> How you can win in life</td> </tr> {% endfor %} </tbody> </table> </div> this is views.py : def home(request): cat = Category.objects.all() return render(request, 'blog_pages/home.html',{'cat': cat}) def all_articles(request, c): post = Post.objects.filter(category__contains = c).values() return render(request,"blog_pages/all_articles.html",{'post':post}) I am getting this error … -
AttributeError at /addtowatchlist/5: 'QuerySet' object has no attribute 'listings'
Within my app, I'm allowing any given user to add an auction listing to their watch list, but no matter what I have tried, it does not seem to work and I keep getting the error in the title. I am simply trying to access the user thats making the request and adding the listing to their watchlist and redirecting them to the main page. views.py from .models import * def add_to_watchlist(request, listing_id): listing = Listing.objects.get(id=listing_id) # Retrieving the user watchlist (where it always fails) watchlist = PersonalWatchList.objects.filter(user=request.user) # Fails here too if (watchlist.listings.all() == None) or (listing not in watchlist.listings.all()): watchlist.listings.add(listing) watchlist.save() else: messages.error(request, "Listing is already in your Watchlist.") return redirect(reverse('index')) messages.success(request, "Listing added to your Watchlist.") return redirect(reverse('index')) models.py class PersonalWatchList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) listings = models.ManyToManyField(Listing, blank=True) def __str__(self): return f"Watchlist for {self.user}" urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("create", views.createListing, name="create"), path("view/<str:listing_title>", views.view, name="view"), path("addtowatchlist/<int:listing_id>", views.add_to_watchlist, name="add_to_watchlist") ] Section of template used to add listing to watchlist <div class="listing-actions"> <a href= {% url 'view' listing.title %} class="btn btn-primary view-button">View</a> <!--TODO: Make watchlist--> <a href={% url 'add_to_watchlist' … -
Connect Django-sql-explorer using Pyodbc connection instead of default Database
I want to connect Django-SQL-explorer using Pyodbc connection instead of Django default database. Django Database connection and Django-SQL-explorer connection Pyodbc connection -
Assign foreing keys of both instances in the same time Django REST
I need a help, please. So I have 2 classes class Pokemon(models.Model): """Pokemon object""" pokedex_creature = models.ForeignKey( PokedexCreature, on_delete=models.CASCADE, ) trainer = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, ) team = models.ForeignKey( Team, on_delete=models.SET_NULL, blank=True, null=True, ) and class Team(models.Model): """Team model""" name = models.CharField(max_length=100) trainer = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True, ) pokemon_1 = models.ForeignKey( Pokemon, on_delete=models.SET_NULL, blank=True, null=True, ) pokemon_2 = models.ForeignKey( Pokemon, on_delete=models.SET_NULL, blank=True, null=True, ) pokemon_3 = models.ForeignKey( Pokemon, on_delete=models.SET_NULL, blank=True, null=True, ) I want to put a ForeingKey of Team to Pokemon model when I add this Pokemon to the team. I use ForeingKey in Team model to assign a Pokemon to this Team so I would like to make the same this Pokemon instance to see to what Team he is assigned. What is the best way to do that? I use Django 3.2.12 and REST Framework 3.13.1 -
Why is google trying to access my backend server?
I have a productionized Django backend server running as on Kubernetes (Deployment/Service/Ingress) on GCP. My django is configured with something like ALLOWED_HOSTS = [BACKEND_URL,INGRESS_IP,THIS_POD_IP,HOST_IP] Everything is working as expected. However, my backend server logs intermittent errors like these (about 7 per day) DisallowedHost: Invalid HTTP_HOST header: 'www.google.com'. You may need to add 'www.google.com' to ALLOWED_HOSTS. DisallowedHost: Invalid HTTP_HOST header: 'xxnet-f23.appspot.com'. You may need to add 'xxnet-f23.appspot.com' to ALLOWED_HOSTS. DisallowedHost: Invalid HTTP_HOST header: 'xxnet-301.appspot.com'. You may need to add 'xxnet-301.appspot.com' to ALLOWED_HOSTS. DisallowedHost: Invalid HTTP_HOST header: 'www.google.com'. You may need to add 'www.google.com' to ALLOWED_HOSTS. DisallowedHost: Invalid HTTP_HOST header: 'narutobm1234.appspot.com'. You may need to add 'narutobm1234.appspot.com' to ALLOWED_HOSTS. DisallowedHost: Invalid HTTP_HOST header: 'z-h-e-n-116.appspot.com'. You may need to add 'z-h-e-n-116.appspot.com' to ALLOWED_HOSTS. DisallowedHost: Invalid HTTP_HOST header: 'www.google.com'. You may need to add 'www.google.com' to ALLOWED_HOSTS. DisallowedHost: Invalid HTTP_HOST header: 'xxnet-131318.appspot.com'. You may need to add 'xxnet-131318.appspot.com' to ALLOWED_HOSTS. DisallowedHost: Invalid HTTP_HOST header: 'www.google.com'. You may need to add 'www.google.com' to ALLOWED_HOSTS. DisallowedHost: Invalid HTTP_HOST header: 'stoked-dominion-123514.appspot.com'. You may need to add 'stoked-dominion-123514.appspot.com' to ALLOWED_HOSTS. My primary question is: Why - what are all of these hosts?. I certainly don't want to allow those hosts without understanding their purpose. Bonus question: What's the … -
Cannot establish incoming connections to docker container
I have a Django app running on docker that requires access to the Azure Storage Accounts from it. It runs fine when the Django server runs from the host computer, but, the connection to the Azure Storage Account fails when running from the container. I guess, somehow Docker is blocking the incoming traffic, as I can perform ping www.google.com.br from the container, but I never get the response back. I used to work with this very same app from a MacOS laptop with no issues (the app establishes connection to the Azure Service), but it does not works since I changed my development setup to Linux (Linux KDE Neon). Any ideas on how can I allow docker containers to receive traffic from the internet? Thanks. This is the error I see that indicates me that Azure Storage Account connection is not allowed (plus the fact this works when I run the same from my MacOs notebook). <urllib3.connection.HTTPSConnection object at 0x7f1286429e10>: Failed to establish a new connection: [Errno -3] Try again')> This is my Docker compose file: the Celery workers are the containers attempting to establish connection with Azure: `version: '3.8' services: web-server: build: ./apps ports: - 8000:8000 - 5678:5678 - … -
Listing profiles and show related user email field in template
Need to list my profilemodel-records. Would like to include the user.email field in the template.(The users email related to the profile...) To get the users email is just {{ user.email }} I was sure I had done it like this before, but now nothing..... {{ profile.user.email }} This is my view: def profileall(request): profilelist = Profile.objects.all() return render(request, 'docapp/profilelist.html',{'profilelist':profilelist}) -
Is there a way to use an abstract value in field in Django Framework?
I have a code like this: class Food(models.Model): ... class Meta: abstract = True class Pizza(Food): ... class Burger(Food): ... class Order(models.Model): ... food_type = models.OneToOneField(Food, on_cascade=CASCADE) So, I'm wondering, if there is a way to set food_type, so it will point either at pizza or at burger model. I've tried to do it like: class Food(models.Model): order = models.OneToOneField(Order, on_delete=CASCADE) class Meta: abstract = True But that allows to have both 'Burger' and 'Pizza' be connected to 'Order', and that's not what I need. -
Jenkins pipeline does not create postgresql_data volume but running docker compose up -d commad manually creates volumes
I'm pretty new to whole docker,docker-compose,jenkins and whole CI-CD concept. So, I may be missing a very simple point. My application is a django web app with postgresql and nginx. If I run docker compose build and docker compose up -d, 3 containers runs and docker volumes are created without any problems. Now I am trying to run these 3 containers with jenkins. I clone my app's repo to jenkins and run docker compose build and docker compose up -d in my pipeline. My app works, static volume is created but postgresql_data docker volume is not created and it's gone if I restart my host machine I thought this might be because of user permissions but the static volume is created by the same jenkins task. Thanks in advance. jenkinsfile pipeline { agent { node { label 'agent-compose' } } environment{ DOCKERHUB_CREDENTIALS = credentials('DockerHub') } stages { stage('Build') { steps { sh 'docker compose build' echo 'Docker compose build is Completed, these images are created:' } } stage('Run The Services') { steps { sh 'docker compose up -d' } } stage('Login To Docker Hub') { steps { sh 'echo $DOCKERHUB_CREDENTIALS_PSW | docker login -u $DOCKERHUB_CREDENTIALS_USR --password-stdin' echo 'Login completed' } … -
How to Access method decorated with @action decorator of a view inherited from APIView Class in urls.py file in DRF?
I need to apply different permission on different methods of my View class which is inherited from APIView in a DRF application. To achieve this I am using @action decorator on my methods of view. Here is views.py code class UserView(APIView): @action(methods=['post'], detail=False, permission_classes=[AllowAny]) def create(self, request): serializer = UserRegSerializer(data=request.data) user_service = UserService() try: serializer.is_valid(raise_exception=True) serialized_data = serializer.validated_data registered_user = user_service.create_user(serialized_data) payload = registered_user.__dict__ response = ResponseGenerator(payload, constants.SUCCESS_KEY) except Exception as e: response = ResponseGenerator(e) return Response(data={"Response": response.get_custom_response()}) I am not getting that how could I access this method in my urls.py file against the pattern '/user', here is my urls.py code. urlpatterns = [ path('user', UserView.as_view()), ] I was using ChatGPT to answer this query of mine. It suggested some ways to use a dictionary object passed {'post':'create'} in as_view() method of View in urls.py as following. urlpatterns = [ path('user', UserView.as_view({'post':'create'})), ] In this it told me that key of the dictionary should be the http method used to access that method against the url pattern and value of dictionary should be the method which you want to access against the given url. But its not working, and gives me following error when I try to start my … -
Cannot display data from the database using id = pk in django
I am trying to fetch data from the database and display it in view_data.html. I cannot seem to do it. I am not sure if i understand the use case of id = pk at this point. I want to be able to display data containing particular host when i click on the view button under the 'host' Can anyone help me display the data. Here is what I have done so far: models.py from django.db import models from django.contrib.auth.models import User class Information(models.Model): host = models.CharField(max_length=200, null=True, blank=False) hostname = models.CharField(max_length=200, null=True, blank=False) port = models.IntegerField() platform = models.CharField(max_length=200, null=True, blank=False) username = models.CharField(max_length=200, null=True, blank=False) password = models.CharField(max_length=200, null=True, blank=False) groups = models.CharField(max_length=200, null=True, blank=False) def __str__(self): return self.host views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Information from .forms import MyForm def home(request): informations = Information.objects.all() context = {'informations':informations} return render(request, 'polls/home.html', context) def view_data(request, pk): information = Information.objects.get(id=pk) context = {'information':information} return render(request, 'polls/view_data.html') def my_form(request): if request.method == "POST": form = MyForm(request.POST) if form.is_valid(): form.save() return redirect('home') else: form = MyForm() return render(request, 'polls/room_form.html', {'form': form}) forms.py from django import forms from .models import Information class MyForm(forms.ModelForm): class Meta: model … -
I want to use decimal for currency but it throws error
I want to use decimal for currency but it throws error i do decimal 9.2 but it renders as 9.0 MySQL V 5.7.14 enter image description here -
Considerations of building an Android service as system app (OEM)
I'm working on an OEM project where we need a background service (no UI) to be working continuously. Of course it'll be an app signed with the OEM key, so it shouldn't be any trouble related to background services Android's restrictions. But, as it is the first time developing this, is there any consideration regarding the implementation of the service lifecycle and workflow? Plus, anything important to consider regarding the testing flow of the project? Thank you, any help related to OEM-apps development will be much appreciated.