Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django serializers unable to serialize a queryset into JSON
Trying simple Django serializer. I use a queryset, with specific values. Then I pass the queryset or the queryset.values() to the serializer. Why doe it give 500 error? @csrf_protect def geoLookup(request, **kwargs): country = kwargs.get('Country') city = kwargs.get('Place') queryset = GeoNames_location.objects.filter(geoCountry_code=country, feature_class='P', geoAsciiName__istartswith=city).values_list("geoAsciiName", "geoLongitude", "geoLatitude", "geo_timezone", "geo_population", "geoCountry_code").order_by('-geo_population')[:5] data = serializers.serialize("json", queryset.values()) # tried queryset and queryset.values() parsed_data = json.loads(data) pretty_json = json.dumps(parsed_data, indent=4) return JsonResponse(json.loads(pretty_json), safe=False) [24/Jul/2024 06:07:52] "GET /edit_chart_form HTTP/1.1" 200 18929 Internal Server Error: /geolookup/US/p Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\decorators.py", line 188, in _view_wrapper result = _process_exception(request, e) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\decorators.py", line 186, in _view_wrapper response = view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "G:\My Drive\myProgram\runtime\devui\ui\views.py", line 81, in geoLookup data = serializers.serialize("json", queryset.values()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\serializers\__init__.py", line 134, in serialize s.serialize(queryset, **options) File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\serializers\base.py", line 113, in serialize concrete_model = obj._meta.concrete_model ^^^^^^^^^ AttributeError: 'dict' object has no attribute '_meta' [24/Jul/2024 06:07:55] "GET /geolookup/US/p HTTP/1.1" 500 105779 -
Django REST framework serializer.is_valid() saves files to MEDIA_ROOT although .is_valid() is False
I have a project which supports file uploads via Django forms and also Django REST framework, these files are used are stored in a model 'Document'. The issue is that when a file that fails validation is uploaded via the REST framework the file is still saved to its 'upload_to' parameter (MEDIA_ROOT) (No 'Document' model instance is created as expected), this doesn't happen when uploading the same file via Django forms. Some testing seems to point to "serializer.is_valid()" being the thing that saves the file dispite "serializer.is_valid()" is false in the case i am refering to. My ideal outcome is that when a unacceptable file is uploaded via REST framework, that file is not present in the MEDIA_ROOT folder. Please leave a answer/comment if you have any advice. My code is below. Models.py: from django.db import models from apps.common.models import BaseModel from datetime import datetime import os from django.core.exceptions import ValidationError def file_storage_handler() -> str: """This function provides a file path to a Document model's FileField based on the current date. If the file path doesn't exist it creates it.""" currentDate = datetime.now().date() path = f"uploaded_documents/{currentDate.year}/{currentDate.month}/{currentDate.day}/" if not os.path.exists("media/"+path): os.makedirs("media/"+path) return path def validate_file(file): # I dont believe that the … -
OAuth2 where to store client id and secret when Application is created on server startup
I am using django-oauth-toolkit for authorization of my Django app, and for development, each dev deploys their server on Kubernetes with a MySQL database also deployed on the side as a StatefulSet. Many times me (or other devs who develop the application) have to remove their database and reinstall their k8s deployment. Usually (in a non k8s deployment and what is there in the quickstart guide), you would deploy your app, register the new client application through the UI provided by the django-oauth-toolkit, and then you get a one time generated client secret that you have to copy immediately otherwise it will be gone and you have to recreate the client. But this is inconvenient as on every new fresh install we have to keep doing this, and update the client_secret in the apps that use the authorization server with the new value. So I found a way to auto-register an OAuth2 client application as follows on post-migrate (this is a snippet, something like this) from oauth2_provider.models import Application @receiver(post_migrate) def initialize_client_applications(): Application.objects.create( client_type="confidential", authorization_grant_type="password", name="client_name", client_id='myComplexClientIdString", client_secret='myComplexClientSecretString", user=User.objects.get(name="someuser") ) But, as you can see, the client_secret is hard coded and therefore quite insecure. How can I do this using … -
Django 5.0: Configuring local development and production environments?
This question, in various forms, has been asked a few times. However, most answers on this topic are ten or more years old. The Two Scoops books I have are for Django 3.x. I think it might be useful to, perhaps, have updated answers relevant to Django 5.0 and hosting options available today. Here's one of the many older discussions I have reviewed: Django: How to manage development and production settings? I am particularly interested in the following scenario: Local development on Windows using PyCharm Using PostgreSQL from the start (rather than SQLite) Production deployment to Heroku, Render or PythonAnywhere I have my preferences when it comes to such things as the directory structure for the local environment. The standard layout for a Django-created application named "mypicturesite" is: mypicturesite/ code/ mypicturesite/ __init__.py settings.py urls.py wsgi.py <directories for other apps in the site> manage.py db.sqlite3 venv/ <various work directories>/ With this you end-up with paths that look like this: z:/mypicturesite/code/mypicturesite My approach looks like this: mypicturesite/ code/ # The entire codebase, including virtual environment site/ # This now makes sense; this contains the site code __config/ # These are the site configuration scripts __init__.py settings.py urls.py wsgi.py <directories for other apps … -
Multi Tenant Docker App with a Authentication Server and APIs
Hi I am working on a web project and my current stack is as follows. I have nginx for http server, nextjs for frontend and django as backend. Simple stuff. Where you can register a company and each company can have multiple users. As the project grew I wanted to instead of having a kitchen sink sort of backend app where there is one DB and all the users and companies are in it. I want to separate them but I am also going to dockerize so each tenant will have a docker app and a docker postgres for that docker app. I am also going to create another djano app just to register the tenants so that I can book keep. So it will look like below --NGINX --domain1.app --domain1.db --domain2.app --domain2.db --domain-registeration-app --frontend-nextjs-app domain-registeration-app app book keeps all the tenants and forks new docker instances for a new tenant and maybe handles payments for each tenant. Now comes the issue. This would work if a user is only in one tenant and will likely remember the subdomain for the tenant and can go to that tenants app by typing tenant1.myapp.com in urk and nginx would route that to … -
How to "fix" user input on the django admin page datetime input
I have a model Itineraries that has a tabularInline model ItineraryDetails that has destination, arrival, and departure times. I want to allow users to input 09302025 and 700 for each datetime field but I can't seem to get it to work. Django admin looks for valid datetime objects before saving and since these are not valid, they can't be saved. I've tried save_model and save_related, but they won't accept the invalid datetime format -
Difference interpretating env variable in django and celery
I had issue with env variable with backslash. I had: NETWORK=\\TI\folder But in Django and Celery this variable will be interpreted in different ways: Django: \\TI\folder Celery: \TIfolder Why I has difference ? Celery and Django has same env file and environment. Python 3.8 -
Queryset annotated with Count is counting wrong occurrences
I want to count the number of times a name is present on a queryset: items = items.values("name").annotate(count=Count("name")).order_by("-count") This should return a query set like this: [ { "name": "Item 1", "count": 1 }, { "name": "Item 2", "count": 4 }, { "name": "Item 3", "count": 12 }, ] This is returning some wrong counts, for example, items that should have 1 occurrence is counting 17, and items that should have 3 occurrences is counting 51, for some reason is multiplying it by 17. How can I solve this? -
VoIP push notifications with django to iOS
Currently, I am using fcm-django to send fcm notifications to both android and iOS and for iOS, i set header apns-push-type: voip. Is it enough for a notification to be treated as voip push notification. On client side, i am using react-native-voip-push-notification, but in the listeners, i am not receiving any notification object. So, How to properly send a voip push from django and handle it on react native side. -
Retrieving image with javascript to display Django
I am trying to retrieve an image via Javascript function that calls a function from my views that has the image. I need help with populating the image: Views: def view_company_logo(request): print('GETTING LOGO') client = Client.objects.get(user=request.user) logo ='' try: logo= client.customer.first().logo.logo print('GOT LOGO') return JsonResponse({'logo':logo, 'media_url':settings.MEDIA_URL}, safe=False) except Exception as e: print(e) return JsonResponse({'logo':logo}, safe=False) HTML File: I am using the image id "company_logo" here: In the bottom, I am using Javascript: <script type="text/javascript"> function get_company_logo() { $.ajax({ url: '/get/company_logo/', method: 'GET', success: function (data) { console.log(data['logo']) display_image(data['logo']) } }) } function display_image(image){ document.getElementById("company_logo").src = image.url; } get_company_logo(); </script> Called by URL: url(r"^get/company_logo/$", views.view_company_logo), How do I get the image to display? -
page-break not working on headings ( python, weasyprint )
I want to create a pdf out of html content. I use beautifulsoup to get html string and then create PDF using weasyprint and python out of it. I have issue when i want to show headings ( specifically h3 ) on a new page ( though this doesn't work for any of the h tags ). Now, I have this code in html {% block report %} <style> h3 { page-break-before:always; } </style> <div class="container" style="padding-top:45px"> <div class="row"> <div class="col-12"> <h1 id="h1-title" class="mb-5">{{report.title|safe}}</h1> <div class="control-head"> <h3 id="1.-first-section">1. First Section</h3> <hr> <p>{{obj.some_content_one|safe}}</p> </div> <div class="control-head"> <h3 id="2.-second-section">2. Second Section</h3> <hr> <p>{{obj.some_content_two|safe}}</p> </div> <div class="control-head"> <h3 id="3.-third-section">3. Third Section</h3> <hr> <p>{{obj.some_content_three|safe}}</p> </div> <div class="control-head"> <h3 id="4.-fourth-section">4. Fourth Section</h3> <hr> {{obj.some_content_four|safe}} </div> </div> </div> </div> {% endblock report %} And when i use page-break-after in h3 tags, weasyprint only renders content until this first h3 including the h3.string... If i use page-break-before: always; then weasyprint renders first "control-head" and {{obj.some_content_one|safe}} and stops rendering second at the end of the page where second h3 is ( it basically renders second control-head h3.string and content from {{obj.some_content_two|safe}} until it fills the page and then stops rendering pdf any further).. I tried using page-break-after/before on … -
test if any object refer to by a base model has a value specified in django orm
Well consider two models: class School(models.Model): name = models.TextField(default="hello world") class Student(models.Model): key = models.TextField(default="somedata") a = models.ForeignKey(Vendor) So a many to one relationship from School to Student How would I get (from School's perspective) all School which have a Student that set "key" to the required value? Especially in the already existing query: School.objects.filter(Q(name="hello world") | Q(queryshould_here)) I've tried A.objects.filter(Q(name="hello world") | Q(student__key="test")) However that (obviously) fails with: django.core.exceptions.FieldError: Unsupported lookup 'v' for ManyToOneRel or join on the field not permitted. -
Large GET Request to DRF causes 504 Gateawy Time-out
I have a database with about 3 million records, and I want to retrieve these records to be displayed by a Django web app. However, attempting to pass these via Model.objects.all() passed by templating a javascript variable causes my Apache server to crash. So, I created a Django REST Framework endpoint which returns these records. But, this returns a 504 Gateway Timeout when I make the GET request. How can I retrieve all these records to display in my Django app? I would like to avoid paging or filtering. -
Error while using "pyttsx3" with "react-speech-recognition"
Error in text-to-speech: run loop already started Backend Code from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status import os import google.generativeai as genai from dotenv import load_dotenv import pyttsx3 from langchain_google_genai import GoogleGenerativeAIEmbeddings from langchain_community.vectorstores import FAISS from langchain_google_genai import ChatGoogleGenerativeAI from langchain.prompts import PromptTemplate from langchain.chains.question_answering import load_qa_chain # Load environment variables load_dotenv() genai.configure(api_key=os.getenv("GOOGLE_API_KEY")) # Initialize TTS Engine engine = pyttsx3.init() voices = engine.getProperty('voices') engine.setProperty('voice', voices[0].id) class VoiceBotView(APIView): def post(self, request): user_message = request.data.get('query') VoiceBotFunction.speak("Searching") try: response_text = VoiceBotFunction.get_voice_response(user_message) VoiceBotFunction.speak(response_text) print(response_text) return Response({'query': user_message, 'response': response_text}) except Exception as e: print(f"Exception occurred: {e}") return Response({'error': 'Internal server error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) class VoiceBotFunction: def speak(text, rate=120): try: engine.setProperty('rate', rate) engine.say(text) engine.runAndWait() # run and wait method, it processes the voice commands. engine.stop() if engine._inLoop: engine.endLoop() except Exception as e: print(f"Error in text-to-speech: {e}") def get_conversational_chain(): prompt_template = """ Answer the question as detailed as possible from the provided context, make sure to provide all the details, if the answer is not in provided context just say, "Answer is not available in the Database", don't provide the wrong answer\n\n Context:\n {context}?\n Question: \n{question}\n Answer: """ model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3) prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"]) … -
graphql query using django for xml data
How can we implement GraphQL query that allows querying values from any selected set of elements from the below xml file using django? <encspot> <file type="audio"> <Name>some filename.mp3</Name> <Encoder>Gogo (after 3.0)</Encoder> <Bitrate>131</Bitrate> <Response> <data> <text>sample data</text> <frequency>200Hz</frequency> </data> </Response> </file> </encspot> -
Template Rendering Issue
I have done Url shortner using django in Python. I am unable to render the template and getting the error as shown. Please help me with this. error picture I have tried some methods and tried ChatGPT, somehow I didn't meet with the answer I was searching for. Anyone help me to sort this out.. -
How to Add Cron Jobs from Multiple Django Applications to Crontab Without Conflict?
I have two Django applications that I'm running on Amazon Linux using Gunicorn. Each Django application has its own cron jobs defined in the settings.py file using django_crontab. However, I'm facing issues when trying to add cron jobs from both applications to the crontab. Here is the structure of my applications: Application 1 /path/to/app1/ ├── manage.py ├── app1/ │ ├── settings.py │ └── ... Application 2 /path/to/app2/ ├── manage.py ├── app2/ │ ├── settings.py │ └── ... In settings.py of each application, I have defined cron jobs like this: # app1/settings.py CRONJOBS = [ ('*/10 * * * *', 'app1.cron.my_scheduled_task'), ] # app2/settings.py CRONJOBS = [ ('*/15 * * * *', 'app2.cron.another_scheduled_task'), ] When I try to add the cron jobs for each application using the following commands: cd /path/to/app1 source /path/to/venv/bin/activate python manage.py crontab add cd /path/to/app2 source /path/to/venv/bin/activate python manage.py crontab add When i do the python manage.py crontab add for the second application, i get an error RuntimeError: No job with hash 65f37180992aa5435pidg617281f3e6 found. It seems the crontab is out of sync with your settings.CRONJOBS. Run "python manage.py crontab add" again to resolve this issue! This hash ID corresponds to a job from the first application. How … -
forms.ModelMultipleChoiceField with widget=FilteredSelectMultiple not working on custom new Django Admin
I am trying to show the forms.ModelMultipleChoiceField on custom new admin form page but it doesn't seem to show it the way it is showing on the Django page that was already made e.g. model product django admin page. Mine forms.ModelMultipleChoiceField is looking like this: Shows how my forms.ModelMultipleChoiceField looks like When it should look like this: Shows how forms.ModelMultipleChoiceField should look like forms.py: from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from django.contrib.admin.widgets import FilteredSelectMultiple from home.models import Collection, Tag, Product class ProductAssignForm(forms.Form): from_name = forms.CharField(required=True, max_length=255, label='From Name') to_name = forms.CharField(required=True, max_length=255, label='To Name') assign_collections_name = forms.ModelMultipleChoiceField( queryset=Collection.objects.all(), required=False, widget=FilteredSelectMultiple( verbose_name='Collections', is_stacked=False ), label='Assign Collection Name' ) tags = forms.ModelMultipleChoiceField( queryset=Tag.objects.all(), required=False, widget=FilteredSelectMultiple( verbose_name='Tags', is_stacked=False ), label='Tags' ) class Meta: model = Product fields = ['collections', 'tags'] # Include the tags field in the fields list def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_method = 'POST' self.helper.add_input(Submit('submit', 'Assign Products')) partial code form admin.py: @admin.register(Product) class ProductAdmin(admin.ModelAdmin): form = ProductAdminForm list_display = ('name', 'quantity', 'price', 'first_collection') exclude = ('user', 'updated',) def save_model(self, request, obj, form, change): if not obj.user: obj.user = request.user obj.save() def first_collection(self, obj): first_collection = obj.collections.first() return first_collection.name if first_collection … -
Configuring SSH port forwarding for Django app on VPS: Browser access issues
I am running a Django application on my laptop at port 8000. The app works locally and I want to make it accessible to others over the internet via SSH remote port forwarding to a VPS. I've connected to my VPS using the following command: ssh -R 9090:localhost:8000 remote_user@remote_host I tried to confirm that the port forwarding works: netstat -tunl | grep 9090 tcp 0 0 0.0.0.0:9090 0.0.0.0:* LISTEN tcp6 0 0 :::9090 :::* LISTEN I can use telnet on the VPS to connect to port 9090 and issue a GET request to retrieve the home page. This part works as expected. However, when I try to open the application in a browser using http://remote_host:9090, it does not load and I get a 503 error. I have already added a rule to the INPUT chain of iptables on my VPS to allow incoming connections to port 9090: sudo iptables -A INPUT -p tcp --dport 9090 -j ACCEPT I've temporarily uninstalled iptables on my laptop. My questions are: Am I missing something in my setup that prevents the application from being accessible over the internet? Was I wrong to assume that this method would make my app accessible over the internet … -
Nested query in Django, need to compare the processing time
time_limit = timezone.now() - timedelta(hours=30) time_limit_str = time_limit.strftime('%Y-%m-%d %H:%M:%S') in_review_records = RequestedData.objects.filter( Q(status='In Review') & ( Q(additional_details__isnull=True) | Q(additional_details__processing_details__isnull=True) | ( Q(additional_details__processing_details__has_key=account_name) & Q(additional_details__processing_details__account_name__lte=time_limit_str) ) | ( Q(additional_details__processing_details__isnull=False) & ~Q(additional_details__processing_details__has_key=account_name) ) ) ).annotate(processing_details=KeyTransform('processing_details', 'additional_details')).annotate(account_name=KeyTransform(account_name, 'processing_details')) ################## account = "abc" here i am trying to get all the records if the additional_details is empty if processing_details in additional_details is empty if processing_details has key account then check the value (which is processing time ) is not in past 30 hours and if processing_details has keys but it is not "abc" we are free to include it i tried so many things but nothing seems to work lastly the format of additional_details which is a json model field is like JSONField(default=dict, null=True, blank=True) "additional_details" : {"processing_details": {"sas": "2024-07-19 11:03:20", "aditi account": "2024-07-20 11:03:20", "irs-account-2": "2024-07-23 11:03:20"}} -
Django OTP Verification Through Email
Registration always goes in successful but then after submitting otp for verification, first error response "error":"authentication failed" and when I try again "error": "error": "OTP or email not found in session.". class UserRegistrationView(APIView): def post(self, request, format=None): serializer = UserRegistrationSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() # Generate and store OTP otp = generate_otp() request.session['otp'] = otp request.session['email'] = user.email request.session['otp_timestamp'] = timezone.now( ).isoformat() # Save as ISO format string # Send OTP to user via email email_subject = 'Your OTP Code' email_message = f'Your OTP code is { otp}. It will expire in 5 minutes.' try: send_mail(email_subject, email_message, settings.EMAIL_HOST_USER, [user.email]) return Response({"message": "Registration successful. Please check your email for the OTP."}, status=status.HTTP_201_CREATED) except Exception as e: return Response({"error": f"Failed to send OTP. Please try again. Error: {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class UserRegistrationSerializer(serializers.ModelSerializer): university = serializers.CharField(write_only=True) gender = serializers.CharField(write_only=True) class Meta: model = User fields = ( "id", "username", "email", "password", "university", "gender", ) extra_kwargs = {"password": {"write_only": True}} def validate_email(self, value): university = self.initial_data.get('university') if university in UNIVERSITY_EMAIL_PATTERNS: pattern = UNIVERSITY_EMAIL_PATTERNS[university] if not re.match(pattern, value): raise serializers.ValidationError(f"""Invalid email address for { university}. Please use a valid student email.""") if User.objects.filter(email=value).exists(): raise serializers.ValidationError( 'A user with this email already exists!') … -
File directory error in python when running python manage.py runserver
I am in the initials stages of starting a django project. Everything is set, I have already installed django, python, virtual env and started myproject project. When I run the command python manage.py runserver I get an error saying no file directory. I have tried any troubleshooting method but the server won't run. -
One common document table vs separate tables for multiple entities: scalability, optimization, and maintainability
I have three tables: inspections, accidents, and claims. Each of these tables has a one-to-many relationship with a documents table, where users can upload documents specific to each record. The process of uploading documents is identical across all three tables. I'm wondering whether to create: A) One common documents table that stores documents for all three entities, with a foreign key referencing the respective table (e.g., inspection_id, accident_id, or claim_id). or B) Separate documents tables for each entity, e.g., inspection_documents, accident_documents, and claim_documents. [enter image description here](https://i.sstatic.net/gw1393oI.png) Which approach is best in terms of: Scalability: Will one approach handle large amounts of data and user traffic more efficiently? Database optimization: Which approach will result in faster query performance and better data retrieval? Maintainability: Which approach will be easier to manage, update, and extend in the long run? Please provide insights and recommendations based on your experience with similar scenarios. here is my models.py class SafetyInspection(models.Model): status = models.CharField(max_length=30, choices=status_choices, default='Closed') #mandatory driver = models.ForeignKey( TeamMember, on_delete=models.CASCADE, related_name='safety_inspections', ) vehicle = models.ForeignKey( Equipment, on_delete=models.CASCADE, related_name='vehicle_safety_inspections', null=True, blank=True ) trailer = models.ForeignKey( Equipment, on_delete=models.CASCADE, related_name='trailer_safety_inspections', null=True, blank=True ) date = models.DateField(null=True, blank=True) start_time = models.TimeField(null=True, blank=True) end_time = models.TimeField(null=True, blank=True) level = … -
Django Profile Page Not Displaying Related Worker Information with Djoser
I'm working on a Django application where users can be either normal app users or workers with additional details. I'm using Djoser for user authentication and registration. I'm having trouble with my profile page, which is supposed to display both user and worker information, but it only shows user information. Here's a brief overview of my code: #models.py from django.db import models from django.contrib.auth.models import AbstractUser, PermissionsMixin from django.utils.translation import gettext_lazy as _ from .managers import CustomUserManager class User(AbstractUser, PermissionsMixin): username = None first_name = models.CharField(_('First name'), max_length=100) last_name = models.CharField(_('last name'), max_length=100) email = models.EmailField(_('Email Address'), max_length=254, unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "last_name"] objects = CustomUserManager() class Meta: verbose_name = _("User") verbose_name_plural = _("Users") def __str__(self): return self.email @property def get_full_name(self): return f"{self.first_name} {self.last_name}" class Worker(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) categories = models.ManyToManyField('Category', related_name='workers') rating = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True) numReviews = models.IntegerField(null=True, blank=True, default=0) pricePerHour = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True) gender_choices = [ ('M', 'Male'), ('F', 'Female'), ] gender = models.CharField(max_length=1, choices=gender_choices) profile_photo = models.ImageField(upload_to='profile_photos/', null=True, blank=True) num_tel = models.CharField(max_length=20) small_description = models.TextField(null=True, blank=True) description = models.TextField(null=True, blank=True) _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return f"{self.user.email} - … -
Using Django REST Framework to make sure cross-platform
I want to create cross platform site in Django, which can work with other clients, like my own c++ apps. Imagine someone creating social media in which you can post videos and articles. What I want is to be able to get all the articles and videos in my c++ app, also be able to do the same in my web browser. Here's some questions: Can I use REST Framework only on authentication and app requests, and for the browser requests simply render HTML file using Django's built-in render() func? Logic for that is when you are in browser you are going on URLs like my-site.com/, my-site.com/about-us, etc., but when you are in c++ app you are going like my-site.com/api/v1, my-site.com/api/v1/about-us. Will it work like that? If it will work like that, how to make you authorize both in browser and in app using REST Framework, but for other parts of the site except for authorization use separate functionality (as I said earlier)? Any help appreciated.