Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to filter objects to get the sum of the repeated values in Django?
models.py name = models.ForeignKey(CustomUser) date = models.DateTimeField() orders = models.IntegerField(default=0) this is the model which counts daily orders of a user. the order which is made in the same day will just increase the orders count by one. So how to make a query or serializer which gives the result of users with their total orders of all time eg: [{name:albert, orders:35}, {name:Vncent, orders:35}, {name:john, orders:35}, {name:dion, orders:35}, {name:aoidi, orders:35},] -
django count ids in every subgroup
I have models of subjects, topics and questions structured as following: class Subject(models.Model): subject = models.CharField(max_length=200, unique=True) class Topic(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE) topic = models.CharField(max_length=200, blank=False) class Question(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE, topic = ChainedForeignKey( "Topic", chained_field="subject", chained_model_field="subject", show_all=False, auto_choose=True, ) Now I want to create a query that will count ids for each subject, topic. viz: ╔═════════╤═══════╤═══════╗ ║ subject │ topic │ count ║ ╠═════════╪═══════╪═══════╣ ║ 1 │ 1 │ 10 ║ ╟─────────┼───────┼───────╢ ║ 1 │ 2 │ 11 ║ ╟─────────┼───────┼───────╢ ║ 2 │ 3 │ 5 ║ ╟─────────┼───────┼───────╢ ║ 2 │ 4 │ 4 ║ ╚═════════╧═══════╧═══════╝ So far tried the following: numberq=Question.objects.all().values('subject','topic').annotate(TotalQuestions=Count('topic')) numberq=Question.objects.all().values('subject','topic','id').order_by('subject','topic') numberq=df.groupby(['subject','topic'])['id'].count()#.size() Unfortunately nothing yielding expected results. Can someone please guide? As a bonus 🙃 I also want to replace the subject_id and topic_id by the respective name fields. -
Django Avatar Library ValueError
Django has added an Avatar Library to make it easy to install User Avatars: https://django-avatar.readthedocs.io/en/stable/. However I'm lost on: 3: Add the avatar urls to the end of your root urlconf. Your urlconf will look something like: urlpatterns = [ # ... path('avatar/', include('avatar.urls')), ] I want to add the ability for the user to change an avatar on the "profile".html page. path("profile/<str:username>", views.profile, name="profile"), How can I do this? 4: Somewhere in your template navigation scheme, link to the change avatar page: <a href="{% url 'avatar_change' %}">Change your avatar</a> When I add step 4 to the profile page, I get a ValueError: not enough values to unpack (expected 2, got 1). I have not specified a User Avatar yet, but the ReadMe documentation doesn't specify how to set a default avatar image. Thanks so much. I am expecting users to be able to add/change their avatar images. -
Why is my Django web page refusing to load? (View pulling from large mySQL table)
I am currently trying to load a web page which is a table of contracts data that is pulled from a mySQL database. There are a large amount of contracts (210,000+) in the contracts table and it will continue to grow by the thousands daily. As you will see, I have already added pagination, and I have changed the model call to only request columns from the table that are needed to display the information on the webpage. I cannot get the view to load, and I think that it is due to to large size of the contracts table that I am pulling information from. In a separate view, I calculate a similarity array (similarity_arr) and save it as a JSON object in another table in the database, which it is then paired with the user's id as a foreign key. The similarity array is an array which matches the length of the amount of contracts in the contracts table. These contracts are pulled and ordered by the dates they were posted to maintain order which is used to pair the similarity scores to the proper contract in the following view function. The similarity score is just a float … -
How to upload files from django admin panel?
iam using django 3.0.7 and i want to upload files from admin panel but when i try to upload file it still loading and at least it show error 500 request time out , i deploy my website in namecheap so how to fix it settings.py : # media dir MEDIA_URL= '/media/' MEDIA_ROOT = os.path.join('/home/traixmua/public_html/media') urls.py : urlpatterns = [ path('', views.home, name='home'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) handler404 = 'blog_app.views.handler404' models.py : class Trainer(models.Model): document = models.FileField(upload_to='documents/') admin.py : from django.contrib import admin from blog_app.models import Trainer # Register your models here. class TrainerAdmin(admin.ModelAdmin): search_fields = ('name', 'name') admin.site.register(Trainer,TrainerAdmin) what is the problem here i can't find any problem note : when i try to upload files using SQLite it's work good but with mysql i have this problem , i can choose the file but it won't to upload -
Integrity error with Django models (NOT NULL constraint failed)
can someone please help with the below error? IntegrityError at /configuration/solarwinds/ NOT NULL constraint failed: pages_cityname.name Request Method: GET Request URL: http://127.0.0.1:8000/configuration/solarwinds/ Django Version: 3.2.5 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: pages_cityname.name Exception Location: /usr/local/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py, line 423, in execute Python Executable: /usr/local/opt/python/bin/python3.7 Here is my models.py: class Region(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Meta: verbose_name_plural = 'Region' class Cityname(models.Model): region = models.ForeignKey(Region, on_delete=models.CASCADE) name = models.CharField(max_length=40) def __str__(self): return self.name class Meta: verbose_name_plural = 'Cityname' class SolarwindsTool(models.Model): region = models.ForeignKey(Region, on_delete=models.SET_NULL, blank=True, null=True,verbose_name='Region') city = models.ForeignKey(Cityname, on_delete=models.SET_NULL, blank=True, null=True, verbose_name='City') class Meta: db_table = 'solarwindstool' def __str__(self): return self.name -
AttributeError at / 'str' object has no attribute 'decode'
i am facing a problem , that is my django website show an error when i put debug True , and the problem is 'str' object has no attribute 'decode' and i don't know why this happened also the error say i have error in line 25 : def home(request): trainerpostforhome = Trainer.objects.all() app = trainerpostforhome page = request.GET.get('page', 1) page 2 etc paginator = Paginator(app, 10) try: single_home_post = paginator.page(page) # line 25 the error here except PageNotAnInteger: single_home_post = paginator.page(1) except EmptyPage: single_home_post = paginator.page(paginator.num_pages) return render(request,'website_primary_html_pages/home.html', { 'single_home_post': single_home_post }) the full error is : Environment: Request Method: GET Request URL: https://trainermods.net/ Django Version: 2.2.5 Python Version: 3.7.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog_app', 'ckeditor'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/traixmua/django/blog_app/views.py" in home 25. single_home_post = paginator.page(page) File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/core/paginator.py" in page 70. number = self.validate_number(number) File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/core/paginator.py" in validate_number 48. if number > self.num_pages: File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/utils/functional.py" in __get__ 80. res = instance.__dict__[self.name] = self.func(instance) File "/home/traixmua/virtualenv/django/3.7/lib/python3.7/site-packages/django/core/paginator.py" in num_pages 97. if self.count … -
DRF serializer validation depends on format of request?
I tried to google this one up and still cannot find an answer. Maybe I am missing sth basic... While testing a PUT and POST requests with pytest I have noticed that when I provide data with a missing serializer field it is ok - as long as I don't specify the format of the request. The code is simply: class MySerializer(CustomModelSerializer): a = ... b = .... c = serializers.BooleanField(source='some_c') def test(): ... data = {'a': something, 'b': something_else} # 'c' is missing, c should be boolean resp = client.post(reverse('articles-list'), data=data, format='json') ... and I get HTTP 400, {'c': [ErrorDetail(string='This field is required.', code='required')]} when I omit the format part though, the test passes... -
Django redirect not clearing after clearing, disabling cache, etc
I have a maintenance mode on my site which I typically turn on while I make changes. It checks if an IP address is in a list of verified IPs, and if it is not, it redirects to a maintenance page. When I finished working on my site I turned maintenance mode back off. Unfortunately, the home page (and, weirdly, only the home page) still appears to redirect to the maintenance page! To fix this problem, I first tried to disable the cache in my browser. Still redirecting. Then I cleared my cache and all of my cookies. Then, to my astonishment, I saw that it was still redirecting in different browsers. What the heck? Then I decided what the heck, and commented out the maintenance mode code from my middleware. Exact same behavior. Then I tried setting up another redirect that would take you from the maintenance page back to the home page, in hopes it would resolve my issue. Turns out this was a bad idea, because now home redirects to maintenance and maintenance redirects to home, so I get a too many redirects error. I tried to just take that part of the code back out, but … -
Why abort() in celery is setting all fields to null?
I have Django application where I am using celery to run asynchronous tasks. The task goes through list of websites and get some data. Inside this task I am using raise Exception inside while loop. Below is my APIView I am using to stop celery task in React. Revoke() does not work at all and this is the only working way to stop my task. class StopTaskResult(APIView): def get(self, request, task_id): AbortableAsyncResult(task_id).abort() return Response({"msg": "Task has been succesfully stopped"}) The problem I am facing is that when the task status is set to ABORTED all fields except task_id are set to null. Once they reach to Exception they are changed to FAILURE and all values are restored. How to change this behaviour? The most important is to keep periodic_task_name and worker fields (even if task status is equal to ABORTED)? -
How is a django date time field saved in a database?
Is the format of a django datetime in a SQLite database converted to text to be an ISO-8601 string? -
Alternative package for mysqlclient
i want to use mysql for database of django project When deploying on cpanel,pip cannot install mysqlcient any one can help me? pip install mysqlclient -
Django - Query on overridden save() method cached or something
I am overriding the default save() method of my model in Django 4. The problem is that I am making queries related to an instance of the model with the overridden save() method, but the queries seem not to be updated during the method execution. Example: class Routine(models.Model): exercises = models.ManyToManyField(Exercise) def save(self, *args, **kwargs): e = self.exercises.all() # 3 exercises returned super().save(*args, **kwargs) # I call to super deleting 1 exercise and adding a new one e = self.exercises.all() # same 3 exercises returned, not updated with the previous save() call Once all the code has been executed the routine.exercises have been properly updated, the problem is that I am not being able to get this query updated during the save() override. -
ModuleNotFoundError: No module named 'crispy_bootstrap5', crispy forms django
I am new to Django and I am trying to learn/use crispy forms to create a registration/login form. however i keep getting a ModuleNotFound error on the 'crispy_bootstrap5'. I am using intellij and have created a new project and I have installed crispy forms and crispy-bootstrap5 (pip install crispy-bootstrap5) screenshot of pip freeze on the virtual environment. I have also updated the settings.py file to include it in the INSTALLED_APPS Screenshot of installed apps in settings.py file. However when i run the server it gives me ModuleNotFoundError: No module named 'crispy_bootstrap5' error. I also tried to install the crispy tailwind but it also gave me the same errors. I have searched the stack overflow forums but I cannot find a solution. Here is my requirements.txt file. Here is my install of crispy bootstrap. -
Celery error when a chord that starts a chain has an error in the group
I have a Chord. After the chord, we chain another task. If one of the tasks in that group of that chord raises an exception, I get a mess of an exception that looks like a bug in celery or django_celery_results. I am using amqp as my task queue and django_celery_results as my results backend. My Tasks: @shared_task(bind=True) def debug_task(self): print(f'Request: debug_task') @shared_task(bind=True) def debug_A(self, i): print(f'Doing A{i}') @shared_task(bind=True) def debug_broke(self): print(f'OH NO') raise Exception("Head Aspload") @shared_task(bind=True) def debug_finisher(self): print(f'OK, We did it all') def launch(): from celery import group g = [debug_A.si(i) for i in range(5)] g.append(debug_broke.si()) r = group(g) | debug_finisher.si() | debug_A.si(-1) r.apply_async() The results when I run this: [2023-03-08 18:19:52,428: INFO/MainProcess] Task topclans.worker.debug_A[c652e39a-8cf5-4ac8-924d-3bce32c190f8] received [2023-03-08 18:19:52,429: WARNING/ForkPoolWorker-1] Doing A0 [2023-03-08 18:19:52,434: INFO/MainProcess] Task topclans.worker.debug_A[c1b8ed9c-a9e0-4960-8b9b-1ecd5b2254a3] received [2023-03-08 18:19:52,436: INFO/MainProcess] Task topclans.worker.debug_A[a4478640-a50a-42a2-a8f0-8e6b84abab90] received [2023-03-08 18:19:52,439: INFO/MainProcess] Task topclans.worker.debug_A[d4c9d249-98dd-4071-ab03-70a350c7d171] received [2023-03-08 18:19:52,439: INFO/MainProcess] Task topclans.worker.debug_A[41c4bdb0-8993-40b0-90bd-2d6c642cb518] received [2023-03-08 18:19:52,462: INFO/ForkPoolWorker-1] Task topclans.worker.debug_A[c652e39a-8cf5-4ac8-924d-3bce32c190f8] succeeded in 0.03368515009060502s: None [2023-03-08 18:19:52,465: INFO/MainProcess] Task topclans.worker.debug_broke[de4d83d9-1f5b-4f02-ad9e-1a3edbedd2f8] received [2023-03-08 18:19:52,466: WARNING/ForkPoolWorker-1] Doing A1 [2023-03-08 18:19:52,481: INFO/ForkPoolWorker-1] Task topclans.worker.debug_A[c1b8ed9c-a9e0-4960-8b9b-1ecd5b2254a3] succeeded in 0.015777542954310775s: None [2023-03-08 18:19:52,483: WARNING/ForkPoolWorker-1] Doing A2 [2023-03-08 18:19:52,500: INFO/ForkPoolWorker-1] Task topclans.worker.debug_A[a4478640-a50a-42a2-a8f0-8e6b84abab90] succeeded in 0.017103158170357347s: None [2023-03-08 18:19:52,501: WARNING/ForkPoolWorker-1] Doing A3 [2023-03-08 18:19:52,515: INFO/ForkPoolWorker-1] Task topclans.worker.debug_A[d4c9d249-98dd-4071-ab03-70a350c7d171] … -
In Wagtail, how to prevent page deletion by editors, or set a minimum number of pages of a kind
The site we developed has 2 type of pages, let's call them... "Static" ones: Home, Contact, About us, the general Catalog page, the general Blog page... "Dynamic" ones: each Collection in the catalog, each Blog entry. We, as developers, provide the final customer with all the structure for the Static ones, meaning they don't have to create them at all. There are many reasons for it but mainly because the site structure counts on these pages to always exist (in a Published state btw, but let's leave that aside). And we let and teach the client's editor to do, among other stuff.. Just edit the existing "static"pages. Create, edit and delete child pages in Catalogue and Blog. But we want to prevent them from deleting any of the other pages. Things might blow up, like, the Home shows some information collected from some of the other sections etc... but mainly because it doesn't make sense in our situation, that is: the only case in which they might delete one of the "static" pages is by accident. If they really want to delete any of these pages, that's a decision design that will involve other people (managers, designers and developers) and … -
How do i fix Reverse for 'viewStudents' with arguments '('',)' not found. 1 pattern(s) tried: ['schedule/(?P<year_id>[0-9]+)\\Z']?
So I am creating auto-generating school schedule app in django. I try to make a list on a page where user can choose different years of classes (For example if someone want to check groups of 4th year) and now i am facing reverse link problem. Here is the code: views.py #adding students def addStudent(request): if request.method == "POST": year = request.POST["year"] faculty = request.POST["faculty"] number = request.POST["group_number"] f = Students(group_year = year, group_title = faculty, group_number = number) f.save() return render(request, "app/AddingForms/addStudents.html") #viewing def viewStudents(request, year_id): arr = Students.objects.filter(group_year = year_id) context = {"year_id":year_id, 'students':arr} return render(request, "app/AddingForms/Studentslist.html", context) models.py class Students(models.Model): group_year = models.IntegerField() group_title = models.CharField(max_length= 10) group_number = models.IntegerField() lessons = models.ManyToManyField(Lesson) def __str__(self): return self.group_title urls.py: #FOR CORE APP app_name = "scheduleapp" urlpatterns = [ path("", views.index, name = 'index'), path("profile/", views.index, name = "profile"), path("about/", views.about, name = "about"), path("add/", views.addingMenu, name = "adding"), path("add-student/", views.addStudent, name = "addStudent"), path("add-lesson/", views.addLesson, name = "addLesson"), path("add-teacher/", views.addTeacher, name = "addTeacher"), path("add-student/<int:year_id>", views.viewStudents, name = "viewStudents") ] html link <ul class="list-group"> <li class="list-group-item active" aria-current="true">Currently Active Groups:</li> <a href = "{% url 'scheduleapp:viewStudents' year_id %}"><li class="list-group-item">1st Year</li></a> </ul> What should I do in order to fix … -
Unabled to edit - Django
I'm creating a simple rest api Right now the result from groups is this: My result from devices right now [ { "id": "8079bf12-bb58-4ea0-a810-58a223d84be7", "name": "Cozinha" } ] my models.py from uuid import uuid4 from django.db import models class Options(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) identifier = models.CharField(max_length=255) class Meta: ordering = ['name'] def __str__(self): return self.name class Groups(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) class Meta: ordering = ['name'] def __str__(self): return self.name class Devices(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) identifier = models.CharField(max_length=255) options = models.ManyToManyField(Options) group = models.ForeignKey(Groups, on_delete=models.CASCADE, default="") viewsets from rest_framework import viewsets from devices.api import serializers from devices import models class DevicesViewsets(viewsets.ModelViewSet): serializer_class = serializers.DevicesSerializer queryset = models.Devices.objects.all() class OptionsViewsets(viewsets.ModelViewSet): serializer_class = serializers.OptionsSerializer queryset = models.Options.objects.all() class GroupsViewsets(viewsets.ModelViewSet): serializer_class = serializers.GroupsSerializer queryset = models.Groups.objects.all() def perform_create(self, serializer): serializer.save() serializers from rest_framework import serializers from devices import models class OptionsSerializer(serializers.ModelSerializer): class Meta: model = models.Options fields = '__all__' class GroupsSerializer(serializers.ModelSerializer): class Meta: model = models.Groups fields = '__all__' class DevicesSerializer(serializers.ModelSerializer): group = GroupsSerializer() options = OptionsSerializer(many=True) class Meta: model = models.Devices fields = '__all__' def create(self, validated_data): group_data = validated_data.pop('group') options_data = validated_data.pop('options') group, _ = models.Groups.objects.get_or_create(**group_data) options … -
Docker Django staticfiles are not copied to STATIC_ROOT
I am generating static files for my Django app inside a Docker environment. In the logs, the static files are 'copied'. 173 static files copied. However, the static files are not present inside the volume. I print my settings to see this... #settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') print('STATIC_ROOT:', STATICFILES_DIRS) print('FILES:', os.listdir(STATIC_ROOT)) The STATIC_ROOT is empty. STATIC_ROOT: '/usr/src/app/staticfiles' FILES: [] I am using a named volume for the static files. I also execute the collecstatic in here. version: "3.9" services: api: container_name: api build: dockerfile: ./api/Dockerfile command: > sh -c "python manage.py wait_for_database && python manage.py migrate && python manage.py collectstatic --no-input --clear && python manage.py loaddata fixtures/initial.json && gunicorn api.wsgi:application --bind 0.0.0.0:8000" volumes: - application:/usr/src/app - static_volume:/usr/src/app/staticfiles ports: - "8000:8000" env_file: - test-prod.env nginx: container_name: nginx build: dockerfile: ./nginx/Dockerfile volumes: - static_volume:/usr/src/app/staticfiles ports: - "80:80" depends_on: - api restart: always volumes: application: static_volume: In my Dockerfile, I create the directory for the staticfiles and copying the source code to the volume. FROM python:3.9-bullseye WORKDIR /usr/src/app ... ... RUN mkdir /usr/src/app/staticfiles COPY api /usr/src/app I do not get where the static files are copied. I know they're not in the correct directory where I specified STATIC_ROOT since no … -
How to convert Neomodel relationship data into JSON for passing it to Cytoscape.js
I am trying to display Neo4J graph data in my Django template. For querying I am using neomodel, and Cytoscape.js for graph visualization. I am able to convert nodes data in the form of JSON that cytoscape.js requires, but for edges I don't have idea how to do it. This are my Models class Player(StructuredNode): name = StringProperty(required=True) age = IntegerProperty(required=True) height = IntegerProperty(required=True) number = IntegerProperty(required=True) weight = IntegerProperty(required=True) team = RelationshipTo('Team', 'PLAYS_FOR', model=PlayerTeamRel) @property def serialize(self): return { 'data': { 'id': self.id, 'name': self.name, 'age': self.age, 'height': self.height, 'number': self.number, 'weight': self.weight, } } class Team(StructuredNode): name = StringProperty(required=True) players = RelationshipFrom('Player', 'PLAYS_FOR') coach = RelationshipFrom('Coach', 'COACHES') @property def serialize(self): return { 'data': { 'id': self.id, 'name': self.name, 'players': self.players, 'coach': self.coach } } class Coach(StructuredNode): name = StringProperty(required=True) coach = RelationshipTo('Team', 'COACHES') @property def serialize(self): return { 'data': { 'id': self.id, 'name': self.name, 'coach': self.coach } } serialize() method is used get JSON format. That relationship attribute(team) is of type ZeroToOne when I try to print it in the console. I want the JSON in the below format, specifically relationship(edges) data as I am able to serialize and display node data. { data: { id: 'a' } … -
How to rename choose file button in Django administration
I have a problem with the translation of the file selection button (specifically pictures). The entire interface of the admin panel is in Ukrainian, that is, as it should be. But only this button (see photo) is in Russian. How can I translate it into Ukrainian? enter image description here I found answers about how to add a button through changing the admin templates, but I could not find how to rename a specific button. I couldn't find where this button is. -
Pycharm virtual environment only displays html of my project, no CSS
I've managed to set up a virtual environment in Pycharm in order to edit my Django app, and the associated website that it interacts with. The interpreter recognizes Django, and I can make edits to my app, but for some reason it can't seem to find my css files that are in my 'static_files' directory. Here are the instructions in my settings.py file, which Django should be able to access:STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_files') Here are my directories in my project, maybe something is in the wrong place? I've tried adding STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_files'),], and still nothing changes, can't find CSS. Not sure what to do about this, Pycharm seems to run into consistently run into problems that don't exist on my regular server for hosting my site and app. -
How to Create a Profile to an user
im relative new to django, before i only created simple applications that did not require any user stuff, now however i need to create a website with users, for now i created user register, log in and log out, but im struggling to create the profile for the user, should i create an app only for profile ? or maybe put the profile together on the models inside the user app where is the user authentication is, how do i go about the views on this matter ? if someone has a simple example that even a dumb person like me can understand i would appreciate a lot, thanks in advance. For now i tried to create an App for profile and make a model for profile with the OnetoOne Field: user = models.OneToOneField(settings.AUTH_USER_MODEL, null = True, on_delete= models.CASCADE) However im having a trouble where the profile does not start with the user, meaning that the user will have to create the profile and then when he wants to change he needs to go on the other option called edit, which is a bit awkward -
Django - get model instance from a custom field
For a new project I defined a custom field EncryptedField. In this field, I use the methods get_prep_value and from_db_value. In these methods, I have access to the value of the field, so I can encrypt and decrypt it. I also need the value of another field of the model where EncryptedField is used for the encryption/decryption. So is it possible to have access to the instance of the model that calls my custom field EncryptedField. Like that I can have access to the other field value. Or there is an other way to get the other field value in these methods? I tried to use contribute_to_class but it seems to not be adapted to get the model instance. Thanks for your help -
Django Rest Framework different image size for different account tiers 3 build in and possibility to make new
#a link to a thumbnail that's 200px in height - Basic #a link to a thumbnail that's 400px in height - Basic and Intermediate #a link to the originally uploaded image - Basic, Intermediate and Premium class Profile(models.Model): MEMBERSHIP = ( ('BASIC', 'Basic'), ('PREMIUM', 'Premium'), ('ENTERPRISE', 'Enterprise') ) user = models.OneToOneField(User, on_delete=models.CASCADE) membership = models.CharField(max_length=10, choices=MEMBERSHIP, default='BASIC') def __str__(self): return f'{self.user.username} {self.membership} Profile' The only way I know how to do 3 build in tiers are like above. I don't know how to do more memberships with different image sizes that can be added from admin panel. I want to have them as one model and add it as necessary to make a new user.