Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I just couldn't connect Railway volume With my django-Project
Here in settings.py I've added if os.environ.get("MOUNT_MEDIA"): MEDIA_ROOT = "/app/media" print("Using Railway mounted volume for MEDIA_ROOT") else: MEDIA_ROOT = BASE_DIR / "media" print("Using local folder for MEDIA_ROOT") MEDIA_URL = "/media/" in urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) else: # allow Django to serve media in production (NOT recommended, but works) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Model is image = models.ImageField(upload_to="products", default="product.jpg") description = models.TextField(blank=True, null=True) Whatever I do. I can't get to view those images..! Here is the edit product view where I am being able to view the photo @login_required def edit_product(request, pk): product = get_object_or_404(Product, pk=pk, user=request.user) if request.method == "GET": # print("GET request for product data") # Return product data as JSON for prefill return JsonResponse({ "id": product.id, "name": product.name, "price": float(product.price), "discounted_price": float(product.discounted_price) if product.discounted_price else "", "stock_quantity": product.stock_quantity, "description": product.description, "status": product.status, "image": product.image.url if product.image and hasattr(product.image, "url") else "" }) elif request.method == "POST": # Update product with submitted form data product.name = request.POST.get("name") product.price = request.POST.get("price") product.discounted_price = request.POST.get("discounted_price") or None product.stock_quantity = request.POST.get("stock_quantity") product.description = request.POST.get("description") product.status = request.POST.get("status") == "True" if "image" in request.FILES: product.image = request.FILES["image"] product.save() return JsonResponse({"success": True, "message": … -
Django Admin is showing a different model
I understand there might be a design issue here but I'm a little confused. I have two very similar models => Submission and Partial Submission. There are two other models linked to them, CheckedSubmission and CheckedPartialSubmission. The way they are displayed and checked is pretty similar, it's just that I need a separate submission model for user convenience. The problem is not with the models, but with how Django admin chooses to display them -- the submission model for some reason displays partial submissions, and the partial submission model is showing submissions. The fields and related names might be the issue too, the partial check model has this: submission = models.ForeignKey(PartialLRSubmission, on_delete=models.CASCADE, related_name="partial_checks") key_source = models.ForeignKey(AnswerKey, on_delete=models.CASCADE, related_name="partial_checks", null=True) And the full check model has this: submission = models.ForeignKey(LRSubmission, on_delete=models.CASCADE, related_name="checks") key_source = models.ForeignKey(AnswerKey, on_delete=models.CASCADE, related_name="checks", blank=True, null=True) Here's a PasteBin with models, inlines and Admins. -
How to set table column width to django admin list_display?
I want column foo (TextField 2500 chars) to have a width of 30% in admin view. Yet whatever I try, the columns widths remain equal (50% / 50%). td.foo {width: 30%;} has no effect at all. admin.py: class FooAdmin(ModelAdmin): list_display = ['foo', 'bar'] # foo column width should be 30% class Media: css = {'all': ('css/custom.css', )} custom.css: table { table-layout: fixed; } td.field-foo { width: 30%; } Working minimal html example of desired result: <!DOCTYPE html> <html> <head> <style> table { table-layout: fixed; } td.foo { width: 30%; } </style> </head> <body> <table border="1"> <tr> <td class="foo">30% width</td> <td>Cell 2</td> <td>Cell 3</td> </tr> </table> </body> </html> -
Viviene Sandhu: Experienced Mediator & Litigator
Viviene Sandhu is a highly seasoned Advocate and Co-Managing Partner at Clifford Law LLP, listed in the Law Guide Singapore directory for her comprehensive practice. Admitted to the Singapore Bar in 1998, she possesses over 25 years of experience in dispute resolution. Viviene's core practice areas include contentious Family Law, Employment Law, and Personal Injury & Negligence Claims, as well as Wills & Probate. Beyond litigation, she is a distinguished Principal Mediator at the Singapore Mediation Centre and an Accredited Mediator (Level 4) with the Singapore International Mediation Institute (SIMI). Viviene Sandhu is committed to providing every client with clear, strategic, and compassionate legal counsel to navigate complex legal processes. -
How to see changes in django admin base.css
I want to change some css in static/admin/css/base.css After some attempts I now fail to understand the static-file concept at all. As a matter of fact I can delete the whole static directory without any effect/error (browser CTRL + F5). # settings.py STATIC_URL = "static/" STATIC_ROOT = BASE_DIR.joinpath('static') # urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Long story short; How to change base.css? -
Is it a bad idea to use the builder pattern to construct elasticsearch queries in Python/Django?
So here's the issue. I am maintaining a somewhat large Django app and am tasked with creating a search bar that relies on elastic search data and need to in the near future convert a large number of Django DB queries into Elastic queries. I'm using python's elasticsearch.dsl package version 8.19.2 for this. Assuming the app uses Articles as a model that needs to be represented as Elastic document. Here is my implementation of the builder pattern from elasticsearch.dsl import Document, Text, Keyword class ArticleDocument(Document): id = Integer() title = Text( fields={ 'keyword': Keyword() } ) class Index: name = INDEX_VAR from app import handle_elastic_connection @dataclass class ElasticSearchResults: count: int results: object class ArticleRepository: def __init__(self, client: Elasticsearch): self.client = client def return_results(self, search: Search): return ElasticSearchResults(results=search.execute(), count=search.count()) class ArticleQueryBuilder: def __init__( self ): # handles index refer self.search: Search = ArticleDocument.search() def builder_method1(self, list_of_values:List): if list_of_values: self.search = self.search(Q('terms', key=list_of_values)) def builder_method2(self, single_value:str): if single_value: method2_filter = Q('term', value1=single_value) | Q('term', value2=single_value) self.search = self.search(method2_filter) # .... more builder methods def build(): return self.search # Usage, most likely in view ec = handle_elastic_connection() repo = ArticleRepository(ec) artcile_search = ArticleQueryBuilder.builder_method1().builder_method2.build() results: ElasticSearchResults = repo.return_results(artcile_search) I know the builder pattern gets … -
Django / Serializer - How to pass label attached to choice field in API?
I am trying to get the label attached to the relevant interger for the choice field. Although the API returns the interger, I cannot seem to be able to return the actual label value. This is the current return: [ { "id": 16, "frequency": 0, }, { "id": 15, "frequency": 2, } ] What am I missing? models FREQUENCIES=( (0,'Monthly'), (1,'Weekly'), (2,'Daily'), (3, 'Bi-Weekly'), ) class Model(models.Model): frequency = models.IntegerField(choices=FREQUENCIES, default=0,null=True, blank=True) serializer class ModelSerializer(serializers.ModelSerializer): frequency_label = serializers.ChoiceField( choices=FREQUENCIES, source='frequency', read_only=True ) class Meta: model = Model fields = [ 'frequency', 'frequency_label', ] viewset class ModelViewSet(viewsets.ViewSet): permission_classes = [IsAuthenticated] @swagger_auto_schema( method='get', responses={200: ModelSerializer(many=True)} ) @action(detail=False, methods=['get'], url_path='list-rules') def a(self, request): q = Model.objects.filter(field=some_variable) return Response( ModelSerializer(q, many=True).data, status=status.HTTP_200_OK ) -
optimization django admin panel queries with select_related and prefetch_related
These are my django models (only the FK s are written) class SellerBuyable(TimeStampMixin, GBSoftDeleteModel): seller = models.ForeignKey(Seller,related_name="seller_buyables",on_delete=models.CASCADE, null=True) buyable = models.ForeignKey(Buyable,on_delete=models.CASCADE,null=True,related_name="seller_buyables",related_query_name='seller_buyable') ... class CampaignItem(TimeStampMixin, GBSoftDeleteModel): campaign = models.ForeignKey(Campaign, related_name='items', on_delete=models.CASCADE) item = models.ForeignKey(SellerBuyable, on_delete=models.CASCADE, null=False) ... class Campaign(TimeStampMixin, GBSoftDeleteModel): name = models.CharField() ... (has no FK) And these are my codes in admin panel: class CampaignItemStackedInline(SortableStackedInline): model = CampaignItem extra = 0 .... @admin.register(Campaign) class CampaignAdmin(SortableAdminMixin, admin.ModelAdmin): inlines = [CampaignItemStackedInline] ... A sample campaign had 11 items. When I open it's page, silk showed 84 queries. I have simplified them to 40 queries by writing CampaignItemStackedInline like this: class CampaignItemStackedInline(SortableStackedInline): model = CampaignItem extra = 0 def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.select_related("campaign", "item__seller", "item__buyable") return qs But I still have 3 queries for each "campaign inline item". 1 for Seller table, 1 for buyable and 1 for seller_buyable. I've tried prefetch_related in CampaignAdmin. The last version is this: @admin.register(Campaign) class CampaignAdmin(SortableAdminMixin, admin.ModelAdmin): ... def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.prefetch_related( Prefetch("items", queryset=CampaignItem.objects.select_related("item__seller", "item__buyable")) ) return qs But it only adds 1 prefetch query and turns into 41 queries Hope to send enough info. -
How to mock django timezone.now in a abstract model
I'm unable to mock timezone.now in the model's created field. The test fails due unmocked/current datetime. I tried patch('django.utils.timezone.now') to no avail. # app/models.py from django.utils import timezone class BaseModel(models.Model): created = models.DateTimeField(default=timezone.now, editable=False) class Meta: abstract = True class MyModel(BaseModel): ... # app/tests/test.py from app.models import MyModel from datetime import dateHow to mock django timezone.now in a abstract modeltime from django.utils import timezone def test_(self): dt=datetime(2018, 1, 24, tzinfo=timezone.utc) with patch('app.models.timezone.now', return_value=dt): instance = MyModel.objects.create() assert instance.created == dt -
Using group_by to find sum in Django
I'm working on a website to track music practice and I'm trying to set up a query to show how many minutes you've spent with a certain instrument or song. I modeled this behavior using Khan Academy (to test the SQL): https://www.khanacademy.org/computer-programming/music-tracker/5599297716994048 but can't find a way to do it in Django. The SQL query would look something like this: SELECT song, SUM(duration) AS total_time_practiced FROM logs GROUP BY song ORDER BY total_time_practiced DESC How does this translate to Django? I've tried a few things and the most promising is: Log.objects.distinct().annotate(total_practice_time=Sum("duration")) but it still doesn't work. I've checked the docs and Django doesn't seem to have a GROUP BY method for QuerySets. Any advice? This is from one database, by the way, not using any joins. (apologies for the lack of syntax highlighting on the code snippets; every time I tried to add rich formatting, the webpage crashed) -
Storing WAV recording to disk plays as static
I'm recording voice via jquery then sending it to django view: views.py ... elif voice_value: #get voice voice_value = request.FILES.get('sound_file.wav') #read as bytes file_content_bytes = voice_value.read() #using pydub audio_bytes = file_content_bytes # Replace with your actual audio data audio_segment = AudioSegment( data=audio_bytes, sample_width=2, # Example: 2 bytes per sample (16-bit audio) frame_rate=48000, # Example: 44.1 kHz sample rate channels=1 # Example: Mono audio ) audio_segment.export("output_1.wav", format="wav") data = {'payload':'anything'} return JsonResponse(data,safe=False) It produces the output as a wav file, but it's distorted and just static when played. I should say that the parameters (channels,sample_width,framerate) are the default. What seems to be the problem ? -
Could not translate host name to address
When I run python manage.py migrate I get this error: (venv) mac@MACs-MBP-2 backend % python manage.py migrate Traceback (most recent call last): File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 279, in ensure_connection self.connect() File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 256, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/db/backends/postgresql/base.py", line 332, in get_new_connection connection = self.Database.connect(**conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.OperationalError: could not translate host name "db.jpjvgnlyxkkhgihmneys.supabase.co" to address: nodename nor servname provided, or not known The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/mac/Documents/projects/community_app/backend/manage.py", line 22, in <module> main() File "/Users/mac/Documents/projects/community_app/backend/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/core/management/base.py", line 416, in run_from_argv self.execute(*args, **cmd_options) File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/core/management/base.py", line 107, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/core/management/commands/migrate.py", line 114, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/mac/Documents/projects/community_app/backend/venv/lib/python3.11/site-packages/django/db/migrations/loader.py", line 58, in __init__ self.build_graph() File … -
How to disable localization ONLY in Django admin (specifically /admin/jsi18n requests) while keeping it in the main site?
How to disable localization ONLY in Django admin (specifically /admin/jsi18n requests) while keeping it in the main site? I experiencing 503 errors on our production server due to a high volume of requests to the /admin/jsi18n endpoint when multiple members use the Django admin simultaneously. -
Django Allauth Google OAuth: MultipleObjectsReturned even though no duplicates in MySQL
I’m using Django + MySQL with django-allauth and Google OAuth. Login fails with this error: MultipleObjectsReturned: get() returned more than one SocialAccount The confusing part is that the database does not contain duplicates. Here is what I checked: 1. No duplicate Google accounts SQL: SELECT uid, COUNT(*) FROM socialaccount_socialaccount GROUP BY uid HAVING COUNT(*) > 1; → returns 0 rows. 2. No duplicate users by email Python: User.objects.values("email") .annotate(count=Count("id")) .filter(count__gt=1) → also empty. 3. My relevant allauth settings: SITE_ID = 1 ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True SOCIALACCOUNT_QUERY_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = "email" 4. Only one Google OAuth app and only using localhost in callback. Credentials are correct. 5. Even after deleting all rows from auth_user and socialaccount tables, the next login still throws the same error. 6. There is really only one row in socialaccount_socialaccount, but allauth still raises MultipleObjectsReturned during login. My question: What else in django-allauth or the authentication pipeline can cause a MultipleObjectsReturned error even when the database does not contain duplicates? Is there something like: a temporary duplicate created during login? signals or adapters running twice? duplicate queries on email lookup? a caching issue? Any debugging tips would help. -
How do I preview a Pdf fike via a presigned S3 URL in React?
I have an api which is responsible for download the file of any mime type if its available in the s3 bucket now in the response it draws a presigned url, hmacsignature, urlbucket name, etc. Now I want to use that presigned url to create an react preview popup to display the pdf without downloading it. My backend code is in Golang. -
How to combine Django server-side rendering with a dynamic JavaScript frontend?
I’ve been working with Django for a while and I’m trying to find an approach that provides fast server-side rendering while still allowing highly interactive, JavaScript-driven behavior on the client side. What are the recommended best practices for combining Django’s server-rendered templates with a modern JavaScript frontend? I currently use Django Ninja as an API layer with a separate JS frontend, but I’m wondering if there’s an established pattern for integrating both approaches effectively. For example, the server could deliver an up-to-date, cached HTML page immediately via Django’s template rendering, and then JavaScript would take over to update or enhance the dynamic parts of the page, but the page should be displayed immediately. -
When are user permissions ready? - trying to assign permission in post-migration signal
Fairly new to django so there must be a lot I have no idea about. How can I assign user related permissions to user groups in a post migration signal? I have read everywhere that post migration signal can work which actually does... to an extent. I can create the required user groups and assign permissions to them but the ones related to user model. E.g. view_user, create_user, change_user are not ready to be assigned in post migration. Im not sure of all the options I have here but already tried to define a migration file and nitpicking sender does not look like a way forward either. Signal handler: @receiver(post_migrate) def create_groups_and_assign_permissions(sender, **kwargs): print(f"sender: {sender}") # Only run after auth migrations if sender.label != "auth": return for (code_name, name), permission_codenames in GROUPS_AND_PERMISSIONS.items(): group, _ = Group.objects.get_or_create(name=name) GroupMetadata.objects.get_or_create( group=group, code_name=code_name, display_name=name ) for codename in permission_codenames: try: perm = Permission.objects.get(codename=codename) group.permissions.add(perm) except Permission.DoesNotExist: print(f"[WARNING] Permission '{codename}' does not exist yet") Singal is imported in the AppConfig: from django.apps import AppConfig class UserGroupsConfig(AppConfig): default_auto_field = "django.db.models.BigAutoField" name = "apps.users.features.user_groups" def ready(self): # Register signals import apps.users.features.user_groups.signals # pylint: disable=unused-import, import-outside-toplevel GROUPS_AND_PERMISSIONS constants: GROUPS_AND_PERMISSIONS = { ("manager", "Manager"): [ ... "add_profile", "change_profile", "view_profile", … -
"You cannot access body after reading from request's data stream"
I have a piece of code that sends a json to the server but form.onsubmit = async (e) => { e.preventDefault(); const formData = new FormData(form); const response = await fetch('api/get-comments/', { method: 'POST', body: formData }); if (response.ok) { await fetchComments(); document.getElementById('commentText').value = ''; } } when I try to read it it comes back with an error that it can't access the body def get_comments(request, gameID: int): """Renders the comment page.""" assert isinstance(request, HttpRequest) if request.method == "POST": comment_text = json.get(request.body) user = request.user # comment = Comments( # userID=user, # gameID = Games.objects.get(gameID=gameID), # commentText=comment_text, # commentTime=datetime.now() # ).save() return HttpResponse(comment_text ,status=201) -
Why does using Python’s print() function cause a rendering error in Django, and what should be passed to render() instead?
Problem Code Snippet (Python: Django)- def home(request): data = {"msg": "Hello"} result = print(data) # Problematic line return render(request, "index.html", result) # why render? Is there any other way? -
Django Admin: User without permissions can still see a model (UserIncomeSupportDocument) — how to hide it?
I have a Django Admin setup where a Marketing user should only be allowed to view Clients and Therapists. However, even after removing all permissions related to UserIncomeSupportDocument, the Marketing user can still see the model in the Django Admin sidebar. They can even open the changelist view. I expected that removing the model’s permissions would hide it, but it still appears by default. Expected behavior If a user does not have: api.view_userincomesupportdocument api.add_userincomesupportdocument api.change_userincomesupportdocument api.delete_userincomesupportdocument Then the model should not appear in Django Admin at all. Current behavior Even after removing all permissions, the model still shows up: Site administration Api Clients (OK) Therapists (OK) User income support documents <-- SHOULD NOT BE VISIBLE Admin code for the model Here is the relevant Django Admin code: class UserIncomeSupportDocumentForm(forms.ModelForm): class Meta: model = UserIncomeSupportDocument fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.instance.document and hasattr(self.instance.document, 'url'): self.fields['document'].initial = self.instance.document.url else: self.fields['document'].initial = None class UserIncomeSupportDocumentAdmin(admin.ModelAdmin): form = UserIncomeSupportDocumentForm def income_support_file_link(self, obj): return f'<a href="{obj.document.url}">Download</a>' income_support_file_link.allow_tags = True # Some attempts I tried but they didn't work: # def get_model_perms(self, request): # if request.user.groups.filter(name='Marketing').exists(): # return {} # return super().get_model_perms(request) My Question Is there a reliable way to ensure … -
How Should I manage AI functions and business logic in back-end efficiently
My recent project is a AI Gym trainer app and I am in charge of the back-end. The project purpose is to let user get an AI Gym trainer who guide them daily with personalized suggestions. The main AI tasks are: Normal chatting Daily workout session generate Body image analysis Calorie target There are some functions that uses RAG. So, it needed to load in the vector db while initializing the project. That's not the main problem I faced. Because of using Pinecone and langchain there were many heavy dependencies that sizes are above 700MB-800MB it took 900s+ just to install the dependencies. Restarting my server each time feels 4-5s or more delay every time. Also I faced a worse scenario while installing the dependencies on VPS. I faced many conflicts related to the langchain related package. At the end I removed all the version names from requirements.txt then finally I was able to install them. So, I was wondering if it is ok to run the heavy AI functions on the business logic server or I should create a micro service. My backend server is using Django and Django Rest Framework. The initial idea came into my mind is … -
Failed import for drf_nested_routers
this import in urls.py gives me an error from drf_nested_routers import DefaultRouter as NestedDefaultRouter Import "drf_nested_routers" could not be resolved however the drf_nested_routers it is installed venv as in inside my requirements.txt file -
Django 3-Tier Nested Modeling
I have a problem where I need a deeply nested model. I have a model named Theme (it's called something else), and in theme I can have many Types. In a Type I can have many or none SubTypes. In a SubType I can have many or none Additionals. The JSON Structure would be like so: { "id": 5, "name": "test-theme", "types": [ { "type_id": 101, "value": "test-type", "subtypes": [ { "subtype_id": 101, "value": "test-subtype", "additionals": [ { "additional_id": 101, "value": "test-additional" } ] } ] } ] } What I've done so far: I've setup my core models -> Type, SubType, and Additionals. Since, these models will be defined and immutable. Then I've setup my models to create the user defined theme context. This is the only time where a type has subtypes, a subtype has additionals. An example of how I set it up: class Theme(models.Model): """ ... """ name = models.CharField(max_length=100, unique=True) ... class ThemeTypeBridge(models.Model): """ ... """ theme = models.ForeignKey(Theme, related_name="types", on_delete=models.CASCADE) type = models.ForeignKey(Type, related_name="theme_links", on_delete=models.CASCADE) ... The 3-tier nested data: Theme - ThemeTypeBridge - ThemeSubTypeBridge - ThemeAdditionalBridge I'm having trouble with writable serializers in django, since I have a main model that has a … -
How to implement oAuth2 login with google?
I Am currently developing a Django game_logging tool. I Implemented a login and signup. But I want to create a Google login to. Can anybody help me with this? -
Solving the circular problem in Django models
acconts/models.py class UserX(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_activ = models.BooleanField(default=True) is_verified = models.BooleanField(default=False) # user_follower= models.ManyToManyField("self", through="friends.Follower", related_name="folowers_user", symmetrical=False) objects = ManageUserX() USERNAME_FIELD = 'username' save_p = models.ManyToManyField(through='posts.SavePosts',to='posts.Posts', related_name='save', blank=True, null=True, default = 0) def _str_(self): return self.username posts/models.py class Posts(models.Model): name = models.CharField(max_length=300) marke = models.ForeignKey('acconts.UserX', on_delete=models.CASCADE, null=True, related_name="marke_post") slug = models.SlugField() bad_admin = models.BooleanField(default=True) like = models.ManyToManyField(through='CustomMtoMLike', to='acconts.UserX', related_name="like_post_user") image = models.ImageField(upload_to = 'jjj', blank=True, null=True) # Data time_create = jalali.jDateTimeField(auto_now_add=True) time_update = jalali.jDateTimeField(auto_now=True) time_update = jalali.jDateTimeField(auto_now=True) def _str_(self): return self.name if self.name else self.marke.email