Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get a QuerySet with type of a ForeignKey attribute in Django
I have a simple database model in Django that looks like: class Employee(Model): first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) class PrizeDraw(Model): winner = models.ForeignKey( Employee, null=True, on_delete=models.SET_NULL, ) What I want now is a QuerySet of type Employee that contains all the winners of all PrizeDraws. I would have thought that to be fairly straightforward by something something like: def get_queryset(self): return PrizeDraw.objects.exclude(winner__isnull=True).values('winner') However, that doesn't actually return me what I want, instead it returns: <QuerySet [{'winner': (Employee1) }, {'winner': (Employee2) }, etc...]> Which makes sense according to the values() documentation it returns a Dictionary of values. But this doesn't work for me in the rest of the code I need, so I want to select only the second (i.e. value) part of the key-value pair and return that as a QuerySet that just looks like <QuerySet[Employee1, Employee2, etc...]>. How can I select the right value as to get that desired QuerySet? -
Django ContentType and generic relationship
I need a proper and detailed explanation and understanding of how Django content type model works and the use and purposes of generic relationships. I am trying to create an anonymous chatting app where users can come and register and other people can send them messages whether registered or not through a link the user created and they would not know who sent it. -
Send data to another django template/view after specific process using ajax
I have a page where I load 2 files. After a click to the load button, this page reload to display a major part of the data, allowing the user to modified it. After a click to lunch button, I want to launch the process and I want to send to another page the path of results files to allow the user to download it. My problem is after clicking on lunch button and send data to the other page. I have 2 versions : The first one, send data to the result page, but I do not find a way to take back in the view the data modified by the user, the ajax seems to be ignored because of the type "summit" for the button launch : <body> <section class="bg-light py-5 border-bottom"> <div class="container px-5 my-5 px-5"> <div> <h1 class="display-5 fw-bolder mb-2"> Convert to Dose </h1> <br> </div> <form id="formCTD" action="{% url 'json:convertToDose' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} ##here some fields to modified one of them following <div class="row gx-5 justify-content-center"> <div class="col-lg-4 col-xl-4"> {% if factors %} <input name="img_path" readonly class="form-control" {{ pathAnalyseForm.img_path }}> {% else %} <input id="btn-submit-form-jsonfile" class="btn btn-lg" {{ formImgFile.imgFile }}> {% endif … -
Django - How to access parent object for passing as URL primary key inside templates?
I have two Django models: class AP(models.Model): room = models.ForeignKey(Room, on_delete=models.SET_NULL, null=True) and class Room(models.Model): name = models.CharField(max_length=20, unique=True) I have passed an object of AP class as ap to the template. In the template, I am trying to create a hyperlink with ID of the room. I am creating hyperlink through the following line: <a href="{% url 'edit_ap' ap.room.id %}">{{ap.room.name}}</a> This is throwing the following error: Reverse for 'edit_ap' with arguments '('',)' not found. 1 pattern(s) tried: ['edit\\-ap/(?P<pk>[^/]+)/$'] The urls.py has the following matching pattern: path('edit-ap/<str:pk>/', views.edit_ap, name='edit_ap'), The hyperlink is working if the primary key is changed from ap.room.id to ap.room, which passes room.name as the primary key to the URL. However, I need to provide ap.room.id as the primary key. I believe it has to do with using two dots in the primary key. Can you please suggest how can I pass ap.room.id as primary key to my URL? Thank you. -
django clean method is not being called when validating form
I tried the simplest way of form validation I could find using the clean method (I need to validate multiple fields). However, it is not working and it is not throwing any errors. forms.py class DOEForm1(ModelForm): class Meta: model = Doe labels = { 'column_parameter': ('Parameter to vary'), 'column_min': ('Minimum value'), 'column_max': ('Maximum value'), 'column_step': ('Step value'), } exclude = ('substrate','row_parameter','row_min','row_max','row_step',) def clean(self): cleaned_data = super().clean() print('test') min = cleaned_data.get('column_min') max = cleaned_data.get('column_max') step = cleaned_data.get('column_step') if min and max and step: if not (int(step) > 10): raise ValidationError( '(!) the parameters you inputted dont go well with the substrate size' ) return cleaned_data template {% extends 'accounts/main.html' %} {% load static %} {% block content %} <br> <div class="row" style = "padding-left: 15px; width: 500px; margin: auto;"> <div class="col" style = "margin: auto; "> <div class="card card-body"> <form style = "margin: auto; width: 400px; padding: 20px; border: 1px solid #270644;" action="" method="POST"> {% csrf_token %} <table> {{ St_form.as_table }} {{ DOE_form.as_table }} </table> {% for error in form.non_field_errors %} <p class = "help is-danger">{{ error }}</p> {% endfor %} <input type="submit" name="Submit" > </form> </div> </div> </div> {% endblock %} views.py def ST_parameters(request): st_form = STForm() doe_form = DOEForm1() … -
working with SQLSERVER database that doesn't have keys using DJANGO
I'm currently doing an internship at a company, they asked me to build an invoice management web app, the process is a little complicated. First I created the login page, home page and the core elements of every web app. I used PostgreSQL for this, but when I wanted to build the main functionalities of the app, I switched to a copy of their database, they are using SQL Server 2012 and the data is coming from an ERP. The problem is when I have connected to database and use inspect DB to get the tables, I discovered that all the tables in the database don't have a Primary Key or Foreign Key. I asked the IT responsible about this and he told me that the ERP is stocking the data without any keys, it uses another method. I would really appreciate it if someone could help me out of this issue. -
Django - making form which contains two related models
I wonder if it is possible to make a django model based form which will allow to create two models which one will be passed as a foreign key to second one. let we have these models: class Book(models.Model): title = models.CharField(max_length=200) published = models.DateField() def __str__(self): return self.name class Chapter(models.Model): name = models.CharField(max_length=200) number = models.IntegerField() book = models.ForeignKey(Book, on_delete=models.CASCADE) def __str__(self): return self.name I'd like to make a view which will contain BookForm and many ChapterForms somehing like: Book.title = [input] Book.published = [input] and below that (still in the same view) Chapter.name = [input] Chapter.number = [input] Chapter.name = [input] Chapter.number = [input] add more chapters After submitting form, Book and related chapters should be created How can I achive it ? Till now I was just making two views: one for making a Book and second one for chapter which gets created book's id as a parameter in url, but I'd like to make it in one view -
Different methods of Django User model
I have been using Django for 4 5 months now and i have been implimenting users by importing the user class like this example 1: from django.db import models from django.contrib.auth.models import User class Posts(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post_name = models.CharField(max_length=150) desription = models.CharField(max_length=200) image = models.ImageField(upload_to="images/uploads") def __str__(self): return self.desription and i have seen some people use the user model like this : example 2: class Recipe(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=220) description = models.TextField(blank=True, null=True) directions = models.TextField(blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) and also like this : example 3: author = models.ForeignKey(get_user_model()) now I have used both example 1 and example 2 for my projects and to mess around in my free time and both seem to work fine , I am wondering what would be the use cases for these different methods and also is there any pros or cons to these methods of using the User Model? -
Add health check to Kafka consumer k8s pods
How to add health check(liveness/readiness) in Kafka consumer pods in my Django application. New to this infra-structure related things. Please help in implementing a periodic health check for Kafka consumer pods in my application so that it does not allow pods to rotate if their health is not perfect if there is any issue. -
Configuration Heroku, daphne, redis - CHANNELS
I'm trying to get django channels to work with daphne, apparently daphne (PROCFILE) works and redis (part of CHANNEL_LAYERS) too, but I can't connect, whenever I run the app, and open a "room" it automatically disconnects, it is worth mentioning that my site is running with HTTPS and has a valid certificate 2022-08-19T13:20:57.879758+00:00 app[worker.1]: conn = await self.create_conn(loop) 2022-08-19T13:20:57.879769+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/channels_redis/core.py", line 79, in create_conn 2022-08-19T13:20:57.879862+00:00 app[worker.1]: return await aioredis.create_redis_pool(**kwargs) 2022-08-19T13:20:57.879863+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/aioredis/commands/__init__.py", line 188, in create_redis_pool 2022-08-19T13:20:57.879967+00:00 app[worker.1]: pool = await create_pool(address, db=db, 2022-08-19T13:20:57.879978+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/aioredis/pool.py", line 58, in create_pool 2022-08-19T13:20:57.880062+00:00 app[worker.1]: await pool._fill_free(override_min=False) 2022-08-19T13:20:57.880073+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/aioredis/pool.py", line 383, in _fill_free 2022-08-19T13:20:57.880224+00:00 app[worker.1]: conn = await self._create_new_connection(self._address) 2022-08-19T13:20:57.880233+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/aioredis/connection.py", line 133, in create_connection 2022-08-19T13:20:57.880336+00:00 app[worker.1]: await conn.auth(password) 2022-08-19T13:20:57.880345+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/aioredis/util.py", line 52, in wait_ok 2022-08-19T13:20:57.880426+00:00 app[worker.1]: res = await fut 2022-08-19T13:20:57.880437+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/aioredis/connection.py", line 186, in _read_data 2022-08-19T13:20:57.880564+00:00 app[worker.1]: obj = await self._reader.readobj() 2022-08-19T13:20:57.880576+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/site-packages/aioredis/stream.py", line 102, in readobj 2022-08-19T13:20:57.880669+00:00 app[worker.1]: await self._wait_for_data('readobj') 2022-08-19T13:20:57.880680+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/asyncio/streams.py", line 502, in _wait_for_data 2022-08-19T13:20:57.880853+00:00 app[worker.1]: await self._waiter 2022-08-19T13:20:57.880863+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.10/asyncio/selector_events.py", line 854, in _read_ready__data_received 2022-08-19T13:20:57.881081+00:00 app[worker.1]: data = self._sock.recv(self.max_size) 2022-08-19T13:20:57.881108+00:00 app[worker.1]: ConnectionResetError: [Errno 104] Connection reset by peer 2022-08-19T13:20:58.216868+00:00 heroku[worker.1]: … -
'list' object has no attribute '_committed'
this is my problem 'list' object has no attribute '_committed' how to solve pls help me. enter image description here def add_trainer(request): if request.user.is_authenticated: if request.method == 'POST': print(request.POST) trainer_name = request.POST.get('trainer_name') adderes = request.POST.get('adderes') phone_no = request.POST.get('phone_no') phone_no_optional = request.POST.get('phone_no_optional') email = request.POST.get('email') email_optional = request.POST.get('email_optional') gender = request.POST.getlist('gender') trainer_international = request.POST.getlist('trainer_international') trainer_pricing = request.POST.get('trainer_pricing') trainer_course_specialization = request.POST.get('trainer_course_specialization') trainer_skill_set = request.POST.get('trainer_skill_set') trainer_enrolled_with = request.POST.get('trainer_enrolled_with') trainer_tier = request.POST.get('trainer_tier') trainer_attachment = request.POST.getlist('trainer_attachment') obj = Trainer(trainer_name=trainer_name, adderes=adderes, phone_no=phone_no, phone_no_optional=phone_no_optional, email=email, email_optional=email_optional, gender=gender, trainer_international=trainer_international,trainer_pricing=trainer_pricing, trainer_course_specialization=trainer_course_specialization, trainer_skill_set=trainer_skill_set, trainer_enrolled_with=trainer_enrolled_with, trainer_tier=trainer_tier, trainer_attachment=trainer_attachment) obj.save() learning_path = Learning_Path.objects.all() df= {'learning_path': learning_path} return render(request, 'add_trainer.html', df) else: print('hello') return render(request, 'add_trainer.html') else: html = '<!DOCTYPE html><html><head></head><body><h1> Unauthorized Access </h1></body></html>' return HttpResponse(html) please help me to solve this as soon as possible -
Problem in posting Django API it shows "name": [ "This field is required." ]
this is my serializers.py from rest_framework import serializers from api.models import Movie class MovieSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) name=serializers.CharField() description= serializers.CharField() viewed = serializers.BooleanField() def create(self,validated_data): return Movie.objects.create(**validated_data) this is my models.py class Movie(models.Model): name = models.CharField(max_length=20) description = models.CharField(max_length=100) viewed=models.BooleanField(default=True) def __str__(self): return self.name this is views.py @api_view(['GET','POST']) def home(request): if request.method == 'GET': movies=Movie.objects.all() serializer=MovieSerializer(movies,many=True) return Response(serializer.data) if request.method == 'POST': serializer=MovieSerializer(data=request.POST) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) this is what my output looks like { "name": [ "This field is required." ], "description": [ "This field is required." ] } -
How to create multiple orderitems according to number of dictionaries in list?
This is the data I am sending through postman raw(json) section. And data = json.loads(request.body) and following data are same data = [{'quantity': 2, 'service_id': 1, 'price': 2}, {'quantity': 2, 'service_id': 1, 'price': 2}, {'quantity': 2, 'service_id': 1, 'price': 2}] @api_view(['GET', 'POST']) @csrf_exempt def create_order(request, *args, **kwargs): if request.method == 'POST': now = datetime.date.today() order = Order.objects.create(date=now) order.save() orderid = order.id order_id = orderid data = json.loads(request.body) print('data = '+ str(data)) price = request.session.get('price') print('Price = ' + str(price)) quantity = request.session.get('quantity') print('quantity ' + str(quantity)) service_id = request.session.get('service_id') print("Service id = "+ str(service_id)) orderitemslist = [int(v) for lst in data for k,v in lst.items()] quantity = orderitemslist[1] service_id = orderitemslist[2] price = orderitemslist[3] for item in orderitemslist: orderitemcreate= OrderItem.objects.create(order_id_id=order_id, quantity=quantity, service_id_id=service_id, price=price) orderitemcreate.save() return Response({"data created"}) else: order_qs = models.Order.objects.all().values_list() OrderItem_qs = models.OrderItem.objects.all().values_list() return Response({"Order":str(order_qs),"OrderItem":str(OrderItem_qs)}) I want to store data in db like if there are three [{'quantity': 2, 'service_id': 1, 'price': 2}, {'quantity': 2, 'service_id': 1, 'price': 2}, {'quantity': 2, 'service_id': 1, 'price': 2}] dictionaries in list. The loop should create 3 Orderitem and store each value in table. But it creates 9 orderitems because there are 9 colums(1 dict has 3 col) 3 dicts = 9 cols … -
I can't understand why the form in django is invalid
models.py class User(AbstractUser): is_employer = models.BooleanField(default=False) is_employee = models.BooleanField(default=False) phone = models.CharField(max_length=9, blank=True, null=True) avatar = models.ImageField(upload_to='avatar/', blank=True, null=True) class Employer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='employer', related_query_name='employer') company_name = models.CharField(max_length=255) class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='employee', related_query_name='employee') cv = models.FileField(upload_to='cv/') views.py class EmployeeCreateView(CreateView): model = User form_class = EmployeeForm template_name = 'common/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'employee' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() login(self.request, user) return redirect('common:index') forms.py class EmployeeForm(UserCreationForm): cv = forms.FileField() class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_employee = True user.save() employee = Employee.objects.create(user=user, cv=self.cleaned_data.get('cv')) return user and i read article on the internet about Multiple Users. https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html -
cannot use django ckeditor rich text field content in vue
I hope you are fine. I have a rich text field in my django model and I want to show the content in a vue js template but unfortunately the content is completely in html tags and when I want to show this in the template it shows an html code. I will thank anyone to give me a piece of guidance about this matter. -
Django, despite of setting request.method to POST it's GET in view
I'm making Django app and I have an issue, I've never had problem with before. As always in form view, I'm checking if request.method == 'POST' but somehow it returns False, My code looks like that: def recipe_create_view(request): context = {} form = RecipeForm() IngredientFormset = formset_factory(IngredientForm) formset = IngredientFormset() print(request.method) # prints GET if request.method == 'POST': form = RecipeForm(request.POST) formset = IngredientFormset(request.POST) if form.is_valid(): if formset.is_valid(): form.save() print("made a recipe") for form in formset: child = form.save(commit=False) child.recipe = parent child.save() print("made an Ingredient") return redirect('index') else: print("formset is not valid") else: print("form is not valid") else: print("request method is not correct") # I can see it every time in console context['form'] = form context['formset'] = formset return render(request, 'recipes/create_recipe.html', context) create_recipe.html <form method="POST"> {% csrf_token %} <label>recipe</label> <p>{{form}}</p> <label>ingredients</label> {% for form in formset %} <ul> <label>name</label> <li>{{ form.name }}</li> <label>quantity</label> <li>{{ form.quantity }}</li> </ul> {% endfor %} <div> <input type="submit" value="submit" class="button-33" role="button"> </div> </form> Where is the issue, it so annoyoing. I have already checked plenty of articles and nothing helps -
Multiple .gs code file to multiple sheet on a project
I'm also a newbie on google AppScript. I'm working on two data entry sheets with datasheets for each. I've done coding two .gs code file for them too. Since, two data entry sheets are of same type but for different scope, hence each functions are managed to be unique too. The problem is once in an execution time, only one data entry sheet get executed and produce the result while the next being nothing. I need to run both of them simultaneously just by switching the sheets. Picture includes, a LL_Tool functioning well while HR_Tool is not. Picture includes, a LL_Tool functioning well while HR_Tool is not. -
Django admin site - limit user content on user
admin.py: from django.contrib import admin from .models import Blog admin.site.register(Blog) I have figured out that Django admin serves my needs very well. The only thing I would like to limit is that Users could write/read/edit the Blog applications but for their own entries only. If Alice posts a blog, she can read/write/edit only her posts and not the posts of Bob. Does Django allow anything like this in the admin site or do I need to develop my code? -
Add Redis USER & PASS to Django channel layer
I'm trying to deploy my WebSocket project on the server (for example Heroku). and I have a Redis server that has a USER & PASS. I want to add this to my Django channel layer. I need your help. This is my channel layer: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'USER': 'spadredis-zxs-service', 'PASSWORD': '9zghygpri84f8vl', 'CONFIG': { "hosts": [('188.40.16.3', 32281)], }, }, } This is my error in terminal : await conn.execute('ping') aioredis.errors.AuthError: NOAUTH Authentication required. WebSocket DISCONNECT /ws/chat/lobby_room/ [127.0.0.1:42812] -
Django 404 css file
For a long time I tried to solve the problem with loading all my static files. When I found a working solution, all svg started loading, but css files didn't. Here is my settings.py (showing you only main things) import mimetypes mimetypes.add_type("text/css", ".css", True) BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = False STATIC_URL = '/static/' if DEBUG: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] else: STATIC_ROOT = os.path.join(BASE_DIR, 'static') Here is my urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls import url from django.conf import settings from django.views.static import serve urlpatterns = [ path('', include('main.urls')), url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}), ] Here is an example of using css files in my templates {% load static %} <!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-v4-grid-only@1.0.0/dist/bootstrap-grid.min.css"> <link rel="stylesheet" type="text/css" href=" {% static 'css/reset.css' %}"> <link rel="stylesheet" type="text/css" href=" {% static 'css/main.css' %}"> And this is the error in Chrome Console Refused to apply style from '<URL>' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. And also i cant open css files in a new tab. I am getting that error Also, if you remove %20 from the address bar, then I will open … -
Uploading a file in a form group in angular and send it to Django API
I have a form in the front-end having multiple entries, i.e name, email, phone and also a file field entry. A Form group is used to group all these elements in the same form in Angular. There is also a corresponding model in Django, (Using Django Rest Framework). I could not manage to have the file sent to the API, even if the rest of the data is sent correctly and saved on the back-end. First, I am able to upload the file successfully to Front-end, below I log in the console: Second, the object I send is something like this: {"name":"name", "age":49, "email":"email@field.com", "file":File} The File in the JSON is the same file object displayed in the console above. I tested my backend with Postman, I was able to succesfully have the file as well as the other data saved. (I believe the problem to be more on the Front-end side ). Solutions I found for uploading file in Angular used form data (i.e here), these solutions were not convenient as the form consists only of a file, however in my case I have file as well as other data (Form Group). Another thing I tried that did not … -
Django Rest Framework - Filter with logical and
I'm using Django Rest Framework with DjangoFilterBackend to filter through Publications. Every publication can have multiple authors. My api call to filter the api for authors looks like: /api/v1/publication/?author=1&author=2 This gives me every publication that either author 1 or author 2 has been assigned to. Instead I want to only see the publications that both have published. In other words it should be a logic and, not or. My code is the following: models.py class Publication(models.Model): id = models.BigAutoField(primary_key=True) title = models.CharField(max_length=400) author = models.ManyToManyField(Author, blank=False) type = models.ForeignKey( Type, on_delete=models.PROTECT, null=False, default=1) label = models.ManyToManyField(Label, blank=True) date = models.DateField(blank=False, null=False) url = models.URLField(null=True, blank=True) journal = models.CharField(max_length=400, blank=True) bibtex = models.TextField(blank=True) public = models.BooleanField(default=False) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) file = models.FileField(upload_to=upload_path, blank=True, null=True) class Meta: ordering = ['-date'] def __str__(self): return self.title views.py class PublicationFilter(django_filters.FilterSet): author = django_filters.ModelMultipleChoiceFilter( queryset=Author.objects.all()) class Meta: model = Publication fields = { 'title': ["exact"], 'author': ["exact"] } class PublicationView(viewsets.ModelViewSet): queryset = Publication.objects.prefetch_related( 'author', 'label').select_related('type') serializer_class = PublicationSerializer filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_fields = ['title', 'date', 'journal', 'label', 'author'] search_fields = ['title'] ordering_fields = ['date', 'title'] serializers.py class PublicationSerializer(ModelSerializer): type = TypeSerializer(read_only=False, many=False) label = LabelSerializer(read_only=False, many=True) author = AuthorSerializer(read_only=False, many=True) class … -
Django proxy model is visible on admin site but not showing up in permissions section of the production admin site
Locally I can see the proxy model on the admin site and permissions are visible in the permission section and can be assigned to different users. In production I can see the proxy model on the admin site but permissions are not visible in the permission section and therefore cannot be assigned to different users. I'm expecting to see something like : apps|details|can add apps|details|can delete apps|details|can update apps|details|can view in the permissions section. For other models the permissions are visible. Versions: djangorestframework --> 3.12.2 python --> 3.8 Dir: +Apps - profile - models.py - admin.py - details - models.py - admin.py profile/models.py class Profile: # Model Details details/models.py from profile.models import Profile class ProxyProfile(Profile): class Meta: proxy = True app_label = 'details' verbose_name = 'ProxyProfile' verbose_name_plural = 'ProxyProfiles' details/admin.py from models import ProxyProfile class ProxyProfileAdmin(admin.ModelAdmin): # Admin Model Details admin.site.register(ProxyProfile, ProxyProfileAdmin) -
how to understand if the env is activated in a django project
I am just starting to learn django and I am facing the set-up phase. In particular I'd like to ask how to recognize if the virtual environment is activated or not. I know that I can use the command "pip freeze" but in all the tutorial that I am following , when the venv is activated, I can see the vevn name in brackets in the terminal command line. I can correctly activate the venv with the source command and check via the pip freeze command but I have no indication in the command line. I am on a Mac/OS (chip mac) and using python3 thank you -
"Django" filter according to last added related objects
I want to filter according to last added element of related model with foreignkey relationship field. I try a lot but can not achieve, My models like this class Status(models.Model): member= models.ForeignKey(Member, on_delete=models.CASCADE, related_name='member_status') name = models.CharField(max_length=2, choices=("new","old","continue") status_created_at = models.DateTimeField(auto_now_add=True) class Member(models.Model): messageContent= models.TextField(null=True, blank=True) my queryset like this { "id": 1, "member_status": [ { "id": 8, "name": "new", "notes": "", "status_created_at": "2021-01-01T17:55:21.523162Z", "member": 1 }, { "id": 9, "name": "old", "notes": "", "status_created_at": "2022-08-09T17:56:06.995086Z", "order": 1 } ], "messageContent": "example", }, "id": 1, "member_status": [ { "id": 11, "name": "new", "notes": "", "status_created_at": "2021-01-01T17:55:21.523162Z", "member": 1 }, { "id": 12, "name": "continue", "notes": "", "status_created_at": "2022-08-08T17:56:06.995086Z", "order": 1 } ], "messageContent": "example content", } for filtering with FilterSet def filter_queryset(self, queryset): queryset= Member.objects.filter(member_status__name=self.request.query_params.get('memberStatus')) return super().filter_queryset(queryset) I want to filter according to last member status but when filter with "new", all objects get with queryset. I want to get members filtered by last status. Can you help me, please?