Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
docker-compose) Django+NGINX+gunicorn, not served static files
My project name is mvp. and I want to build docker-compose that django+nginx+gunicorn ├── Dockerfile ├── README.md ├── mvp │ ├── __init__.py │ ├── __pycache__ │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── contents ├── core ├── db.sqlite3 ├── docker-compose.yml ├── mains ├── manage.py ├── media ├── nginx.conf ├── requirements.txt ├── static │ ├── css │ ├── fonts │ ├── images │ ├── js │ └── thirdparty └── templates and Django project's settings.py static code is STATIC_URL = "static/" STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) dockerfile FROM python:3.9 RUN apt-get update && apt-get install -y python3-pip && apt-get clean WORKDIR /usr/src/app/ COPY requirements.txt ./ RUN python -m pip install --upgrade pip RUN pip install -r requirements.txt COPY . . RUN python manage.py collectstatic --noinput RUN python manage.py makemigrations RUN python manage.py migrate nginx.conf user nginx; worker_processes auto; events { worker_connections 1024; } http { server { listen 80; server_name localhost; include mime.types; client_max_body_size 16M; location /static/ { alias /staticfiles/; } location /media/ { autoindex on; alias /media/; } location / { proxy_pass http://mvp:8000; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } } docker-compose.yml version: "3.7" services: nginx: image: … -
How to make test codes JSONField in DRF
I have JSON parse problem. When I use Insomnia(API Testing tool), there is no problem. But my test case, it is. Do you think that my test case code is wrong? {'detail': ErrorDetail(string='JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)', code='parse_error')} models.py class Profile(models.Model): ... passions = models.JSONField(max_length=100, null=True, blank=True) ... tests.py from rest_framework.test import APITestCase class UpdateProfileTestCase(APITestCase): def setUp(self): ... self.url = reverse("profile") def test_can_update_profile(self): data = { "passions": {"data": ["soccer", "tennis"]} } response = self.client.patch( self.url, data, content_type="application/json", ) self.assertEqual(response.status_code, status.HTTP_200_OK) views.py class ProfileViewSet(viewsets.ViewSet): def partial_update(self, request, pk=None): ... serializer = ProfileSerializer(profile, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = [ "passions" ] -
Using FormMixin with DetailView?
In detail page: We want to display form:According docs,We must be used wrapper: from django.views import View class CommentGet(DetailView): model = Article template_name = "article_detail.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["form"] = CommentForm() return context class CommentPost(SingleObjectMixin, FormView): model = Article form_class = CommentForm template_name = "article_detail.html" def post(self, request, *args, **kwargs): self.object = self.get_object() return super().post(request, *args, **kwargs) def form_valid(self, form): comment = form.save(commit=False) comment.article = self.object comment.save() return super().form_valid(form) def get_success_url(self): article = self.get_object() return reverse("article_detail", kwargs={"pk": article.pk}) class CView(View): def get(self, request, *args, **kwargs): view = CommentGet.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = CommentPost.as_view() return view(request, *args, **kwargs) Are we could simply used post method with detailview? class Detail(DetailView): model = ... def post(self): #do something here. -
How to send JSON data from client to Django websocket server
I'm trying to create Django server to receive JSON data fast from external client (sensor), so I decided to go from classic HTTP to consumers. I can add data from admin page and from REST framework page, but I can't send anything via test client (browser extention). Here is my consume.py (based on this repo live-data-drf-channels). # consumers.py from djangochannelsrestframework.generics import GenericAsyncAPIConsumer from djangochannelsrestframework.mixins import ListModelMixin from djangochannelsrestframework.observer import model_observer from . import models, serializers class PostConsumer(ListModelMixin, GenericAsyncAPIConsumer): queryset = models.SensorsValue.objects.all() serializer_class = serializers.SensorsValueSerializer() # permissions = (permissions.AllowAny,) authentication_classes = [] # disables authentication permission_classes = [] async def connect(self, **kwargs): await super().connect() await self.model_change.subscribe() print("Connected") @model_observer(models.SensorsValue) async def model_change(self, message, **kwargs): print("JSON") await self.send_json(message) @model_change.serializer def model_serialize(self, instance, action, request_id=None, **kwargs): print(dict(data=serializers.SensorsValueSerializer(instance=instance).data, action=action.value)) return dict(data=serializers.SensorsValueSerializer(instance=instance).data, action=action.value) async def disconnect(self, message): print("Disconnected") await super().disconnect(message) My test client is connecting and disconnecting correctly, but every time I try to add new data like: {"data": {"timer": 3, "accX": 10.0, "accY": 10.0, "accZ": 10.0, "gyrX": 10.0, "gyrY": 10.0, "gyrZ": 10.0}, "action": "create"} I get this error: Exception inside application: 'request_id' Traceback (most recent call last): File "C:\Users\Natalia\Desktop\djangoProject\venv\lib\site-packages\django\contrib\staticfiles\handlers.py", line 101, in __call__ return await self.application(scope, receive, send) File "C:\Users\Natalia\Desktop\djangoProject\venv\lib\site-packages\channels\routing.py", line 62, in __call__ return … -
what i handel 500 (Internal server error) when url pattern str?
This is my code: project/urls/py: from django.contrib import admin from django.urls import path from todoapp import views urlpatterns = [ # admin page path('admin/', admin.site.urls), # home page path('', views.index, name='todo'), # delete with item_id path('del/<str:item_id>', views.remove, name='del'), ] handler404 = 'todoapp.views.handling404' and app/views.py: def remove(request, item_id): item = get_object_or_404(Todo, id=item_id) item.delete() messages.info(request, "Item Removed!!!") return redirect('todo') index.html: <form action="/del/{{item.id}}" method="POST" style="padding-right: 4%; padding-bottom: 3%;"> {% csrf_token %} <button value="Remove" type="submit" class="btn btn-primary" style="float: right;"> <span class="glyphicon glyphicon-trash"> Remove</span> </button> </form> when I intentionally access eg /del/abc then I get the 500 error instead of the 404 I expected So what's the real problem here? i tried replacing str to int and then i went to /del/abc got the page not found i expected path('del/<int:item_id>', views.remove, name='del'), -
Django best Practice for checking user type using Model
I am working on a Django project where I have Landlord, Agent and Prospect users and I want to check user type whenever a user logs in to determine the user type and redirect user appropriately, but my code does not work properly. Even when a valid user tries to login, the view redirects back to the login page. Some should help a brother. Models: class Landlord(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_verified = models.BooleanField(default=False) def __str__(self): return self.user.username class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_verified = models.BooleanField(default=False) def __str__(self): return self.user.username class Prospect(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='prospect_profile') payment_ref = models.CharField(max_length=100, blank=True, null=True) payment_status = models.BooleanField(default=False) properties = models.ManyToManyField('Property', through='Tenancy') def __str__(self): return self.user.username def become_tenant(self, property): if self.payment_status: tenant = Tenancy.objects.create(tenant=self, property=property, agent=property.agent, landlord=property.landlord) return tenant else: return None class Tenancy(models.Model): tenant = models.ForeignKey(Prospect, on_delete=models.CASCADE) property = models.ForeignKey('Property', on_delete=models.CASCADE) agent = models.ForeignKey('Agent', on_delete=models.CASCADE) landlord = models.ForeignKey('Landlord', on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() def __str__(self): return f'{self.tenant} - {self.property}' class Meta: verbose_name_plural = 'Tenancies' View code: def index(request): user = request.user if user: # Check if User Profile is completed with new image uploaded def profile_complete(profile): return ( profile.full_name is not None and profile.full_name != '' and profile.phone_number is … -
Django: How to use a modal to delete an object?
On the index page for a list of food objects I've included a button to delete an object that is not used. The delete button launches a Bootstrap 5 modal delete form. But when I click the Delete button, the error thrown includes the name of index page. In the code below, where & how can this be fixed? Expected url on delete: .../food/1/delete Page not found: Request URL: http://127.0.0.1:8000/food/foodIndex/1/delete It may be worth noting that the 404 error considers the request to be GET rather than POST [I'm attempting to learn Python & Django by recreating a working PHP project. All of the HTML & javascript comes from that project.] food/urls.py: urlpatterns = [ path('foodIndex/', views.foodIndex, name="foodIndex"), path('<int:id>/edit/', views.foodEdit, name="foodEdit"), path('<int:id>/foodDelete/', views.foodDelete, name = "foodDelete") ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Note: a path('foodIndex/<int:id>/foodDelete/',... does not solve the problem Template included in ".../food/foodIndex.html": {% if allFoods.count > 0 %} {% for food in allFoods %} <tr> <td data-foodid="{{ food.id }}">{{ food }}</td> <td><a class="btn p-0" href='{% url "food:foodEdit" food.id %}'>Edit</a></td> {% if food.used == False %} <td><button id='btn_delete' type="button" class="btn p-0" data-bs-toggle="modal" data-bs-target="#modal-delete" data-bs-foodid='{{ food.id }}' data-bs-foodname='{{ food }}'>Delete</button></td> {% endif %} </tr> {% endfor %} {% else %} <tr> <td … -
Django/Async: When Using {%For Loop%}
I have working javascript in my Django code. The Javascript updates a field by fetching the field and passing the data as json to a view. Then it updates this field in the DB. The html contains a table and every time someone fills a form out a new row in the table is created. Problem: It doesn't work when I use For Loops in my html code. What do I need to add to my javascript to get it to accept the code changes one at a time? . . . <td> <form action=" method='post' "> {%csrf_token%} <textarea name="cust_notes" maxlength="1000" required="" id="cust_notes" class="form-control" value="">{{ x.cust_notes }} </textarea> </form> </td> . . . . <script> const customerNoteInput = document.querySelector('#cust_notes'); const notesEndpointURL = '/customers/notes/' const customerId = {{note.user_cust_id}} let autosaveTimer; customerNoteInput.addEventListener('input', () => { clearTimeout(autosaveTimer); autosaveTimer = setTimeout(autosaveNote, 2000); }) function autosaveNote() { let noteText = customerNoteInput.value let data = { 'user_cust_id': customerId, 'cust_notes': noteText, } // Fetch API fetch(notesEndpointURL, { method: 'post', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{csrf_token}}', }, body: JSON.stringify(data) }) .then(response => { if (response.status == 200) { console.log('Success! Response was 200!') } return response.json() }) .then(data => { console.log(data) }) .catch(error => { console.error('Error: ', error) }) … -
Django: Reverse lookup of optional foreignkey-entry and inclusion in dataset
I would like to compose list of database entries, and corresponding (but not necessarily existing) related entries in another table. The concrete context is a list of events, in which the user should be able to see, whether he already stated his participation (thus has an entry in the database which should be displayed) or not (which would give him a link to a participation form) My models (minimal): class Event(models.Model): title = models.CharField(max_length = 200) #... class Event_Participation(models.Model): EVENT_PARTICIPATION_CHOICES = [ ("Y", "Yes"), ("N", "No"), # few other options ] event = models.ForeignKey(Event, on_delete=models.CASCADE) participation = models.CharField(max_length=1, choices= EVENT_PARTICIPATION_CHOICES) user = models.CharField(max_length=10) #originally another foreign key Ideally, I'm searching for one expression like Event.appendIfExists(Event_Participation)... For template rendering, I was able to query the data, but this doesn't seem elegant and I don't know, how to merge the information inside the template: def event_list(request): e_all = Event.objects.all() #normally filtered part_list = {} for e in e_all: if e.event_participation_set.get(user_id = request.user.id) : p = e.event_participation_set.get(user_id = request.user.id).participation else: p = "X" part_list[e.id]= p context = {"part_list":part_list,"full_event_list":e_all} return render(request, "event_list.html", context) An index-based variable in the template did not work for part_list, and I was not able to extend the queries in … -
Page not found (404) error django for given id in url
I have this path : re_path('likecomment/(?P<comment_id>[0-9]+)/', LikeComment_view , name="LikeComment_page"), and I have the fallowing view: def LikeComment_view(request , comment_id): comment = get_object_or_404(Comment , id=comment_id) if not comment.likes.filter(id = request.user.id).exists(): comment.likes += 1 comment.liked.add(request.user) comment.save() else: comment.likes -= 1 comment.liked.remove(request.user) comment.save() and I generate the url with this code in template: {% url 'LikeComment_page' i.id %} and when I try to enter this url : http://127.0.0.1:8000/likecomment/6/ I get an 404 error . I have the object with id=6 but I still get this error! -
remove ManyToMany from model but still access data
I'm a DJANGO/python novice and I have two models Enqueue and EnqueueGroup. Enqueue has a M2M field: groups = models.ManyToManyField( "EnqueueGroup", related_name="Enqueued", blank=True, ) if I remove the groups field from the Enqueue model, what do I need to do in order to access the data formerly in groups if EnqueueGroups is currently as follows class EnqueueGroup(models.Model): name = models.CharField( max_length=100, null=False, blank=False, ) description = models.TextField( null=True, blank=True ) class Meta: app_label = "test" verbose_name = "Enqueue Group" verbose_name_plural = "Enqueue Groups" def __str__(self): return "Enqueue Group {}".format(self.name) read through the DJANGO M2M and relational database docs. I understand that the relation is called groups in Enqueue and Enqueued in EnqueueGroup. I just dont /get/ how to still access the data. -
The data in a table when this code is refreshed in a django server disappers. How to make it so that the code stays and just new rows in db stay?
I am running django server and when I run the server for the first time the code adds the data to the database. Upon running it a second time the data in the database disappears. How do I have it so that everytime the server runs it just adds the new data to the database? The data in this case is youtube data import sqlite3 def youtube_data(request): # Replace 'YOUR_API_KEY' with your actual YouTube Data API key api_key = 'YOUR_API_KEY' youtube = build('youtube', 'v3', developerKey=api_key) channel_ids = ['CHANNEL_ID_1', 'CHANNEL_ID_2', 'CHANNEL_ID_3'] # Replace with the desired channel IDs videos = [] conn = sqlite3.connect('your_database.sqlite3') # Replace 'your_database.sqlite3' with your SQLite database file path try: for channel_id in tqdm(channel_ids, desc="Extracting Channels"): response = youtube.search().list( part='snippet', channelId=channel_id, maxResults=10 ).execute() for item in tqdm(response.get('items', []), desc="Extracting Videos"): video_id = item.get('id', {}).get('videoId') if video_id: # Check if the video already exists in the database cursor = conn.cursor() query = "SELECT * FROM youtube_video WHERE video_id = ?" cursor.execute(query, (video_id,)) result = cursor.fetchone() if not result: try: video_data = youtube.videos().list( part='snippet, statistics, contentDetails', id=video_id ).execute() snippet = video_data['items'][0]['snippet'] statistics = video_data['items'][0]['statistics'] content_details = video_data['items'][0]['contentDetails'] transcript = get_video_transcript(youtube, video_id) insert_query = """ INSERT INTO youtube_video (published_at, title, … -
Why N+1 problem is enormous in DRF and how can I solve it?
I have site that was powered on vanilla django framework. I created a custom manager for my models to reduce N+1 problem and it worked very well. But when I moved to DRF, I just can't handle it with usual select_related and prefetch_related methods. Number of queries has increased dramatically. For example, here is my UserPostListView that should display 10 user's posts: class UserPostListView(generics.ListAPIView): serializer_class = PostSerializer comment_serializer_class = CommentSerializer def get_queryset(self): slug = self.kwargs['slug'] return Post.objects.detail().filter(author__slug=slug).order_by('-post_date') def list(self, request, *args, **kwargs): response = super().list(request, *args, **kwargs) data = response.data posts = data['results'] for post in posts: comments = Comment.objects.detail().filter(post_id=post['id'], comment_to_reply=None)[:5] serialized_comments = self.comment_serializer_class(comments, many=True).data post['comments'] = serialized_comments data['results'] = posts response.data = data return response It generates around 130 queries. I tried move this comment functionality to the serializer. It didn't help at all. Ideally I see it working smth like that: class PostSerializer(TaggitSerializer, serializers.ModelSerializer): author = UserSerializer(read_only=True) tags = CustomTagListSerializerField(required=False, allow_empty=True, allow_null=True) connected_subs = UserFilteredSubscriptionsField(many=True, required=False) post_media = PostMediaSerializer(many=True, required=False) likes_count = serializers.SerializerMethodField() views_count = serializers.SerializerMethodField() comments_count = serializers.SerializerMethodField() calculate_grid = serializers.SerializerMethodField() def get_comments(self, instance): comments = Comment.objects.detail().filter(post=instance, comment_to_reply=None)[:5] comments_serializer = CommentSerializer(comments, many=True) return comments_serializer.data def to_representation(self, instance): representation = super().to_representation(instance) representation['comments'] = self.get_comments(instance) return representation But actually … -
Why page renders slowly (about 2s)? Django
Rendering page takes too long (about 2s) Even if i return dummy data (without querying) page renders slowly. But when i return empty dict tasks_by_day it takes only ~150ms to load page. My question is why it takes so much time to process so small amount of data and how can I fix this? Here is my view code: def tasks(request): tasks = Task.objects.filter(owner=request.user.id) tasks_by_day = { "MONDAY" : [tasks[0]], "TUESDAY" : [tasks[1]], "WEDNESDAY": [tasks[2]], "THURSDAY": [tasks[3]], "FRIDAY": [tasks[4]], "SATURDAY": [tasks[5]], "SUNDAY": [tasks[7]] } return render(request, "todo/tasks.html", {"tasks_by_day": tasks_by_day}) Here is my model code: class Task(models.Model): # DAY_OF_THE_WEEK_CHOICES, STATUS_CHOICES - constants day_of_the_week = models.CharField( max_length=10, choices=DAY_OF_THE_WEEK_CHOICES, default=default_day ) status = models.CharField( max_length=2, choices=STATUS_CHOICES, default=NOT_COMPLETED ) task_text = models.CharField(max_length=200) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) I've measured time that needed to execute tasks function - it's around 110ms. -
django : How can i check if an object is exist in a many-to-many relation?
I have a model named Post that has some fields like this : class Post(models.Model): title = models.CharField(max_length=500) slug = models.SlugField(allow_unicode=True , unique=True , null=True , blank=True) likes = models.ManyToManyField(User , blank=True , help_text="amount of likes") likes_count = models.IntegerField(default=0 , help_text="amount of likes") def __str__(self): return self.title and I have a view that needs to check if the user is in "likes" relation and do some stuff . But I don't know what to do ! this is my view: def Like_view(request , slug): post = get_object_or_404(Post , slug=slug) if not request.user in post.likes: post.likes.add(request.user) post.likes_count += 1 post.save() else: post.likes.remove(request.user) post.likes_count -= 1 post.save() -
HTMX form not getting file upload succesfully with django
I have this form: class FormCotacao(forms.Form): descricao = forms.CharField( label = 'Descrição', max_length = 200, required = True ) valor1 = forms.FloatField( label = "Valor 1 (R$)", required = True ) orcamento1 = forms.FileField( label = "Orçamento 1", widget = forms.FileInput(attrs={'accept': '.pdf, .xls, .xlsx'}), required = True ) This htmx: {% load crispy_forms_tags %} <form method="post" enctype="multipart/form-data" hx-enconding="multipart/form-data" action=""> {% csrf_token %} {{ form|crispy }} <input type="hidden" name="id" value="{{ orcamento.id }}"> <input type="hidden" name="acao" value="addItemCotacao"> <button type="button" class="btn btn-secondary" hx-get="{% url 'visualizar-orcamento' id %}" hx-swap="innerHTML" hx-target="#itemsAdicionados">Cancelar</button> <button type="submit" hx-post="{% url 'item-cotacao' id %}" hx-swap="innerHTML" hx-target="#itemsAdicionados" class="btn btn-primary" name="addItemCotacao">Salvar item</button> </form> And this is the view to which it's directed: def orcamentoCotacao(response, id): usuario = response.user orcamento = Orcamento.objects.get(id=id) if orcamento.aprovado != True: if response.method == 'POST': form = FormCotacao(response.POST) arquivos = response.FILES if form.is_valid(): pass else: form = FormCotacao() context = { 'form': form, 'id': id } return render(response, "main/partials/item-cotacao.html", context) When the user uploads files in the form, they show up in response.POST but, for some reason, there's nothing in response.FILES. What might be the problem? -
Ubuntu Django WebSocket connection to ... failed
i am new to this field, i tried to run websocket in ubuntu but it gives error i followed the instructions on this page(enter link description here) i don't understand where the error is located. -
How to run a Jupyter Notebook tool in a server
I have created data analysis tool using Jupyter Notebook. Currently, I installed python+Jupyter Notebook in virtual machine and my teammates login to VM to use the tool. But, it’s limiting the users as only one person can login at a time. So, moving forward , I want to keep tool in a server so n number of users can use it at a time. Note: I am from non-it background. Except coding and logic building, don’t have any knowledge on server, web application etc. currently, I built and developed code in Jupyter notebook.. once Jupyter Notebook finishes running user saves notebook as html report as notebook has all plots and statistical tables. I see some options like streamlite, mercury but I didn’t get any clear idea for my problem. I want to run Jupyter Notebook in the backend and save it as html report but users should run from their own laptops without login to virtual machine or installing anaconda distribution on their laptops -
Passing Correct POST request from React component, but Django view is receiving an empty dictionary
In my application, users can play songs and the play count is supposed to get updated in the backend. When I pass the song ID of the song that needs it's play count incremented, it is being passed as None. When I hardcode a song ID into the Django view, the plays are incremented like it's supposed to, but when I try to use the song ID that is passed from the frontend, it passes None. This is the where the handlePlay function is called, which handles the play count update <audio controls src={`/media/${song.file}`} data-song-id={song.id} onPlay={() => handlePlay(song.id)} ></audio> This is the handlePlay function which makes the request to the backend. Both of the console.log(songID) lines are correctly logging the song ID in the browser console. function handlePlay(songID) { console.log(songID) axios .post('/api/update-plays/', { "songID": songID }) .catch((error) => { console.log(error); }); console.log(songID) } This is the updatePlays Django view which gets the song ID, finds the song, then increments the play count. When I print(request.POST), it prints an empty dictionary. @csrf_exempt def updatePlays(request): print(request.POST) if request.method == "POST": songID = request.POST.get("songID") song = Song.objects.get(id=songID) song.plays += 1 song.save() return JsonResponse({"song": song}, safe=False) return JsonResponse({"error": "error"}) When I hardcode the actual … -
Usage of .to_representation() in django-rest-framework resulting a slow response for a large(1000 records) list
I have an endpoint www.exapmle.com/list?page_size=1000 sample code looks like - class TestViewSetV10(ViewSet): queryset = Test.objects.all()#.order_by("pk") serializer_class = TestSerializerV10 filterset_class = TestFilterV10 class TestSerializerV10(serializers.ModelSerializer): #pass Backend serializers is serializers.ModelSerializer, which is calling .to_representation() in the list. This is leading to a slow response, taking around 2 min. Is there any way to optimize the above-mentioned case? -
How to fetch relation table one to another via serializer? django
I have two serializers for two models (Blog and User). This is one to many relation, User can have one or more Blog. But a Blog should belong only to one User. The goal is I want to include blogs model if I will fetch the user. vice-versa API: /user/1 response: { name: 'John Doe', blogs: [ <========== include { id: 1, title: 'First Blog', }, ... so on, so forth ] ... more field } The current situation is, the UserSerializer can incude the blogs. But in BlogSerializer it cannot include the user since "BlogSerializer" is not defined. class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog fields = "__all__" user = UserSerializer(many=True, read_only=True) class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = "__all__" blog = BlogSerializer(many=True, read_only=True) Do you have idea how to fix or achieve this? I'm new in Django, I would appreciate any comments or suggestions. -
Django: query parameters in the middle of the url - how?
This is a Django project and our project lead has come up with following URL-schema: <some-url>/avail?region_id=1&date=2021-01-01 ... get avail-data for given region and date <some-url>/cust?id=1/regs/ ... meaning we want the regions of customer with id 1 Now for all I know this is not really the way you normally would do it in Django, where you would define an URL as something like: <some-url>/cust/1/regs/ Furthermore I read that "query parameters are usually handled in the view" with request.query_params.get(). But if we go forward with this URLs-schema of having query parameters - even in the middle of the URL as in the 2nd case - what would be the best way of implementing it? How to set up urls.py? Another option would be to convince our lead of a better way - a more Django-ish way? How would we best define these URLs to adhere to Django conventions? -
`ValueError: %s has host bits set` while using InetAddressField in django model
I am using InetAddressField from django.netfields to store IP address in DB. I followed steps from this answer. I have following model: class MyModel(models.Model): // some fields ... ip_address = InetAddressField() objects = NetManager() I have two REST end points, one with MyModel.objects.exclude(ip_address__net_contained=subnet_mask) and another with MyModel.objects.filter(ip_address__net_contained=subnet_mask) where subnet_mask is input from UI. Now the thing is all bits for host need to be zero in subnet mask. In, 10.0.0.2/24, its 2. So it gives error as follows: ERROR [2023-06-15 20:49:41,326] [django.request] [log] [Process:2090] [Thread:139874097665792] Internal Server Error: /my_module/my_rest_endpoint Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/myapp/my_module/views.py", line 484, in my_rest_endpoint .exclude(ip_address__net_contained=subnet_mask) File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 899, in exclude return self._filter_or_exclude(True, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 908, in _filter_or_exclude clone.query.add_q(~Q(*args, **kwargs)) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1290, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1318, in _add_q split_subq=split_subq, simple_col=simple_col, File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1251, in build_filter condition = self.build_lookup(lookups, col, value) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1116, in build_lookup lookup = lookup_class(lhs, rhs) File "/usr/local/lib/python3.6/site-packages/django/db/models/lookups.py", line 20, in __init__ self.rhs = self.get_prep_lookup() File "/usr/local/lib/python3.6/site-packages/netfields/lookups.py", … -
Django migration issues when changing model field
we have a Model with a field such as from core import snippets from modelcluster.fields import ParentalKey, ParentalManyToManyField tags = ParentalManyToManyField( snippets.Tag, blank=True, ) we have changed the snippets import from from readiness import snippets to from core import snippets where snippets is just the same but moved to the core app getting migration errors tags was declared with a lazy reference to 'readiness.tag', but app 'readiness' isn't installed. -
Having issues running py, python3, python etc. Environment Variables correct as far as I can tell
I have used Django in the past but just got this new computer and was running though the Django tutorial a refresher. Having issues running the python manage.py runserver command. I get "Python was not foun; run....." error. I've tried py, python, python3. I have made sure my path varibles are set correctly. Not really sure what to try next. The only thing that is different on this PC than other computers Ive used is my username has been set as (username.computername) not really sure but it has messed with some code I use to get the user for file directories. I added a path variable with my full path instead of the %USERPROFILE% incase this was effecting something. Path Varibles Image of CMD I have also looked at the "Manage App Execution Aliases" and python is clicked to on. Thanks in advance for any help here is what I'm getting from CMD: `C:\Users\jlr.DESKTOP-4N4QMUN\Documents\GitHub\Tracker_Reporting>py --version Python 3.11.4 C:\Users\jlr.DESKTOP-4N4QMUN\Documents\GitHub\Tracker_Reporting>python --version Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases. C:\Users\jlr.DESKTOP-4N4QMUN\Documents\GitHub\Tracker_Reporting>python3 --version Python was not found; run without arguments to install from the Microsoft Store, or disable …