Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Return JSON or template based on query parameter with django restframework
''' class ProfileList(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'profile_list.html' def get(self, request): queryset = Profile.objects.all() return Response({'profiles': queryset}) ''' As documented, the above View renders and returns a html template. However, how to control the view to return the json or html template in the view? For example, by providing parameter as ?type=html, it returns the html page; and with ?type=json it return the json data. -
Django - Counting ManyToMany Relationships
In my model, I have many Things that can have many Labels, and this relationship is made by user-submitted Descriptions via form. I cannot figure out how to count how much of each Label each Thing has. In models.py, I have: class Label(models.Model): name = models.CharField(max_length=100) class Thing: name = models.CharField(max_length=100) class Description: thingname = models.ForeignKey(Thing, on_delete=models.CASCADE) labels = models.ManyToManyField(Label,blank=True) If we say our current Thing is a cat, and ten people have submitted a Description for the cat, how can we make our template output an aggregate count of each related Label for the Thing? For example: Cat 10 fluffy 6 fuzzy 4 cute 2 dangerous 1 loud I've tried a few things with filters and annotations like counts = Label.objects.filter(description_form = pk).annotate(num_notes=Count('name')) but I think there's something obvious I'm missing either in my views.py or in my template. -
"formfield_overrides" vs "formfield_for_dbfield()" vs "form" vs "get_form()" to change the width of the field in Django Admin
For example, there is Person model below: # "models.py" from django.db import models class Person(models.Model): name = models.CharField(max_length=20) age = models.PositiveSmallIntegerField() def __str__(self): return self.name Then, when using formfield_overrides, formfield_for_dbfield(), form or get_form() below: # "admin.py" from django.contrib import admin from .models import Person from django.db import models from django import forms @admin.register(Person) class PersonAdmin(admin.ModelAdmin): formfield_overrides = { # Here models.PositiveSmallIntegerField: { 'widget': forms.NumberInput(attrs={'style': 'width:100ch'}) }, } Or: # "admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): # Here def formfield_for_dbfield(self, db_field, request, **kwargs): field = super().formfield_for_dbfield(db_field, request, **kwargs) if db_field.name == 'age': field.widget.attrs['style'] = 'width: 100ch' return field Or: # "admin.py" from django.contrib import admin from .models import Person from django import forms class PersonForm(forms.ModelForm): age = forms.CharField( widget=forms.NumberInput(attrs={'style':'width:100ch'}) ) @admin.register(Person) class PersonAdmin(admin.ModelAdmin): form = PersonForm # Here Or: # "admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): # Here def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) form.base_fields['age'].widget.attrs['style'] = 'width: 100ch;' return form I can change the width of age field on "Add" and "Change" pages as shown below: Now, are there any differences between formfield_overrides, formfield_for_dbfield(), form and get_form() to change the width of the field in … -
ValueError at /book/add Field 'id' expected a number but got 'add' --- django
A working site was bringing the collection of books with its content displayed But when I add a function def addbook(request): it gives me a problem this: ValueError at /book/add Field 'id' expected a number but got 'add'. in -- all_book.html: {% extends 'base.html' %} {% block content %} <h1>kljgf</h1> <a href ="{% url 'addbook' %}">Add Book</a> {% for book in books %} <h3> <a href = "{% url 'detail_book' book.id %}">{{book.namebook}}</a> </h3> <hr> {% endfor %} {% endblock content %} in views: def detail_book(request, id): boo = book.objects.get(id=id) context = {'book' : boo} return render(request, 'detail_book.html', context) def addbook(request): book_form = book_form() context = {'form' : book_form} return render(request, 'add_book.html', context) in url: path('book/<id>', views.detail_book, name="detail_book"), path('book/add', views.addbook, name="addbook"), in add_book.html {% extends 'base.html' %} {% block content %} <h1>add book </h1> <form method="POST"> {% csrf_token %} {{form}} </form> {% endblock content %} -
How to create a function for Phone Dialing [for Python Django]?
I am an Python Django newbie , trying to find an function to add to my website im working on. What Im trying to do is simple operation - when you click a "Call us" button in my website, to open the Phone Dial with the specific number inputed in the phone dial input line not call immeadiately, just automatically prewrited the set phone number, as shown in the picture I searched alot in google,git,youtube, but I couldn't find what exacly I am looking for. -
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.