Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Graphql Wrapper for Rest APIs with Django
Trying to implement wrapper for existing REST APIS using Django graphQL. Found similar one in JS but not in Django. https://graphql.org/blog/rest-api-graphql-wrapper/ Could anyone please suggest if there is a GraphQL Django wrapper for REST calls. Haven't found in documentation either -
deleting object by senting two id's in django by ajax call
am trying to delete an object in django via ajax call.I need to pass two id's.When I perform delete the id's are not passing .I get an url like 127.0.0:8000/delete// what is wrong with my script and views.py?? urls.py path('delete/<int:id1>/<int:id2>',views.delete,name="delete") views.py def delete(request,id1,id2): if request.method == "POST": obj=ShopUserMapping.objects.get(id1=id1,id2=id2) obj.delete() return render(request,"delete_mapping.html",{'obj':obj}) delete.html <form method="post" id="form_delete"> {% csrf_token %} <input type="hidden" id="id1" name="id1" data-value="{{obj.id1}}"> <input type="hidden" id="id2" name="id2" data-value="{{obj.id2}}"> Are you sure want to delete this item? <button type="submit" class="btn btn-danger login-btn" id="delete">Delete</button> </form> delete.js $("#form_delete").submit(function(event){ event.preventDefault();//prevent the form submitting via browser var formData=new FormData(); var id1=$("#id1").data("value"); var id2=$("#id2").data("value"); formData.append('csrfmiddlewaretoken','{{ csrf_token }}'); $.ajax({ //submit a request to the backend(server) using ajax url:'delete/'+ id1 + '/' + id2,//server script to process data type:'POST', data:new FormData(this), processData:false, contentType:false, success:function(res) { console.log("Successfully Deleted"); }, error:function(errResponse) { console.log(errResponse); } }); return false;}); -
Django: How Can I get 'pk' in views.py when I use class based views?
I'm writhing an app with class based views. I need to receive 'pk' in my views.py file when I load my page using generic DetailView. My urls.py file: from django.urls import path from . views import HomeView, ProfileView, AddPetView, EditPetView, DeletePetView, PetProfileView urlpatterns = [ ... path('profile/pet/<int:pk>', PetProfileView.as_view(), name='pet_profile'), path('', HomeView.as_view(), name='home'), ] My views.py file: from django.shortcuts import render from django.views.generic import TemplateView, ListView, UpdateView, CreateView, DeleteView, DetailView from django.urls import reverse_lazy from . models import Pet class PetProfileView(DetailView): model = Pet template_name = 'pet_profile.html' #key = Pet.objects.values_list('birth_date').get(pk=1) I need to extract from database birh_date column for this specific pet. How to get this pk=? when I load pet_profile page? I'm not sure if I can describe the case well. If something is not clear, ask me. I will try to explain again. Thanks in advance, -
Django admin panel does't work correctly on Debug=False on production
I can't add or delete items when Debug = False on production. On Debug = True everything is fine. Screenshot when Debug = True: Screenshot when Debug = False: Code from models.py: class Portfolio(models.Model): miniaturka=models.FileField(blank=False) logo=models.FileField(blank=True) nazwa=models.CharField(max_length=300, blank=False) link=models.CharField(max_length=400, blank=True) grafika=models.FileField(blank=True) grafika_mobilna=models.FileField(blank=True) opis=models.TextField(blank=True) class Meta: verbose_name="Portfolio" verbose_name_plural="Portfolio" def __str__(self): return self.nazwa class PortfolioRow(models.Model): portfolio = models.ForeignKey(Portfolio, default=None, on_delete=models.CASCADE) portfolioRowType = models.ForeignKey(PortfolioRowType, null=True, blank=True, on_delete=models.CASCADE) photo1 = models.FileField(blank=True) photo2 = models.FileField(blank=True) def __str__(self): return self.portfolio.nazwa class PortfolioVideo(models.Model): portfolio = models.ForeignKey(Portfolio, default=None, on_delete=models.CASCADE) link = models.CharField(max_length=300) def __str__(self): return self.portfolio.nazwa Code from admin.py: from typing import List from django.contrib import admin from main.models import * class PortfolioRowAdmin(admin.StackedInline): model = PortfolioRow class PortfolioVideoAdmin(admin.StackedInline): model = PortfolioVideo @admin.register(Portfolio) class PortfolioAdmin(admin.ModelAdmin): inlines = [PortfolioRowAdmin, PortfolioVideoAdmin] class Meta: model = Portfolio -
is there a way to use something like p=product.objects.filter(category=home)?
I have some categories that I can filter them by primary key like this : p=product.objects.filter(category=2) but I do not want to bother my self with primary keys I want to filter with exact name of the category not primary key. I have categories like this : image is there a way to use something like p=product.objects.filter(category=home) ? models: class category(models.Model): name=models.CharField(max_length=255, db_index=True) def __str__(self): return self.name class product(models.Model): category = models.ForeignKey(category, related_name='products',on_delete=models.CASCADE) image=models.CharField(max_length=500) description=models.CharField(max_length=500) price=models.CharField(max_length=50) buy=models.CharField(max_length=100) -
Upload document to all the related inquiries
So in my application there is something called Inquiry which also has related_inquiries associated with it. so in my model Inquiry i have a field related_inquires which is m2m field to self i.e is same model Inquiry have file upload page linked to this inquiry, I need a checkbox on my file upload page which should be displayed only if the inquiry has related_inquiries when checked that it should upload file to all the related_inquiries. class Inquiry(models.Model): name = models.Charfield(max_length = 255) related_inquiries = models.ManytoManyField('Self', null=True) file = models.FileField() class InquiryFileUpload(APIView): queryset = Inquiry.objects.all() lookup_url_kwarg = 'inquiry.id' def post(self, request, *args, **kwargs): '''code''' class InquiryModel(forms.ModelForm): upload_to_related_inquiries = models.Booleanfield() class Meta: model = Inquiry fields = '__all__' -
bulk_create , ignore_conflicts=True is not working in django?
ps_data=[PassengerDetail(name=j.get(name) for i, j in enumerate(ps)] PassengerDetail.objects.bulk_create(objs=ps_data, ignore_conflicts=True) Here I bulk create a django objects. I tried to bulk create objects without duplicate entries in db. But this isn't working. Where i get problem? -
django taking post request as get. django forms not working properly
django is taking my post request and get and the action of the form is returning the wrong url over and over. (my html template):- <div class="flex flex-col text-center w-full mb-12"> <h1 class="sm:text-3xl text-2xl font-medium title-font mb-4 text-gray-900">Change Password</h1> <p class="lg:w-2/3 mx-auto leading-relaxed text-base">Change Your Accounts Password.</p> </div> <div class="lg:w-1/2 md:w-2/3 mx-auto"> <form action="/profile/change-password/" method="post"> {% csrf_token %} {{ form|crispy }} <div class="p-2 w-full"> <button class="flex mx-auto text-white bg-indigo-500 border-0 py-2 px-8 focus:outline-none hover:bg-indigo-600 rounded text-lg">Change</button> </div> </form> </div> </div> (views.py):- def change_password(request): if request.method == "POST": form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): form.save() messages.info(request, "Password Changed Succesfully!") update_session_auth_hash(request, form.user) return redirect("/profile/") else: messages.info(request, "Please Try Again.") return redirect("/change-password/") else: form = PasswordChangeForm(user=request.user) return render(request, "change_password.html", {'form': form}) (urls.py):- urlpatterns = [ path("", profile), path("edit-profile/", edit_profile), path("change-password/", change_password), ] Please help -
Django F expression in boolean expression raises a TypeError exception
I am using Django 3.2 in a project. I have a method that compares the value of a field to an integer (see code below). Django throws an error (which makes sense because of the different types). My question is - how else am I to implement this check (whilst using F expression to avoid race conditions)? Code def bookmark(self, actor, note=''): if self.can_bookmark(actor): ct, object_id = self.get_content_info() found_objects = self.bookmarks.filter(content_type=ct, object_id=object_id, actor=actor) if found_objects: # We are unbookmarking found_objects.delete() self.bookmarks_count = F('bookmarks_count') - 1 # Sanity check (-ve value may occur if Db has been manipulated manually for instance) if self.bookmarks_count < 0: # <- Barfs here self.bookmarks_count = 0 if self.bookmarks_count == 0: # <- Barfs here too self.last_bookmarked = None self.save() return True else: # Create bookmark object and save it if self.create_and_increment(self.bookmarks, actor, note=note): self.bookmarks_count = F('bookmarks_count') + 1 self.last_bookmarked = timezone.now() actionable_object = self.actionable_object self.save() self.refresh_from_db() item_bookmarked.send(sender= actionable_object.__class__, instance=actionable_object, event_type = BOOKMARK, actor=actor) return True else: return False else: # do nothing return False [[Edit]] Here is the full traceback: Traceback (most recent call last): File "<console>", line 1, in <module> File "/path/to/myproj/models.py", line 455, in bookmark if self.bookmarks_count < 0: TypeError: '<' not supported … -
Recovered XML File Error and File contents shows some numeric-character combinations
Due to Crash of My OS, I Have lost some files, I need to recover some important xml files. After using some Recovery Softwares, i got the file restored, but in all recovery softwares, file contents seems like below. Its not XML. Anyone can help me to convert it to xml 582b 11f7 624f 4c90 7094 9d7d 65b2 ca2d 96b5 8d6c 5357 5ac4 4716 de88 d540 deae 6950 0480 d84d 88ba 8cd2 0938 480b deb5 9492 ef16 5d44 ff01 828d ceef 38be 4ed3 5ce1 a292 a0af a837 8d8c 910a 82c1 c9f0 e936 e889 d112 8da0 30b5 8ee5 2a10 6487 e6b5 0080 2b4f 73c9 e2dd 1d0e 8189 c0a6 28c2 0c32 b08e 95dc d17a ebd8 0f97 ffdc add5 86dd c1ad c438 5953 a77d c842 f0a6 5aba 9669 fb04 6eb6 ded5 ee48 d882 62e3 16a2 2441 a368 632a 619d 3e08 7f92 b735 78da 4cdf c435 d58f df02 9f07 75be 3548 996d 78d2 dd08 a2d9 dda3 d497 9e8e 1a88 cbff 48da de46 db44 25f8 5562 e9ad 4ba7 2f67 53f9 1582 19ea d48a 79f5 b59d da2d 3a08 7a9c dd62 60e9 45f1 6348 4676 550a d122 539b 6269 9b21 05d4 cb42 cd19 f076 de29 a1ae 0c06 623f 8225 83b6 0a0e a95b................... -
(DRF) ValueError: Field 'id' expected a number but got ''. Unable to pass in id to the url
I am writing a custom function to add favourite to Thread model. The function should expect an id pass in to the get_object_or_404. @csrf_exempt def add_favourites(request, id, *args, **kwargs): thread = get_object_or_404(Thread, id=id) if request.method == 'POST': if thread.liked.filter(username=request.user.username).exists(): thread.liked.remove(request.user.username) else: thread.liked.add(request.user.username) and I have my url.py like this to receive an id from axios url: path('api/public/favourites/<int:id>/', add_favourites, name='add_favourites'), However, when I perform the axios post request like this: axiosInstance.post(`api/public/favourites/4/`) It should be receiving id = 4, but it always return error: (DRF) ValueError: Field 'id' expected a number but got ''. Anybody has an idea whats wrong with my code? Much Thanks. -
Django pagination has_previous and has_next methods doesn't work
I'm using pagination in Django 1.11. But when I use has_next and has_previous it returns false everytime. Don't print anything. I'm sure that there is previous and next pages. In views I'm using TableView which is like ListView. Here is my code: <div class="pagination"> <span class="step-links"> {% if customers.has_next %} <p>HAS NEXT</p> {% endif %} {% if customers.has_previous %} <p>HAS PREVİOUS</p> {% endif %} </span> </div> views.py class TableView(ExportMixin, SingleTableView): model = Customer table_class = CustomerTable template_name = 'admin_pages/user_admin_page.html' context_object_name = 'customers' paginate_by = 3 *I'm using tableview just for export table. -
Django doesn't load a default picture. I have MEDIA root connected to urls
So I want the imageField to load a default picture when one is not uploaded by user. When I upload something in the imageField form, they end up in the correct folder. When I want it to load a default pic, it simply doesn't show up. I checked online, but the solutions I found point to things that I already have done (I think) right. models.py: class Ingredients(models.Model): type = models.IntegerField(choices=ingredientType) name = models.CharField(max_length=100) image = models.ImageField(default='no-photo-available-hi.png') def __str__(self): return self.name class DrinkRecipe(models.Model): name = models.CharField(max_length=100) ingredients = models.ManyToManyField(Ingredients) utensil = models.IntegerField(choices=requiredUtensil, default=0) preparation = models.CharField(max_length=1000) image = models.ImageField(default='no-photo-available-hi.png') def __str__(self): return self.name def __unicode__(self): return self.ingredients.name forms.py: class DrinkForm(forms.Form): name = forms.CharField(max_length=100, label="Name:") utensil = forms.ChoiceField(choices=requiredUtensil, label="Required utensil:") ingredients = forms.ModelMultipleChoiceField( queryset=Ingredients.objects.all(), widget=forms.CheckboxSelectMultiple() ) preparation = forms.CharField(widget=forms.Textarea) image = forms.ImageField(required=False) class IngredientForm(forms.Form): name = forms.CharField(max_length=100, label="Ingredient name") type = forms.ChoiceField(choices=ingredientType) image = forms.ImageField(required=False) settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/shakerApp/media') project's (not app's) urls.py: urlpatterns = [...] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Project's directory: |Project |Project folder |App folder |Static |AppName |media |no-photo-available-hi.png |venv -
how to see OperationProxy attributes using zeep
from requests import Session from zeep import Client, Settings from zeep.plugins import HistoryPlugin from zeep.transports import Transport session = Session() session.verify = True transport = Transport(session=session) history = HistoryPlugin() wsdl_url = 'https://argusgate2.fitorf.ru/debug/ws/uz3?wsdl' settings = Settings(strict=False, xml_huge_tree=True) client = Client( wsdl_url, transport=transport, settings=settings, plugins=[history]) logging.getLogger("zeep").propagate = False parametrs = { "a": "something", } def send_request(cl, **parametrs): r = cl.service.Request91.input(**parametrs) return r enter code here a = send_request(client, **parametrs) print(a) When i sending this request it shows this error message: AttributeError: 'OperationProxy' object has no attribute 'input' . How to identify which attributes has OperationProxy -
is my problem from regex or youtube_dl ? the high quality videos downloaded without sounds
i have published a site for online youtube video downloader , { https://ytv.pythonanywhere.com } , everything is working Good But if i choise to download the video with high Resolution the video will be without sounds , here's my views enter image description here enter image description here -
Django MySQL charset setting is not working, utf8mb4 changed to utf8
My setting file is looks like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # ... 'OPTIONS': { 'charset': 'utf8mb4', } }, } After some migrates(like python manage.py migrate zero, python manage.py reset_db..), the MySql encoding changed from utf8mb4 to utf8. docker volume ls docker volume rm -f xx # this not work, say "xx volume is in use" # use this one cleard the volume. docker-compose -f xx.yml down --volumes I use above command to recreate docker volumes fix it, But I wanna know why, so here is the question. My docker-compose file looks like: # ... services: # ... db: image: mysql:5.7.18 command: --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci # ... -
I am trying to deploy a website built with Django in Gitpod to Heroku. I am getting the below error message when the application starts
I am new to website development and this is the first time using Django. As per the title when I open the app in Heroku I get the below log in my Gitpod terminal when I use Heroku Logs. Is anyone able to tell where I have gone wrong? Thanks in advance for looking. 2022-06-08T05:16:59.043815+00:00 heroku[web.1]: State changed from crashed to starting 2022-06-08T05:17:07.475383+00:00 heroku[web.1]: Starting process with command gunicorn fitness_subscription_app.wgsi:application 2022-06-08T05:17:09.218098+00:00 app[web.1]: [2022-06-08 05:17:09 +0000] [4] [INFO] Starting gunicorn 20.1.0 2022-06-08T05:17:09.218770+00:00 app[web.1]: [2022-06-08 05:17:09 +0000] [4] [INFO] Listening at: http://0.0.0.0:23902 (4) 2022-06-08T05:17:09.218849+00:00 app[web.1]: [2022-06-08 05:17:09 +0000] [4] [INFO] Using worker: sync 2022-06-08T05:17:09.225947+00:00 app[web.1]: [2022-06-08 05:17:09 +0000] [10] [INFO] Booting worker with pid: 10 2022-06-08T05:17:09.230090+00:00 app[web.1]: [2022-06-08 05:17:09 +0000] [10] [ERROR] Exception in worker process 2022-06-08T05:17:09.230091+00:00 app[web.1]: Traceback (most recent call last): 2022-06-08T05:17:09.230091+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2022-06-08T05:17:09.230092+00:00 app[web.1]: worker.init_process() 2022-06-08T05:17:09.230092+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_process 2022-06-08T05:17:09.230092+00:00 app[web.1]: self.load_wsgi() 2022-06-08T05:17:09.230093+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2022-06-08T05:17:09.230093+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2022-06-08T05:17:09.230093+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2022-06-08T05:17:09.230094+00:00 app[web.1]: self.callable = self.load() 2022-06-08T05:17:09.230094+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2022-06-08T05:17:09.230094+00:00 app[web.1]: return self.load_wsgiapp() 2022-06-08T05:17:09.230095+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp 2022-06-08T05:17:09.230095+00:00 … -
Docker-compose - Cannot connect to Postgres
It looks like a common issue: can't connect to Postgres from a Django app in Docker Compose. Actually, I tried several solution from the web, but probably I'm missing something I cannot see. The error I got is: django.db.utils.OperationalError: could not translate host name "db" to address: Try again Where the "db" should be the name of the docker-compose service and which must setup in the .env. My docker-compose.yml: version: '3.3' services: web: build: . container_name: drf_app volumes: - ./src:/drf links: - db:db ports: - 9090:8080 env_file: - /.env depends_on: - db db: image: postgres:13-alpine environment: - POSTGRES_HOST_AUTH_METHOD=trust - POSTGRES_USER=myuser - POSTGRES_PASSWORD=mypass - POSTGRES_DB=mydb volumes: - postgres_data:/var/lib/postgresql/data/ ports: - 5432:5432 volumes: postgres_data: My .env: SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=mydb SQL_USER=myuser SQL_PASSWORD=mypass SQL_HOST=db #this one should match the service name SQL_PORT=5432 As far as I know, web and db should automatically see each other in the same network, but this doesn't happens. Inspecting the ip address with ifconfig on each container: django app has 172.17.0.2 and the db 172.19.0.2. They are not able to ping each other. I really cannot figure out the issue, so am I missing something? -
What is the best way to achieve cross database relationships in django?
What is the best way to achieve cross database relationships in django? Are there any simple examples? -
Django. How to pass a value to CharField with choices in forms?
I want to test post request in my update view. In order to do it I have to fill all fields in corresponding form. After I pass data for all fields the form has one error and it's this CharField with choices parameter. The error message: .......<ul class="errorlist"><li>user<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li><li>position<ul class="errorlist"><li>Select a valid choice. CEO is not one of the available choices.</li></ul></li></ul> The model: class Employee(models.Model): SALES_MANAGER = 'SM' CHIEF_SALES_MANAGER = 'CSM' CEO = 'CEO' POSITION_CHOICES = ( (SALES_MANAGER, 'SM'), (CHIEF_SALES_MANAGER, 'CSM'), (CEO, 'CEO'), ) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) user = models.OneToOneField(User, on_delete=models.CASCADE) position = models.CharField(max_length=255, choices=POSITION_CHOICES, default= SALES_MANAGER, null=True, blank=True) reports_to = models.ForeignKey('self', on_delete=models.DO_NOTHING, null=True, blank=True) birthday = models.DateField() hire_date = models.DateField() address = models.CharField(max_length=255) phone_number = models.CharField(max_length=15) pfp = ResizedImageField(size=[350, 350], upload_to='media/profile_pics/user.id/', blank=True,default='media/profile_pics/default_pfp.png') The view: class EmployeesUpdateView(LoginRequiredMixin, UpdateView): model = Employee template_name = 'employees/employee_update.html' form_class = EmployeeUpdateForm The form: class EmployeeUpdateForm(forms.ModelForm): class Meta: model = Employee fields = ['first_name', 'last_name', 'user', 'position', 'reports_to', 'birthday', 'hire_date', 'address', 'phone_number', 'pfp'] The test: def test_updateview_post(self): self.client.force_login(user=self.test_user) response = self.client.post(reverse('employees:employee-update', kwargs={'pk': self.test_employee.pk}), { 'first_name':'John', 'last_name': 'Smith', 'user': self.test_user, 'position': 'CEO', 'birthday': date(year=1995, month=3, day=20), 'hire_date': date(year=2019, month=2, day=15), 'address':'LA', … -
binded data tables for leaflet maps in django
I want to bind a leaflet map to a according datatable using django. I've just googled it and not sure if I've used the correct buzz words. At the end I want to interact in a first shot, so that: clicking on the data table element zooms to leaflet map feature and the bounds of displayed features on maps - filters the data table For displaying the features on the map, I'm using geojson. What are the best practises for that use case? my map.js handler const attribution = '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' const map = L.map('map', { center: [52.39886, 13.06566], zoom: 10 }); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: attribution }).addTo(map); const markers = JSON.parse(document.getElementById('markers-data').textContent); let feature = L.geoJSON(markers, { onEachFeature: function (feature, layer) { if(feature.properties.kategorie == 1){ layer.setStyle({color :'black'}); } else { } layer.bindPopup('<strong>Parkname: </strong>'+layer.feature.properties.name.toString() + '<br /> <strong>Kategorie: </strong>' + layer.feature.properties.kategorie.toString()); } }).addTo(map) my views.py from django.shortcuts import render import json import logging from django.views.generic.base import TemplateView from django.core.serializers import serialize from .models import NotusProjekte from django.db.models import Q logger = logging.getLogger(__name__) class MarkersMapView(TemplateView): """Markers map view.""" template_name = "map.html" def get_context_data(self, **kwargs): """Return the view context data.""" query = NotusProjekte.objects.using('spatial').filter(Q(kategorie=1) | Q(kategorie=2)) context = super().get_context_data(**kwargs) context["markers"] = json.loads(serialize("geojson", query)) … -
Using F object in Django filteredRelation condition
I'm trying to use Django (2.2) filteredRelation with something like that: products = Product.objects.annotate( valid_stocks=FilteredRelation( 'stocks', condition=( Q(stocks__nb_ordered__lt=F('stocks__nb_total')) ) ) ) Seems like Django can't evaluate this query and I'm getting the following error: ProgrammingError: missing FROM-clause entry for table "t7" LINE 1: ...ce_produce"."id" = valid_stocks."produce_id" AND (T7."custom... Note that it works like expected by replacing the F object by some integer. Q(stocks__nb_ordered__lt=10 This is weird because this limitation is not documented, see https://docs.djangoproject.com/en/2.2/ref/models/querysets/#filteredrelation-objects Does anyone have an idea about how to solve this problem ? -
Django Order_by Retrieves same data thrice
I have a model called as Annual. When I am retrieving the annual report from database after using order_by on queryset same data is retrieved thrice. Here's my views.py class AnnualView(APIView): serializer_class = AnnualSerializer def get(self, request): queryset = Annual.objects.all().order_by('-group__student__level', '-group__gName') print(queryset) serializer = self.serializer_class(queryset, many=True) for serialized_data in serializer.data: current = serialized_data.get('current') for data in current: data.get('topic')['current']= data.get('current') data.get('category')['topic']= data.get('topic') data.pop('topic') data.pop('current') context = { "Status": 200, "payload": serializer.data } return Response(context) Here's my Model.py class Group(models.Model): id = models.AutoField(primary_key = True) student = models.ManyToManyField(Students, related_name="student_groups", default="No Student") gName = models.CharField(max_length=10) teacher = models.ForeignKey(User, related_name="GroupTeacher", on_delete=DO_NOTHING) speciality = models.ForeignKey(SubjectSpeciality, on_delete=models.DO_NOTHING, blank=True) subject = models.ForeignKey(Subject, on_delete=models.DO_NOTHING, blank=True) class AnnualCurrentPL(models.Model): id = models.AutoField(primary_key = True) category = models.ForeignKey(Category, on_delete=DO_NOTHING) topic = models.ForeignKey(Topic, on_delete=DO_NOTHING) current = models.CharField(max_length=512) annual = models.ForeignKey("Annual", on_delete=DO_NOTHING, blank=True, null=True) # Annual Report Model class Annual(models.Model): id = models.AutoField(primary_key=True) teacher = models.CharField(max_length=100) group = models.ForeignKey(Group, on_delete=models.CASCADE) year = models.CharField(max_length=100, default="2022") # current = models.CharField(max_length=512, default="current") current = models.ManyToManyField(AnnualCurrentPL, related_name="AnnualCurrentPL", blank=True) expectations = models.CharField(max_length=512, blank=True) month = models.ManyToManyField("MonthAnnual", blank=True) class MonthAnnual(models.Model): id = models.AutoField(primary_key=True) numeric_Month = models.IntegerField() month = models.CharField(max_length=100) year = models.IntegerField() teacher = models.CharField(max_length=255) goal = models.CharField(max_length=512) I have included all models responsible for end result. When I … -
Django ManyToMany Serializer
I implemented nested serializer, but I have that error: NameError: name 'SamplesSerializer' is not defined. I have called the SampleSerializer without defining it yet, I am aware, but here I have also defined the patientid as a foreign key which is related to Epi_dataSerializer. What should I do to fix the problem? class Epi_dataSerializer(serializers.ModelSerializer): epi_data_hospitals = HospitalsSerializer(read_only=True) epi_data = SamplesSerializer(read_only=True, many=True) class Meta: model = Epi_data fields = ['epi_data', 'bday', 'age', 'gender', 'born_country', 'foreigner', 'year_arival', 'date_arival', 'residence', 'postcode', 'occupation'] class SamplesSerializer(serializers.ModelSerializer): projects = ProjectsSerializer(read_only=True) hospitals = HospitalsSerializer(read_only=True) source_samples = SourceSamplesSerializer(read_only=True) sequencing = SequencingSerializer(read_only=True) patientid = Epi_dataSerializer(read_only=True) class Meta: model = Samples fields = ['id', 'reception_date', 'hospital_date', 'culture', 'index_sample', 'is_index_sample', 'status', 'hospital_sample_number', 'patientid', 'sample_type', 'box', 'last_extraction_date', 'inactivation_date', 'transfer_date', 'comments', 'projects', 'hospitals', 'source_samples', 'sequencing'] -
Every 10 row of my table I want to show them seperatly
In my Django project I have a table which datas coming from database. There can be hundreds of rows. I can't display all in one page. I want to display my tables 10 rows for each. I got two buttons for next and previous rows. Can I do this with jquery or some python code? index.html <table class="table" border=1> <thead> <tr> <th>Full Name</th> <th>Company</th> <th>Email</th> <th>Phone Number</th> <th>Note</th> <th>ID</th> <th>Item Barcode</th> </tr> </thead> <tbody> {% for x in thelist %} <tr> <td>{{x.full_name}}</td> <td>{{x.company}}</td> <td>{{x.email}}</td> <td>{{x.phone_number}}</td> <td>{{x.note}}</td> <td>{{x.id}}</td> <td>{{x.item_barcode}}</td> </tr> {% endfor %} </tbody> </table> <button type="button" class="btn btn-primary" name="button">Next</button> <button type="button" class="btn btn-primary" name="button">Previous</button>