Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filtering with ipaddress lib
For example, I got a table with address field which can store both ip and subnet addresses. Called IPTable. And a got entire ip address like '127.0.0.1' How can i write a query to get data that into subnet? IPTable.objects.create(address='127.0.0.0/32') IPtable.objects.filter('127.0.0.1' in '127.0.0.0/32')?? Tried to use ipaddress lib to get all ips from this subnet -
Create and update 3 tables OneToMany relationship with nested serializers in Django Rest Framework
I have 3 tables in my database : Quiz - question - answer, with this models class Quiz(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) class Question(models.Model): id = models.AutoField(primary_key=True) question = models.CharField(max_length=255) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name="questions") class Answer(models.Model): id = models.AutoField(primary_key=True) answer = models.CharField(max_length=255) is_correct = models.BooleanField() question = models.ForeignKey( Question, on_delete=models.CASCADE, related_name="answers" ) i need to override create and update method for create or put/patch a quiz with questions and answers in one time with the default route. i try différent things to do this. My create methode is is operational thise is the serializers of quizz questio nand answers : class AnswerSerializer(ModelSerializer): class Meta: model = Answer fields = ( "id", "answer", "is_correct", ) class QuestionSerializer(ModelSerializer): answers = AnswerSerializer(many=True, required=True) class Meta: model = Question fields = ("id", "question", "answers") class QuizSerializer(ModelSerializer): questions = QuestionSerializer(many=True, required=True) class Meta: model = Quiz fields = ("id", "name", "questions") # create function for create a quiz with questions and answers def create(self, validated_data: Dict[str, Any]) -> Quiz: questions = validated_data.pop("questions") quiz = Quiz.objects.create(**validated_data) for question in questions: answers = question.pop("answers") question = Question.objects.create( quiz=quiz, question=question.get("question") ) for answer in answers: Answer.objects.create( question=question, answer=answer.get("answer"), is_correct=answer.get("is_correct"), ) return quiz my views : … -
Data does not get saved in database ; unexpected keyword arguments
I have gone through many solutions posted on SO and other places but have been running into the same issue. Pretty new to django and trying to understand where I am going wrong I am getting the following error TypeError: Basetable() got unexpected keyword arguments: 'CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents' I have the following JSON Data jsonToUse = { "CompanyId": "320193", "CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents": [ { "decimals": "-6", "unitRef": "usd", "value": "39789000000" }, { "decimals": "-6", "unitRef": "usd", "value": "50224000000" }, { "decimals": "-6", "unitRef": "usd", "value": "25913000000" }, { "decimals": "-6", "unitRef": "usd", "value": "35929000000" } ] } Model: class Basetable(models.Model): basetable_id = models.AutoField(primary_key=True) CompanyId = models.IntegerField() class Cashcashequivalentsrestrictedcashandrestrictedcashequivalents(models.Model): cashcashequivalentsrestrictedcashandrestrictedcashequivalents_id = models.AutoField( primary_key=True) unitRef = models.CharField(max_length=100) value = models.CharField(max_length=100) decimals = models.IntegerField() basetable_id = models.ForeignKey(Basetable, on_delete=models.CASCADE) Serializer: class CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalentsSerializer(serializers.ModelSerializer): class Meta: model = Cashcashequivalentsrestrictedcashandrestrictedcashequivalents fields = ['decimals', 'unitRef', 'value'] class CashFlowSerializer(serializers.ModelSerializer): CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents = CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalentsSerializer( many=True) class Meta: model = Basetable fields = "__all__" View: .....#TRIMMED GET SYNTAX..... check = CashFlowSerializer(data=jsonToUse) if (check.is_valid(raise_exception=True)): print("ready to send to db") check.save() return JsonResponse(jsonToUse, safe=False) I want to save the data in the database for the provided JSON -
¿How can i to read request headers using django test?
I'm using ApiClient class but I don't know how to send a headers, I'm trying to do it like this, but the answer is that I'm not authorized. I have been trying to solve it for several hours but I have not been able to, your contribution would be of great help. self.client = APIClient() self.jwt = response.json()["access"] self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.jwt) self.client.headers.update({'Origin': 'https://travelingapps.com.co'}) this is te response: ('status_code', 401), ('content_type', 'application/json'), ('content', 'UNAUTHORIZED')]) -
Graphene Enums not working when using without creating a new class
From the documentation, it's evident that we are not bound to create new classes for using Enums. I have the following code snippet: from graphene import Enum, InputObjectType GRAPH_TYPES = [ ('step', 'Step graph'), ('bar', 'Bar graph'), ('line', 'Line graph'), ('dot', 'Dot graph'), ] class DataType(Enum): VELOCITY = 'velocity' ACCELERATION = 'accelration' class SomeInput(InputObjectType): data_type = DataType('DataTypeEnum') graph_type = Enum('GraphTypeEnum', GRAPH_TYPES) When I head over to GraphiQL, I am able to see SomeInput but graph_type is missing inside. Package versions: graphene-django==2.12.1 graphene==2.1.8 -
Is it acceptable to put a break points in the Django admin site file (admin.py) of my app to debug?
Simply, I need to debug the admin.py file, but it doesn't give me the chance for this, so the error pops up directly without stopping at the break point or going line by line after it. So here I have a problem at line 14 related to the tuples because I have nested tuples without adding a comma after the nested tuple. enter image description here I tried to render the page of the admin site to implement the method line by line, but the error happens directly Sorry for this long question . -
Google Sheets Python Client gives indeterministic behavior
I have created a Django project with uses Google Sheets to store some data. When I make a request to an endpoint (/ca/register), sometimes the request passes successfully with a new ca object being created in the database, and its details being added to the corresponding Google Sheet too. Other times, with the same data, the new CA's data is added to the Django database, but the script responsible for adding the data to the Google Sheets fails, leading the request to fail as a whole. I get a weird error in the deployment logs. PS. CA stands for Campus Ambassador. Attaching the relevant pieces of codes and logs: Error Log Internal Server Error: /ca/register/ Traceback (most recent call last): File "/opt/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/opt/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/venv/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/opt/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/opt/venv/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/opt/venv/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/opt/venv/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/opt/venv/lib/python3.7/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/app/ca/views.py", line 19, in post … -
How to combine multiple custom management commands in Django?
I wrote a set of commands for my Django project in the usual way. Is it possible to combine multiple commands into one command? class Command(BaseCommand): """ import all files in media in dir and add to db after call process to generate thumbnails """ def handle(self, *args, **options): ... To make easy steps I have commands like: import files, read metadata from files, create thumbnails etc. The goal now is to create a "do all" command that somehow imports these commands and executes them one after another. How to do that? -
I am adding a new row instead of make changes in a existing row in my DB
I am trying to save my form in my data base. But my code adds a new row instead of save changes to the existing one. where is my mistake? view.py def settings(request): error = '' if request.method == 'POST': new_form = TrafficSourcesForm(request.POST) if new_form.is_valid(): new_form.save() else: error = 'Something went wrong!' new_form = TrafficSourcesForm() forms = [TrafficSourcesForm(instance=x) for x in TrafficSources.objects.all()] return render(request, 'mainpage/dashboard.html', {'new_form': new_form, 'forms': forms, 'error': error}) template <div class="table table-striped table-hover"> <div class="table-row"> <th style="width: 42%">Name</th> <th style="width: 43%">Token</th> <th style="width: 15%">Action</th> </div> {% for form in forms %} <div class="table-row"> <form method="POST"> {% csrf_token %} <div class="table-cell">{{ form.name }}</div> <div class="table-cell">{{ form.token }}</div> <div class="table-cell"><button class="btn btn-lg btn-success w-100"">Save</button></div> </form> </div> </div> If its not clear: I am showing all the table from my databese on the page. I want to edit them and save again to the database. -
Is it possible to map a field to a custom template radio button group?
Question in the title. I have a form like so class SelectTypeForm(forms.Form): the_type = forms.CharField(max_length=100) I have a custom template with a radio button group. How can make the field get the selected value? -
How to merge two model sinto one mode with django?
I have to identical models: class AnimalGroup(models.Model): name = models.CharField(max_length=50, unique=True) description = models.TextField(max_length=1000, blank=True) images = models.ImageField(upload_to="photos/groups") class AnimalSubGroup(models.Model): name = models.CharField(max_length=50, unique=True) description = models.TextField(max_length=1000, blank=True) images = models.ImageField(upload_to="photos/groups") and they have a on-to-many relationship. So AnimalGroup can have multiple AnimalSubGroups But as you see they have identical fields. Question: how to make one model of this? -
How to solve libmagic.dylib - incompatible architecture error?
I'm trying to install my Django project to my M1 Mac laptop but it is giving errors. ..OSError: dlopen(/Users/e.celik/Library/Python/3.8/lib/python/site-packages/magic/libmagic/libmagic.dylib, 0x0006): tried: '/Users/e.celik/Library/Python/3.8/lib/python/site-packages/magic/libmagic/libmagic.dylib' (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64')), '/System/Volumes/Preboot/Cryptexes/OS/Users/e.celik/Library/Python/3.8/lib/python/site-packages/magic/libmagic/libmagic.dylib' (no such file), '/Users/e.celik/Library/Python/3.8/lib/python/site-packages/magic/libmagic/libmagic.dylib' (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64')) I do not know why is this happening? I'm using python 3.8 and last version of pip. How can I fix that? -
why there is a yellow line underneath the import modules?
I see this is a problem but the program still runs. Can you point out where is the problem? I'm newbie to programming. Especially to python language.enter image description here I can't solve this on my own even if I search it online. I need a finger to point out where can I solve this problem in models.py. -
Running test together fails, running test alone succeeds
I'm using pytest. Going through the tests with a debugger, running both test_joining_previously_entered_queue_returns_previous_queue_details and test_joining_queue_enters_correct_position together, test_joining_previously_entered_queue_returns_previous_queue_details succeeds but test_joining_queue_enters_correct_position fails at queue = get_object_or_404(Queue, pk=kwargs["pk"]) in the JoinQueue view, where the view throws a 404 If I run test_joining_previously_entered_queue_returns_previous_queue_details individually, then the test will pass no problem. What should happen is that create_company_one creates a Company object, which in turn creates a Queue object (shown in the overridden save method of Company). The associated Queue object does not seem to be created if test_joining_queue_enters_correct_position is run with the other test, but works if the test is run standalone Why does this happen and how can I fix it? test_join_queue.py def create_company_one(): return Company.objects.create(name='kfc') @pytest.mark.django_db def test_joining_previously_entered_queue_returns_previous_queue_details(authenticated_client: APIClient): create_company_one() url = reverse('user-queue-join', args=[1]) first_response = authenticated_client.put(url) first_data = first_response.data second_response = authenticated_client.put(url) second_data = second_response.data assert first_data == second_data @pytest.mark.django_db def test_joining_queue_enters_correct_position(factory: APIRequestFactory): """ Makes sure that whenever a user joins a queue, their position is sorted correctly based on WHEN they joined. Since all users in self.users join the queue in a time canonical manner, we can iterate over them to test for their queue positions. """ create_company_one() users = create_users() view = JoinQueue.as_view() url = reverse('user-queue-join',args=[1]) request = … -
In django, can I prevent attacker from re-using a session from one domain to gain access to another domain?
I have a django project serving two different purposes. On one subdomain, let's call it public.example.com, I allow unprivileged users to access a portal to edit their profile and settings. On another domain, private.example.com, I give the user access to some management functions. I have the default django session cookie settings, so when I log in to public.example.com and then try accessing private.example.com, I get redirected to a login page. This is normal and expected because the browser will not send the session cookie to any domain other than public.example.com. If I copy the session cookie that is sent to public.example.com and tamper with the request made to private.example.com so that I send the public cookie to the private domain, django responds with a 200 OK answer and renders the page as if I am a user that has logged in to that domain. I can not find any documentation that tells me that sessions are limited to the domains that they originated from, other than the default browser behaviour of limiting cookies to their respective domains. Is it possible to prevent such unwanted access without serving the project on two different instances with two different databases? -
Slow dropdown menu for foriegn key
I have created a backend website and is in production. It is using jawsdb and one of my models have 15000 records. The problem is when I click on the dropdown list of another model in admin panel it to select a model, it takes too much time for the list to appear and the search bar on the dropdown list hangs as well while writing. Is it because of cheap heroku plans and jawsdb. I could nt have messed up in the code. -
Error Heroku , desc="No web processes running" method=GET path="/favicon.ico"?
2023-01-24T12:48:09.490016+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=pizza.herokuapp.com request_id=cb7658a6-061a-4ae1-8e3c-f07247d956fc fwd="78.141.167.114" dyno= connect= service= status=5 03 bytes= protocol=https 2023-01-24T12:48:10.638376+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=pizza.herokuapp.com request_id=0a379b0d-021f-4dc8-967b-b897ff678596 fwd="78.141.167.114" dyno= connect= servic e= status=503 bytes= protocol=https I don't understand this error, what it means by the /favicon.ico being unable to have the get method? -
Why i am getting "error": "user_not_found" whenever i call "users.profile.get" slack API?
So, I created the slack bot and it was working completely fine but, When I distributed the slack bot app to another workspace I started facing the "user not found" error on API call of "users_profile_get" as I have also cross-checked the required scopes for this API, user_id, and access token and they are completely fine but still API call returns user not found. I need your help guys on it as I am missing something while distributing the app or Is there any other problem? There is also One strange thing that I can call "chat.postMessage" API of slack and it runs successfully. result = app.client.users_profile_get(user=slack_id) While calling this API, I am getting error : { "ok": false, "error": "user_not_found" } -
Additional DRF serializer field with search request only
I'm working with postgis and geodjango and i have a Store model as follow: from django.contrib.gis.db import models . . class Store(models.Model): . . . # Storing the exact location of the store with (longtitude, latitude) geo_location = models.PointField(null=True, blank=True, srid=4326) . . . and the serializer: from rest_framework import serializers from rest_framework_gis.serializers import GeoFeatureModelSerializer from .models import Store class StoreSerializer(GeoFeatureModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') # This field is generated only when there is a near by store filter distance = serializers.DecimalField(source="dist.m", max_digits=10, read_only=True, decimal_places=2) class Meta: model = Store geo_field = "geo_location" fields = '__all__' The view: from rest_framework import generics from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAuthenticated from rest_framework_gis.pagination import GeoJsonPagination from django.contrib.gis.geos import GEOSGeometry from django.contrib.gis.db.models.functions import Distance from rest_framework_gis.filters import DistanceToPointFilter, DistanceToPointOrderingFilter from .serializers import StoreSerializer from .models import Store from .permissions import IsOwnerOrReadOnly class StoreListView(generics.ListCreateAPIView): def get_queryset(self): queryset = Store.objects.all() # If there are user coordinates in the query params point = self.request.query_params.get('point', None) if point : # in case of white space after the simicolon in lat, lng ex: (point='12.2123, 5.21354') coordinates = [crd.strip() for crd in point.split(',')] user_point = GEOSGeometry('POINT('+ coordinates[0]+ ' ' + coordinates[1]+ ')', srid=4326) queryset = queryset.annotate(dist=Distance('geo_location', user_point)).order_by('dist') return queryset queryset = Store.objects.all() … -
How to print a form in PHP or django to already structured pdf?
all right? I have a doubt about how I can make a form in php or django in which the client completes it, then it is sent to the server and when I refresh the page, the pdf document will appear for printing. In this case, the pdf will already have a ready-made structure with gaps, these gaps will be filled in with the customer's information. I just need to fill out this form and print it later, if it is not necessary to save it on the server, no problem. -
Copy data from guest user Account and delete the guest user and send data to logged in or registered user with pure django
I'm currently working on an e-commerce website and the customer can order without logging in, but what I'm looking for is that after the customer add product to the cart, when they decide to Checkout must login or register. What I want is for the guest user account to be deleted and the card data to be transferred to the logged in or registered user account. ` """ My custom user manager """ class Account(AbstractBaseUser): phone_number = models.CharField(unique=True, max_length=11, validators=[MinLengthValidator(11)], blank=True) session_key = models.CharField(max_length=40, null=True, blank=True) USERNAME_FIELD = 'phone_number'` `class OrderSummaryView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) context = { 'object': order } return render(self.request, 'shop/ordersummary.html', context) except: """ **here i can create Guest user account with session_key** """ session_key = self.request.COOKIES['sessionid'] customer, created = Account.objects.get_or_create(session_key=session_key) order = Order.objects.get(user=customer, ordered=False) context = { 'object': order } return render(self.request, 'shop/ordersummary.html', context)` `def CheckoutView1(request): """ **Here when the guest user wants to checkout, he/she has to login or register And when they log in I want to remove the guest account and send the data to the logged in or registered account.** """ if not request.user.is_authenticated: return redirect("login") context = {} if request.POST: form = CheckOutUpdateForm(request.POST, instance=request.user) if form.is_valid(): … -
JWT authentication module not being recognized in django rest api even after being installed
I'm implementing JWT authentication in my API made from Django. I installed the recommended package (rest_framework_jwt) and added it to the required files according to the documentation. However, upon running the server, I'm getting the following error:- Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.11/threading.py", line 1038, in _bootstrap_inner self.run() File "/usr/local/lib/python3.11/threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.11/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/usr/local/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1128, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework_simplejwt' Here is my settings.py file:- import … -
Send scheduled message everyday to all users using the slack bot
I am creating a slack bot project using Django. Here I would like to send a scheduled message to every user of the workspace. Every day, the bot will ask specific questions to all users, but personally. In that case, how can I post questions every day within a specific schedule? Which tool or django-package will be appropriate to fulfill my problem? -
Django image dosen't show when searching?
I have an inventory app with products and its name, photo. I query the records in HTML page and all works fine and the images showing. when i try to search the result come without the photo. View: def inventory_search_view(request): query = request.GET.get('q') product_search = Inventory.objects.filter(name__icontains = query).values() print(product_search) context = {'object_list': product_search} return render(request, 'inventory_search.html', context = context) HTML: <div class="product-image"> <img src="{{object.image}}" alt="{{object.name}}" /> <div class="info"> <h2> Description</h2> <ul> {{object.description}} </ul> </div> </div> </div> search form: <form action="search/"> <input type="text" name="q"> <input type="submit" value="Search"> </form> Thanks in advance. -
Django - How to get object on another app model without direct relationship in the parent model?
I have a Profile model, Award model as child of the Profile model [which takes other award details like achievement detail], and a List_of_awards model as child of the Award model [which takes list of awards and a count of how may profiles has the specific award]. Award model is inline with the Profile model using Foreignkey and List_of_awards model as Foreignkey field in the Award model for the choices of awards. What I am trying to do is, display the List_of_awards in the Profile model. The idea originated when I was able to display the List_of_awards in the list_display of the Award model', so, I was trying to link List_of_awardsin theProfile` which has no direct relationship. class Profile(models.Model): first_name = models.CharField(verbose_name=_('First Name'), max_length=255, null=True, blank=True, ) middle_name = models.CharField(verbose_name=_('Middle Name'), max_length=255, null=True, blank=True) last_name = models.CharField(verbose_name=_('Last Name'), max_length=255, null=True, blank=True) .... class Award(models.Model): list_of_award = models.ForeignKey('system_settings.Ribbon', related_name='awards_ad_ribbon', on_delete=models.DO_NOTHING, verbose_name=_('Type of Award'), blank=True, null=True) achievement = models.TextField(verbose_name=_('Achievement')) profile = models.ForeignKey('reservist_profile.Profile', related_name='awards_ad_profile', verbose_name=_('Profile'), on_delete=models.DO_NOTHING, blank=True, null=True) def image_tag(self): from django.utils.html import format_html return format_html('<img src="/static/media/%s" title="" width="75" /> %s' % (self.list_of_award.image,self.list_of_award.award)) image_tag.short_description = 'Award' class Ribbon(models.Model): award = models.CharField(verbose_name=_('Award'), max_length=255, null=True, blank=True) award_desc = models.TextField(verbose_name=_('Description'), max_length=255, null=True, blank=True) image = models.ImageField(verbose_name …