Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django nested transacion.atomic() questions. Is it significant what exception is raised to abort a transaction?
I'm writing code which is basically to upload a spreadsheet. Each row requires the creation of multiple DB objects and relationships. If the data in the row is incapable of being stored, I want to tell the user about the problem, abort the transction representing this row, and continue with the next row. But if there's a more disastrous failure or "too many errors", I want to abort the outer transaction to commit nothing at all to the DB. Is there any particular recommended Python or Django exception class to subclass, to generate exceptions for this purpose? And can I safely catch IntegrityError in the row-processing code so as to issue the best possible error to the user, and then exit the inner transaction by railsing a different exception? I'm thinking Class CannotStoreRow( ValueError): pass, because something in that row of data is an invalid value. Is there any reason something other than ValueError should be used? (Why doesn't Django supply something like AbortTransaction, or does it? ) Overall outline code: try: with transaction.atomic(): process_spreadsheet() except CannotContinueLikeThis: # tell user we have given up and reassure that the DB is unaltered # uncaught exception, DB likewise undamaged? def process_spreadsheet(): # … -
Django ORM: move filter after annotate subquery
This Django ORM statement: Model.objects.all() \ .annotate( ord=Window( expression=RowNumber(), partition_by=F('related_id'), order_by=[F("date_created").desc()] ) ) \ .filter(ord=1) \ .filter(date_created__lte=some_datetime) Leads to the following SQL query: SELECT * FROM ( SELECT id, related_id, values, date_created ROW_NUMBER() OVER ( PARTITION BY related_id ORDER BY date_created DESC ) AS ord FROM model_table WHERE date_created <= 2022-02-24 00:00:00+00:00 ) WHERE ord = 1 As you can see, the date_created__lte filter gets applied on the inner query. Is it possible to control statement location preciser and move the filter outside, like ord? -
Django how to export datetime from MySQL to csv as correct format
I can show datetime from mysql by convert datetime of mysql to string like this code. upd_time = str(log.updated) Then, I use javascript to convert to date like this <script> const dateFromMysql = '{{ upd_time }}'; // conver the string into javascript date object const dateObject = new Date(dateFromMysql); // output complete date in javascript document.getElementById("dt").innerHTML = dateObject; </script> It show correct date. I export datetime from mysql to csv with this code. def export_csv(request): key=request.POST['key'] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename= '+ str(key)+".csv" writer = csv.writer(response) writer.writerow(['field1','field2','updated']) users = Data.objects.filter(key=key).values_list('field1','field2','updated') for user in users: writer.writerow(user) return response In column updated show the time like this. It is UTC timezone. I change TIME_ZONE and USE_TZ in setting it show same time format in mysql. How to export datetime from csv to local timezone? -
How to show reversed foregin key in DRF
I have 2 model and i want to Retrieve all info about card and his reversed foreign key but when i try to do that i get only Card field and not DigitalCard fields models.py class Cards(models.Model): user = models.ForeignKey(IndividualUser, on_delete=models.CASCADE) main_business_card = models.ForeignKey('UserDigitalCard', on_delete=models.PROTECT, null=True, blank=True) class UserDigitalCard(models.Model): card = models.ForeignKey(Cards, on_delete=models.CASCADE) digital_card = models.FileField(blank=True, null=True, upload_to=digital_card_upload_to) digital_card_name = models.CharField(max_length=100) generated_code = models.CharField(max_length=30, default=generate_code) serializer.py class GetDigitalCardSerializer(serializers.ModelSerializer): class Meta: model = UserDigitalCard fields = ('digital_card', 'digital_card_name', 'generated_code') class GetCardSerializer(serializers.ModelSerializer): digital_cards = GetDigitalCardSerializer(read_only=True, many=True) class Meta: model = Cards fields = ('user', 'main_business_card', 'digital_cards') views.py class GetUserCards(generics.RetrieveAPIView): queryset = Cards.objects.all() serializer_class = GetCardSerializer permission_classes = (IsAuthenticated, ) thats what i`ve got { "user": 1, "main_business_card": 6 } -
how to add a huge amount of data in database using Django/python
I am trying to add a huge amount of data in my Django app, data is about 800k, and am calculating some kind of distance and adding an empty field in every input. here is how my models.py looks : class MapLayers(models.Model): """ This Model Saves the KML Files to be shown as map layers in the application """ directory_string_var = "upload/files/" # Fields created = models.DateTimeField(auto_now_add=True, editable=False, verbose_name=_( "Date Created"), help_text=_("Date the layer created at")) last_updated = models.DateTimeField(auto_now=True, editable=False, verbose_name=_( "Last Update"), help_text=_("Date the layer was last updated")) file = models.FileField(upload_to=get_file_path, help_text=_('Uploaded File'), verbose_name=_('File')) name = models.CharField(max_length=100, help_text=_('Map Layer name'), verbose_name=_('Map Layer name')) category = models.ForeignKey( LayersCategory, on_delete=models.CASCADE, null=True, verbose_name=_("Category"), help_text=_("Category of the current being uploaded layer")) element_count = models.IntegerField(default=0, verbose_name=_("Elements Count"), help_text=_("Shows how many elements inside this file")) class Meta: """ Define the name user will see this model in the admin dashboard """ verbose_name = _('Map Layers') verbose_name_plural = _('Map Layers') def __str__(self): """ Define the object viewable name in the admin dashboard """ return str(self.pk) class WaterElement(models.Model): """ Saves the Name of the internal elements inside every layer """ element_name = models.CharField(max_length=100, verbose_name=_("Element name"), help_text=_("The name of the water element")) map_layer = models.ForeignKey(MapLayers, on_delete=models.CASCADE, verbose_name=_("Map Layer … -
Django error path does not exist. Static files sometimes do not load
I have a weird problem with my app in Django. The link for the app is www.mativated.com. The problem is - sometimes the app loads normally, but very often, some static files do not load - that's why it looks like page is bugged. These are the logs. I am using Whitenoise to serve files in development. My settings are: STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' I checked the file logo.removebg, and whenever it appears it is called correctly - like this src="{% static 'main/img/logo-removebg.png' %}"> I've been fighting with all these static files since one month, I am looking for any help, advice. I can give you access to files, or give more specific informations. Traceback (most recent call last): File "/home/srv52965/virtualenv/main/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/srv52965/virtualenv/main/3.8/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/srv52965/virtualenv/main/3.8/lib/python3.8/site-packages/django/views/static.py", line 40, in serve raise Http404(_("\u201c%(path)s\u201d does not exist") % {"path": fullpath}) django.http.response.Http404: \u201c/home/srv52965/main/staticfiles/main/img/logo-removebg.png\u201d does not exist During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/srv52965/virtualenv/main/3.8/lib/python3.8/site-packages/django/template/base.py", line 880, in _resolve_lookup current = current[bit] TypeError: 'URLResolver' object is not subscriptable During … -
Is it able to patch Django thread_sensitive for tests?
I use sync_to_async with thread_sensitive=False for async django view like this: @sync_to_async(thread_sensitive=False) def get_some_from_db(): ... But in test cases all handlers marked as thread_sensitive=False returns None. Is there any way to patch thread sensitive on True only for tests? -
Python Django with Electron React boilerplate
I'm using Electron React boilerplate for a desktop application. Now I want to use python django apis for database and business logics I'm just preferring django because of my good knowledge in it. Now I need some suggestions whether it is a good approach or not. If yes so how can I make standalone file for this approach django+eletron-react. I searched this on internet but didn't find answer -
Annotate closest OSM vertex
I'm trying to get the closest OSM vertex for each row of MyModel class MyModel(models.Model): location = GeometryField() I currently use RawSQL for this def annotate_closest_vertex(queryset): queryset = queryset.annotate( closest_vertex=RawSQL( """ SELECT id FROM planet_osm_roads_vertices_pgr ORDER BY the_geom <-> "mymodel"."location" LIMIT 1 """, (), ) ) And I would like to use the ORM I tried to create a unmanaged Model for OSM vertices class OSMVertex(models.Model): the_geom = GeometryField() class Meta: managed = False db_table = "planet_osm_roads_vertices_pgr" And a distance function class Distance(Func): arity = 2 def as_sql( self, compiler, connection, function=None, template=None, arg_joiner=None, **extra_context, ): connection.ops.check_expression_support(self) sql_parts = [] params = [] for arg in self.source_expressions: arg_sql, arg_params = compiler.compile(arg) sql_parts.append(arg_sql) params.extend(arg_params) return f"{sql_parts[0]} <-> {sql_parts[1]}", params Then using a simple Subquery def annotate_closest_vertex(queryset): queryset = queryset.annotate( closest_vertex=Subquery( OSMVertex.objects.order_by( Distance("the_geom", OuterRef("location")) ).values_list("pk")[:1] ) ) However I get the error /usr/local/lib/python3.8/site-packages/django/db/models/query.py:1324: in _fetch_all self._result_cache = list(self._iterable_class(self)) /usr/local/lib/python3.8/site-packages/django/db/models/query.py:51: in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) /usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py:1162: in execute_sql sql, params = self.as_sql() /usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py:513: in as_sql extra_select, order_by, group_by = self.pre_sql_setup() /usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py:55: in pre_sql_setup self.setup_query() /usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py:46: in setup_query self.select, self.klass_info, self.annotation_col_map = self.get_select() /usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py:262: in get_select sql, params = self.compile(col) /usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py:445: in compile sql, params = node.as_sql(self, self.connection) /usr/local/lib/python3.8/site-packages/django/db/models/expressions.py:1126: in as_sql subquery_sql, sql_params … -
What is the proper way to pass a JS object as a django field value?
Given the following form: from django import forms class MyForm(forms.Form): my_field = forms.CharField() views.py from django.shortcuts import render from myapp.forms import MyForm def index(request): form = MyForm() if request.method == 'POST': form = MyForm(request.POST) return render(request, 'index.html', {'form': form}) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post"> {% csrf_token %} {{ form }} <button type="submit">Submit</button> </form> </body> </html> I don't mean the field to be a character field, it's just for the sake of the example. What would be the proper and safe way to pass a JS object as the field value? This would be one possible way to do it. I'm not sure how safe or proper this is: document.querySelector('#id_my_field').value = JSON.stringify({a: 1, b: 2}) and then parse the resulting string: >>> json.loads(form.cleaned_data['my_field']) {'a': 1, 'b': 2} Yeah, I know I could just create a and b fields and make them numeric or whatever the dtype is but this is not an option in my case because these field values will be set dynamically and how many values are expected cannot be known in advance, so this is the convenient way to pass as many values as needed. -
ERROR `long_description` has syntax errors in markup and would not be rendered on PyPI
ERROR long_description has syntax errors in markup and would not be rendered on PyPI. No content rendered from RST source. WARNING long_description_content_type missing. defaulting to text/x-rst. Checking dist\sdk_passport-0.1.tar.gz: PASSED with warnings WARNING long_description_content_type missing. defaulting to text/x-rst. Checking dist\sdk_passport-1.0.tar.gz: PASSED with warnings WARNING long_description_content_type missing. defaulting to text/x-rst. WARNING long_description missing. i am facing this issue when i am going to upload my own package in Pypi. i have validated README.rst file also. Please give me any solution. my expectation is to find out long_description validation error -
How to get average by month in Django queryset?
I have been trying to get average values per month for the rainfall. There are dates, hours and values (hours don't matter here since average will be of all values per month). class TimeSeries(models.Model): station = models.ForeignKey(Station, on_delete=models.CASCADE) date = models.DateField() hour = models.IntegerField() value = models.FloatField() What i have tried is: delta = relativedelta(months=1) dateStart=TimeSeries.objects.values('date').order_by('date').values_list('date',flat=True).first() dateEnd=TimeSeries.objects.values('date').order_by('date').values_list('date',flat=True).last() for i in range(len(stationNumbers)): while dateStart <= dateEnd: timeSeries = TimeSeries.objects.filter(station__number=stationNumbers[i],date__range=[dateStart,dateStart+delta]).annotate(month=TruncMonth('date')).values('station__number','month').annotate(value=Avg('value')).order_by( 'station__number','month') I have tried making some changes into the query but it doesn't work in any way. Should i be using raw SQL here? and Can someone kindly help? i am new to Django. Thanks in advance. -
What should I do to edit django data?
I created a html page for a user page code that help the user to edit his information that stored in django admin, this code is to change (username, first name, last name, email) but whenever I try to change those 4 fields, it only changes username and email, but first name and last name is not being changed. I tried another html page and it worked, but I can't make this html to work. {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>User Profile</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <!-- Fontawesome CSS --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous"> <!-- Custom CSS --> <link rel="stylesheet" href="{% static 'css/stylee.css' %}"> </head> <body> <div style="backdrop-filter: blur(2px);"> <div class="homeicon"> <a id="homeicon" href="/MainPageAL/"> <img src="{% static 'image/Payment/homeIcon.png' %}" width="50" height="50"> </a> </div> <div class="container"> <form action="" method="POST" > {% csrf_token %} <div class="row"> <div class="imagelog"> <img class="imagelog-1" src="{% static 'image/UserProfilePage/UserProfile.png' %}" alt="Profile Picture"> </div> <div class="saker"> <div class="saker-left"> <div class="col"> <h3 class="title">User Profile</h3> <div class="inputBox"> <label for="username">Username:</label> <input type="text" id="username" name="username" placeholder="Username"> </div> <div class="inputBox"> <label for="first_name">First Name:</label> <input type="text" id="fname" name="fname" placeholder="First Name"> </div> <div class="inputBox"> <label for="last_name">Last Name:</label> … -
Add product to wish list in Djagno
I want to add a product in the wish list with click on the heart and become red when the product in the wishlist and remove when i click again here my views fonctions : @login_required(login_url='login') def favorie(request): if request.method == 'GET': query = request.GET.get('query', '') if query: products = Product.objects.filter(Q(nom__icontains=query) | Q(description__icontains=query)) return redirect(f'/products?query={query}') favories = Favorie.objects.filter(user=request.user) if favories : template = 'favorie.html' else: template = 'favorie_vide.html' return render(request, template , {'favories': favories}) def add_to_favorie(request,id): product = get_object_or_404(Product, id=id) favorie, created = Favorie.objects.get_or_create(user=request.user, product=product) if not created: favorie.delete() return redirect('detail', id=id) def remove_from_favorie(request, id): product = get_object_or_404(Product, id=id) favorite = Favorie.objects.filter(user=request.user, product=product).first() if favorite: favorite.delete() return redirect('product_detail', id=id) and here the template where i wanna to click : i try this make it bouton but nothing change -
Django Daphne - Secure websocket connection fails
I have setup my Django server to run on https mode and the API calls are also working. I have also configured Daphne which is starting without any problems. However, when I try to open a secure websocket connection using wss, it fails. It would be great if I can get any help on this. Thanks. docker-compose.yml services: api: platform: linux/amd64 container_name: api build: context: . dockerfile: Dockerfile.dev command: 'sh -c "./manage.py migrate && python manage.py runsslserver 0.0.0.0:8080"' restart: always networks: - default volumes: - ./:/app - $HOME/.aws:/root/.aws:ro - /var/run/docker.sock:/var/run/docker.sock - type: bind source: ./docker/cpuinfo_with_fake_speed.txt target: /proc/cpuinfo ports: - 8080:8080 env_file: - ./.env depends_on: - db daphne: platform: linux/amd64 container_name: daphne build: context: . dockerfile: Dockerfile.dev command: 'sh -c "daphne --ws-protocol [ws, wss] -v 1 -e ssl:8000:privateKey=key.pem:certKey=cert.pem apps.asgi:application"' restart: always working_dir: /app networks: - default volumes: - ./:/app - /var/run/docker.sock:/var/run/docker.sock ports: - 8000:8000 asgi.py django_asgi_app = get_asgi_application() from channels.routing import ProtocolTypeRouter, URLRouter application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AuthMiddlewareStack(URLRouter([path('ws/notifications/', NotificationConsumer.as_asgi())])), } ) I can see that Daphne service is starting up fine daphne | 2023-04-28 05:39:32,845 INFO Starting server at ssl:8000:privateKey=key.pem:certKey=cert.pem daphne | 2023-04-28 05:39:32,847 INFO HTTP/2 support enabled daphne | 2023-04-28 05:39:32,847 INFO Configuring endpoint ssl:8000:privateKey=key.pem:certKey=cert.pem daphne | … -
How to allow users to attach multiple images to a Django post using a ModelForm and formset?
I'm building a Django app that allows users to create posts and attach images to those posts. Each user can create multiple posts, and each post can have multiple images. I'm using a ModelForm to handle the creation of posts, but I'm having trouble figuring out how to handle the creation of the images associated with each post. Here's my current code: models.py class Post(models.Model): title = models.CharField(max_length=200) body = models.TextField() class Image(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) image = models.ImageField(upload_to='post_images/') forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title', 'body'] views.py def create_post(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm() return render(request, 'create_post.html', {'form': form}) What's the best way to modify my code to allow users to attach multiple images to their posts when they create them? How can I modify the PostForm to handle this, and how should I modify the create_post view to save the images along with the post? Any help is greatly appreciated! -
Candy translate to translate the data returned from controllers.py to javascript?
def mymethod(request): return_obj = {} if request.method == 'POST': info = request.POST try: ts_vals, coordinates, name = somefunction(params) return_obj["values"] = ts_vals return_obj["msg"] = candy.translated(request, "all_msg") # all_msg is from the excel return_obj["name"] = name return_obj["success"] = "success" except Exception as e: return_obj["error"] = candy.translated(request, "all_Error") return JsonResponse(return_obj) I tried the above process. The returned JSON is parsed in my javascript code and sent back to the interface from javascript code. How do we handle this situation with Candy Translation? -
When using group by count in a subquery using python django, an error occurs
I am using django 2.2.7, python3.7.9. class FuneralHall(models.Model): hall_name = models.CharField(max_length=100, null=False) flower_vender = models.ForeignKey('bugo.FlowerVender', default=None, null=True, blank=True, on_delete=models.SET_NULL) sales_partner = models.ForeignKey('main.SalesPartner', default=None, blank=True, null=True, on_delete=models.SET_NULL) class FlowerOrder(models.Model): STATUS_CHOICE = ( ('init', '결제준비'), ('ready', '입금대기'), ('paid', '입금완료'), ('confirm', '주문확인'), ('sent', '배송출발'), ('complete', '배송완료'), ('cancel', '배송취소'), ('refund', '환불'), ) funeral = models.ForeignKey(Funeral, null=True, blank=True, on_delete=models.SET_NULL) funeral_hall = models.ForeignKey(FuneralHall, null=True, blank=True, on_delete=models.SET_NULL) funeral_room = models.ForeignKey(FuneralRoom, null=True, blank=True, on_delete=models.SET_NULL) flower_product = models.ForeignKey(FlowerProduct, null=True, blank=True, on_delete=models.SET_NULL) flower_vender = models.ForeignKey(FlowerVender, null=True, blank=True, on_delete=models.SET_NULL) sales_partner = models.ForeignKey(SalesPartner, null=True, blank=True, default=None, on_delete=models.SET_NULL) order_status = models.CharField(max_length=10, null=False, choices=STATUS_CHOICE, default='init') flower_order_count = FlowerOrder.objects.filter(funeral_hall_id=OuterRef('id')).annotate(flower_order_count=Func('funeral_hall_id', function='Count')).values('flower_order_count') hall_list = FuneralHall.objects.annotate(flower_count=Subquery(flower_order_count)) This code works fine. However, if I add a filter condition to the subquery, an error occurs. flower_order_count = FlowerOrder.objects.filter(funeral_hall_id=OuterRef('id'), order_status='complete').annotate(flower_order_count=Func('funeral_hall_id', function='Count')).values('flower_order_count') hall_list = FuneralHall.objects.annotate(flower_count=Subquery(flower_order_count)) The error is 'Expression contains mixed types. You must set output_field.' occurs, but output_field doesn't seem to matter. When using group by count in a subquery, I shouldn't add a condition to the filter. Is there a way to add it? I've tried adding output_field to the subquery, and I've tried meeting different conditions. All failed to work. -
Python Django Framework Error: Could Not Find 'My Tasks' in the h1 tag
I am new to coding in Django. I am creating a Django App called Tasks. My code within each of the following files will be included. I keep getting the error that 'Could not find 'My Tasks' in h1 tag'...Could someone please explain to me what I am doing wrong here? admin .py from django.contrib import admin from tasks.models import Task # Register your models here. @admin.register(Task) class Task(admin.ModelAdmin): list_display = ( "name", "start_date", "due_date", "is_completed", "project", "assignee", ) Apps.py from django.apps import AppConfig class TasksConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "tasks" Forms.py from django import forms from tasks.models import Task class TaskForm(forms.ModelForm): class Meta: model = Task fields = [ "name", "start_date", "due_date", "project", "assignee", ] Models.py from django.db import models from django.conf import settings from projects.models import Project class Task(models.Model): name = models.CharField(max_length=200, default="New Task") start_date = models.DateTimeField() due_date = models.DateTimeField() is_completed = models.BooleanField(default=False) project = models.ForeignKey( Project, related_name="tasks", on_delete=models.CASCADE, ) assignee = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="tasks", on_delete=models.CASCADE, null=True, ) Urls.py from tasks.views import create_task, show_my_tasks from django.urls import path urlpatterns = [ path("create/", create_task, name="create_task"), path("mine/", show_my_tasks, name="show_my_tasks"), ] Views.py from django.shortcuts import render, redirect from tasks.forms import TaskForm from projects.views import list_projects from django.contrib.auth.decorators import login_required from … -
integrating fusionauth and django-rest-framework
I am trying to integrate FusionAuth and Django-Rest-Framework (with a React frontend), and am getting very confused. I have some code that kind of works. It uses the "authorization code grant". The React frontend redirects to the FusionAuth login page which once submitted redirects back to the frontend with an authorization_code as a URL Parameter. The frontend passes that code to the Django backend which exchanges it for an access_token. That access_token is used to get some user information from FusionAuth including a unique id with which to create a local Django User (if one doesn't already exist). It then generates a local token and passes that to the frontend to use for authentication in future requests. Here is some pseudo-code: from fusionauth.fusionauth_client import FusionAuthClient client = FusionAuthClient(FA_API_KEY, FA_URL) def authenticate(request): authorization_code = request.data["code"] fa_token_response = client.exchange_o_auth_code_for_access_token() fa_user_response = client.retrieve_user(user_id=fa_token_response["userId"]) user, created = UserModel.objects.get_or_create( fa_id=fa_token_response["userId"], defaults={ "username": fa_user_response["username"], "email": fa_user_response["email"], }, ) token = generate_token(user) # THIS IS PROBABLY WRONG return Response( { "token": token, "user_id": user.id, } status=status.HTTP_200_OK, ) As you can see, I generate my own token (I happen to be using knox, but that's not important). But I want to just use the same access_token provided by … -
Getting the value of Foreign key values in Django
I just want to get the clientType.name through an ID of foreign key from Clients table and pass it to jsonResponse , I have tried but it doesn't work below I tried select_related but it doesn't work it says AttributeError: 'str' object has no attribute '_meta' def patientdetails(request): patient_id = request.POST.get('patient') context = { 'company' : Clients.objects.filter(id=patient_id).select_related() } qs_json = serializers.serialize('json', context) return JsonResponse({'data': qs_json}) models.py class ClientType(models.Model): name = models.CharField(max_length=128, blank=True, null=True) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True) updated_at = models.DateTimeField(blank=True, null=True, auto_now=True) class Meta: managed = True db_table = 'client_type' class Clients(models.Model): client_type = models.ForeignKey(ClientType, models.DO_NOTHING) first_name = models.CharField(max_length=128, blank=True, null=True) middle_name = models.CharField(max_length=128, blank=True, null=True) last_name = models.CharField(max_length=128, blank=True, null=True) birthdate = models.DateField(blank=True, null=True) sex = models.CharField(max_length=128, blank=True, null=True) address = models.CharField(max_length=128, blank=True, null=True) occupation = models.CharField(max_length=128, blank=True, null=True) class Meta: managed = True db_table = 'clients' Result data in javascript }).done(function(data){ var resultdata = JSON.parse(data.data); }); -
I get the error "detail": "Method \"GET\" not allowed." when trying to make an action
Not really sure why this is happening. I want to send a leaderboard with some data. I already made it work as part of my view/ but i wanted to implement it in an action. Yet when I do it, I get this error. This is my code in my view file @action (methods="GET", detail=False, serializer_class=LeaderboardSerializer, permission_classes=[AllowAny]) def Leaderboard(self, request): return Response({ "results": str(request.results) },status=status.HTTP_200_OK) Not working :( -
What is best practice for storage of AWS credentials within a django application?
I'm new to using AWS Services and Django together and I'm having trouble finding information around best practices for storing your aws creds for Django to access? I have a basic django application that's connected to an S3 bucket, so I need to be able to use boto to invoke the connection to the bucket. But I'm not sure how to go about storing the aws credentials I would need to pipe into my boto functions to use any of the services. I have read in a few places of people putting their aws credentials into the settings.py file within their django project, but this doesn't really feel secure to me. I also looked into AWS Secrets Manager, but it looks to me as though it's more suited for keys related to other services. Could anyone perhaps explain what my other options are, or why storing them in settings.py is perhaps a safe option? Really not certain on the best way to go about this one. -
Change value in form with readonly_fields field when creating an object
class PostAdmin(admin.ModelAdmin): form = PostFormAdmin readonly_fields = ['author'] class PostFormAdmin(PostValidationMixin, forms.ModelForm): class Meta: model = Post fields = '__all__' author = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, null=False, default=1) Since the field is readonly_fields, it is always default Before I submit the form, I need to substitute request.user there I want to understand at what stage it is possible to assign request.user so that the user sees himself in the form and not the default user -
Not getting fields to post data in Django REST framework
Perfoming a crud api rest in django rest framwork, i created class based views. But when i run my app in browse, I am not getting forms to post data. When i scroll down getting media type and content option not my model fields. There is my model: from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from djongo import models as djongo_models from bson.objectid import ObjectId from django.contrib.auth.hashers import make_password, check_password from django.core.validators import RegexValidator from api.enums import Status, UserRole class UserManager(BaseUserManager): def create_user(self, username, email, password=None, **extra_fields): if not email: raise ValueError('The email is required') email = self.normalize_email(email) user = self.model(username=username, email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('role', UserRole.ADMIN) return self.create_user(username, email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): mongo_id = djongo_models.ObjectIdField() def save(self, *args, **kwargs): if not self.mongo_id: self.mongo_id = ObjectId() super().save(*args, **kwargs) username = models.CharField(max_length=20, blank=False) name = models.CharField(max_length=20, blank=False, default='') lastname = models.CharField(max_length=20, blank=False, default='') password = models.CharField(max_length=128, blank=False,) def set_password(self, raw_password): self.password = make_password(raw_password) def check_password(self, raw_password): return check_password(raw_password, self.password) phone_number = RegexValidator(regex=r'^\+\d{1,3}\s\d{6, 14}$', message='Insert a valid phone number and it\'s country code') email = models.EmailField(unique=True, blank=False) birth_date = models.DateField(null=True) role = models.CharField(max_length=10, choices=[(role, role.value) …