Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework: How to show fields of many to many field?
I'm finding a way to serialize model fields of a Many To Many relation object. Models class Tag(models.Model): name = models.CharField(max_length=150) description = models.TextField(blank=True) class Book(models.Model): name = models.CharField(max_length=150) slug = models.SlugField(max_length=255, unique=True) tag= models.ManyToManyField(Tag, related_name='books', blank=True) Serializers - class BookSerializer(serializers.ModelSerializer): author = serializers.StringRelatedField(read_only=True) slug = serializers.SlugField(read_only=True) class Meta: model = Book fields = '__all__' Views - class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() lookup_field = 'slug' serializer_class = BookSerializer def perform_create(self, serializer): return serializer.save(owner=self.request.user) I want to add the tag name to the response of the detailed view as well as the list view of books. If I try to create a serializer for the Tag model and use it in the book serializer, I'm not able to create or update the Book. What should I do? Also, is there a way to update only the tag field? -
How do I email a user a temporary password in Django and allow them to change their password?
I need to send a Django user a random temporary password to their email, so that they can use it to change their forgotten password. They should be able to come back to the forgot password page and type in their temporary password to change it to a new one. How do I do this in Django? This is only for testing purposes and not for actual development. What's the best way to quickly implement this feature and test it in Django? -
i want to change on 2 webpages at same time
[ana document.addEventListener('DOMContentLoaded',function(){ document.querySelector('.first').addEventListener('dragover',dragOver); document.querySelector('.first').addEventListener('drop',drop); }) function dragOver(event){ event.preventDefault(); } var count=0; function drop(event){ if (count!==0){ document.querySelector('.drag_btn_btn').style.display='none'; document.querySelector('.text-btn-index').style.display='block'; } else{ document.querySelector('.drag_slider_btn').style.display='none'; document.querySelector('.slider-index').style.display='block'; count++; } } /* 1st page */ <Button>Run</Button> <div class="second" style="padding-left: 40px;"> <button class="drag_slider_btn" style="background-color: gray; position: absolute; left: 35px; top:80px;" draggable="true">Slider</button> <button class="drag_btn_btn" style="background-color: gray; position: absolute; left: 35px; top:200px;" draggable="true">TextField</button> </div> <div class="first"> <section class="sec1" style="width: 70%; height: 100px; position: absolute; left: 100px;" id="section1_index"> <input type="range" min="-2" max="2" value="0" class="slider slider-index" id="slider" draggable="false" style="width: 300px; display: none;"> </section> <section class="sec2-i" style="width: 70%; height: 100px; margin:40px; margin-top:5px;"> <button style="background-color: gray; position: absolute; left: 180px; top:200px; display: none;" class="text-btn-index" draggable="false">0</button> </section> </div> /*second page */ <div class="second" style="padding-left: 40px;"> <h3 style=" border:1px solid black; background-color:grey; height:80px; width:100px; margin-top: 80px;" class="dropitem h3-d" id="text-box" draggable="true">Python code</h3> </div> <div class="first"> <section class="sec1" style="width: 70%; float: left; height: 100px; margin:40px; margin-top: 5px;"> <button class="diagram-slider" style=" display:none; background-color: gray; position: absolute; left: 30px; top:70px;">Slider</button> </section> <section class="sec2" style="width: 100%; height: 170px; position:absolute; top:120px; left:0px; margin-top:5px; border:1px solid black;"> </section> <section class="sec3"> <button class="diagram-textbox" style=" display:none; background-color: gray; position: absolute; left: 300px; top:300px;">TextField</button> </section> </div> ]1i have 2 webpages and i have already defined the slider in both the property is set to none i … -
Django is not showing image when using AWS
I am having an issue displaying an image from the AWS bucket in django, here a brief explanation: I am passing dynamic data (image) from django to HTML. When running the app locally it shows the image, but when using Heroku/AWS Bucket it doesn't. This only happens when passing dynamic data to CSS format inside an HTML file, but other dynamic data (also image) works well. Another thing to include is that the image gets properly saved into the AWS bucket. It can be accessed from the bucket. Here is my index.html: ''' {% load static %} {% static "img" as baseUrl %} . . . <style> .Modern-Slider .item-1 .image { background-image: url('{{img.0.url}}'); } .Modern-Slider .item-2 .image { background-image: url('{{img.1.url}}'); } </style> . . . <body> <div class="slider"> <div class="Modern-Slider content-section" id="top"> {% for info_home in information_home %} <div class="item item-{{forloop.counter}}"> <div class="img-fill"> <div class="image"></div> <div class="info"> <div> <div class="white-button button"> <a href="{{info_home.home_destination}}">{{info_home.button_home}}</a> </div> </div> </div> </div> </div> {% endfor %} </div> </div> </body> ''' Here is my views.py : ''' def index(request): information_home = Info_Home.objects.all() lista_imagenes = [] for info in information_home: imagen = info.image_home lista_imagenes.append(imagen) return render(request, "index.html", {'information_home': information_home, 'img': lista_imagenes}) ''' -
why my django-ckeditor Link tab does not have Target option?
I am using django-ckeditor=6.0.0 for my django app. I used earlier version of django-ckeditor before, and I remembered that the Link tab has Target option, so you can choose whether to open a new tab/ open a new window/ or _blank, etc. I could not figure out why in current version, there is not Target option. I am using default toolbar. -
Django Signal Loop
Can someone help me resolving this problem. I've created an django-app with two models. One model is an Wallet model and other is Transaction model. Every transaction is conneted to a wallet with models.ForeignKey. I've also created two signals, one is for updating cryptocurrency balance (eg. BTC, ETH) in Wallet when transaction is made and the other signal i want to update Total_Balance (which is all other balances converted to USD). And here I have a problem because my signal is POST_SAVE and in it I have a save() method which causes infinity loop. I think if I would do a whole thing in my first signal it would work but in future i want to add new model which also will be connected to Wallet and it would pop-up my total_balance, therefor i would need same logic in third signal and I would end up with same code in two signals. I know my description is a little messy. Here is some code to help understand it. My Models: class Wallet(models.Model): name = models.CharField(max_length=50) total_balance = models.IntegerField(blank=True) btc_balance = models.DecimalField(max_digits=15, decimal_places=8) xrp_balance = models.DecimalField(max_digits=15, decimal_places=8) eth_balance = models.DecimalField(max_digits=15, decimal_places=8) class Transaction(models.Model): wallet = models.ForeignKey(Wallet, on_delete=models.CASCADE) currency_paid = models.CharField(choices=CURRENCY, max_length=3) … -
Sharing an image to LinkedIn using Django 2.2
To share an image on LinkedIn you need to follow the instructions at https://docs.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/share-on-linkedin?context=linkedin/consumer/context What I don't understand is how to make this curl request "curl -i --upload-file /Users/peter/Desktop/superneatimage.png --header "Authorization: Bearer redacted" 'https://api.linkedin.com/mediaUpload/C5522AQGTYER3k3ByHQ/feedshare-uploadedImage/0?ca=vector_feedshare&cn=uploads&m=AQJbrN86Zm265gAAAWemyz2pxPSgONtBiZdchrgG872QltnfYjnMdb2j3A&app=1953784&sync=0&v=beta&ut=2H-IhpbfXrRow1'". Using Django's requests library. So Basically what I need help with is converting the curl request above into a regular HTTP call such as get, post, put, etc. To Whom it may concern, Jordan -
Django session_key get new value for each request
I create session like this: request.session['user_id'] = 111 if not req.session.session_key: req.session.save() Then in another view, I print: print(request.session.get('user_id')) print(request.session.session_key) session data (user_id) showing correctly, and session_key looks like: eyJ1c2VyX2lkIjoiMTAwIiwidXNlcl9uaWNrIjoibmljazEifT:1khfFA:rwQnzaXk4HQ9XdKPuL1fhRPuLbl8w-TUNR3RMPsNQQr though, for every request, (page refresh) session_key prints different value (BTW part before first ":" stays same). Question: is this behaviour normal? does not session_key must to be same, while session is "alive" ? -
add fields in Django auth Group
I edit the django admin form to show users list with the permission to create group of users to to som actions I want to add a new field without creation a new modal is it possible? forms.py class GroupAdminForm(forms.ModelForm): class Meta: model = Group exclude = [] users = forms.ModelMultipleChoiceField( queryset=User.objects.all(), required=False, widget=FilteredSelectMultiple('users', False) ) def __init__(self, *args, **kwargs): super(GroupAdminForm, self).__init__(*args, **kwargs) if self.instance.pk: self.fields['users'].initial = self.instance.user_set.all() def save_m2m(self): self.instance.user_set.set(self.cleaned_data['users']) def save(self, *args, **kwargs): instance = super(GroupAdminForm, self).save() self.save_m2m() return instance admin.py admin.site.unregister(Group) class GroupAdmin(admin.ModelAdmin): form = GroupAdminForm filter_horizontal = ['permissions'] admin.site.register(Group, GroupAdmin) the filed I want to add I have triyed thois but it is not working: models.py class MyGroup(Group): notes = models.TextField(blank=True) def __unicode__(self): return self.name when I add this model I have edit the model in the GroupAdminForm to use this model but no sucess ? -
How to filter foreign key on datatables with server side processing?
How do i filter Foreign keys on a datatable with server side processing? I'm using a datatable to display 3.500 entries from my sql server within Django/Ajax/Rest-Framework. The table is working as intended when searching columns within the given table, but: Foreign key filtering appears not to be working. error i get when searching: raise FieldError("Cannot resolve keyword '%s' into field. " django.core.exceptions.FieldError: Cannot resolve keyword 'bib_tipo_nome' into field. Choices are: autor, cadastro_id, datacriado, emailautor, referencia, tema, tema_id, tipo, tipo_id Is there a solution for this? Do i need client-sided processing? -
Unable to download zip file from server with %20 in it's name but when I copy the link from html it works fine
I am trying to figure out the exact issue but with little success. I have rendered a template containing the link for a file in media directory of my server. The filename has a space in it in the media directory and in the database this space has been replaced with %20 in the filename. I am fetching the filename from the database and passing it to the HTML template with the media url. When I check the rendered html, it has %20 and if I copy the link from the HTML and try to download the file, it is getting downloaded. e.g. The file in the HTML looks like : http://abc.domain.com/media/Demo%20Report.xlsx The file in the media directory is "Demo Report.xlsx" -
DJANGO Static Image deletion
I am experiencing an issue with images saved in the static/images directory in Django. My website was rendering images appropriately, by referencing the name of the image e.g., Image_1. However, once I've tried to delete this image and include a new one in the static/images directory with the same name, Image_1, the website keeps rendering the old image. New images added in the same directory with new names are rendered without issues. Since then I have specified all STATIC_ROOT, MEDIA and MEDIA_ROOT routes in settings.py, I have run manage.py collectstatic and I have checked the images stored in these directories. The "old" version of Image_1 is not there anymore, but the new one is, and the website still renders the "old" version of it. Does anybody have an explanation for this, and how to fix it? Thanks in advance! -
ModuleNotFoundError: No module named 'django_countries'
I have a docker django project and I want to use django-countries. This is my requirements.txt .... django-countries django-cities This is the INSTALLED_APPS in settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_countries', ... (others) ] When I run docker-up, I receive the below error: docker_name | Traceback (most recent call last): docker_name | File "/app/manage.py", line 22, in <module> docker_name | main() docker_name | File "/app/manage.py", line 18, in main docker_name | execute_from_command_line(sys.argv) docker_name | File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line docker_name | utility.execute() docker_name | File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 377, in execute docker_name | django.setup() docker_name | File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup docker_name | apps.populate(settings.INSTALLED_APPS) docker_name | File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate docker_name | app_config = AppConfig.create(entry) docker_name | File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 90, in create docker_name | module = import_module(entry) docker_name | File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module docker_name | return _bootstrap._gcd_import(name[level:], package, level) docker_name | File "<frozen importlib._bootstrap>", line 1030, in _gcd_import docker_name | File "<frozen importlib._bootstrap>", line 1007, in _find_and_load docker_name | File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked docker_name | ModuleNotFoundError: No module named 'django_countries' Any ideas? -
Django getting (AttributeError: 'str' object has no attribute 'get') after submitting a form
I am studying django recently, and I met problem, Internal Server Error: /event_edit Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/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.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/workspace/CalendarProject/cencal/views.py", line 107, in event_edit if form.is_valid(): File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 185, in is_valid return self.is_bound and not self.errors File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 180, in errors self.full_clean() File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 381, in full_clean self._clean_fields() File "/usr/local/lib/python3.7/site-packages/django/forms/forms.py", line 393, in _clean_fields value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name)) File "/usr/local/lib/python3.7/site-packages/django/forms/widgets.py", line 258, in value_from_datadict return data.get(name) AttributeError: 'str' object has no attribute 'get' This error message appeared while doing form.is_valid(), but I can't know what is the problem. There was surely no problem with form field values. If you need any additional informations for this, I am ready to do it. -
Paginator problems on class based views in django
I'm trying to add the pagination functionality on my project that has a plog section. On this project I have different types of page that needs to display some content and to be more efficient I've mad a single model that hold all types of pages. On the page section I want to display just the pages that has the blog_post=True and apply a pagination. I've tried that on my class based view but the paginator is not working. It show me correct number of post per page, is showing the pagination buttons but when I try to acces another page, for example next page it give an error like this, but on the url I know that should display me something like blog/?page=2 but it displays me this "http://localhost:8000/blog/?page=%3Cbound%20method%20Page.next_page_number%20of%20%3CPage%201%20of%202%3E%3E" class BlogListView(generic.ListView, MultipleObjectMixin): model = Page template_name = 'pages/blog_list.html' paginate_by = 1 def get_queryset(self): return Page.objects.filter(blog_post=True).order_by('-created_dt') Models.py class Page(models.Model): class Meta: ordering = ['slug'] blog_post = models.BooleanField(_("Blog Post"), blank=False, default=False) title = models.CharField(_("Title"), blank=True, max_length=100, unique=True) slug = models.SlugField(_("Slug"), unique=True, max_length=100, blank=True, null=False) breadcrumb_title = models.CharField( _("Breadcrumb Title"), blank=True, max_length=100, null=False, default='') text = MarkdownxField(_("Text"), blank=True, null=False) description = models.TextField( _("Meta Description"), blank=True, null=False, default='') keywords = models.TextField( _("Meta Keywords"), … -
Pytest after running all tests raises AttributeError: 'ReprExceptionInfo' object has no attribute 'rsplit'
I use the pytest-django package for testing in the project. When running pytest for my Django project, I run into an exception that shows up after the whole tests have been ran, hence does not show the test results. This happened on OSX. The following is the complete stacktrace of the error. Nothing that leads back to my code whatsoever. Really frustrating. Traceback (most recent call last): File "/Users/oluwanifemi/Desktop/projects/env/bin/pytest", line 8, in <module> sys.exit(console_main()) File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/_pytest/config/__init__.py", line 187, in console_main code = main() File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/_pytest/config/__init__.py", line 164, in main ret = config.hook.pytest_cmdline_main( File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/pluggy/hooks.py", line 286, in __call__ return self._hookexec(self, self.get_hookimpls(), kwargs) File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/pluggy/manager.py", line 93, in _hookexec return self._inner_hookexec(hook, methods, kwargs) File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/pluggy/manager.py", line 84, in <lambda> self._inner_hookexec = lambda hook, methods, kwargs: hook.multicall( File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/pluggy/callers.py", line 187, in _multicall res = hook_impl.function(*args) File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/pluggy/callers.py", line 80, in get_result raise ex[1].with_traceback(ex[2]) File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/pluggy/callers.py", line 187, in _multicall res = hook_impl.function(*args) File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/_pytest/main.py", line 306, in pytest_cmdline_main return wrap_session(config, _main) File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/_pytest/main.py", line 257, in wrap_session session.exitstatus = doit(config, session) or 0 File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/pluggy/hooks.py", line 286, in __call__ return self._hookexec(self, self.get_hookimpls(), kwargs) File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/pluggy/manager.py", line 93, in _hookexec return self._inner_hookexec(hook, methods, kwargs) File "/Users/oluwanifemi/Desktop/projects/env/lib/python3.8/site-packages/pluggy/manager.py", line 84, in <lambda> self._inner_hookexec = … -
Remove _id automatically appended by Django in case of foreign key
account_number = models.ForeignKey("commuter.Account", on_delete=models.CASCADE, db_column="account_number ") -
Am I unable to use sendinblue with heroku?
I just deployed a tiny website to Heroku and it uses SendInBlue as the SMTP. It's not sending any of the messages. Does Heroku force you to use one of their add-ons and refuse to let you use other types of SMTP servers? -
How do I add more than one dictionary list to a Django return render call?
Hey guys I'm trying to send more than one dictionary list to a certain HTML template from Python. I know how to do it with one list. How would I send more than one? In my example below I am sending the list newquery to the render request so that I can use it in my HTML. But I also want to include another list from my Follows model...what is the correct syntax for this? Here's what I have: def profile(request, username): newquery = Follow.objects.filter(username=username) return render(request, "network/profile.html", { "newqueries": newquery }) Here's what I want: def profile(request, username): newquery = NewPost.objects.filter(username=username) query = Follow.objects.filter(username=username) return render(request, "network/profile.html", { "newqueries": newquery }, { "queries": query }) -
How to use django-user-agents with class ListViews
I am building a blog and I have different templates for mobile and desktop versions, I have successfully implemented the user_agent identification for addressing mobile or desktop template for all of my functions as follow: ''' def about(request): user_agent = get_user_agent(request) if user_agent.is_mobile: return render(request, 'about-mobile.html') elif user_agent.is_pc: return render(request, 'about.html') ''' However, once I have to implement it to the ListView classes I really have no idea how to do that! ''' class homepage(ListView): model = DeathAd template_name = 'homepage.html' ordering = ['-id'] paginate_by = 5 ''' -
uwsgi failed to open python file for deploying
I am trying to set up uwsgi on a linux machine. I created a conda environment and isntalled uwsgi and django using conda. To test the installation I created a test: # test.py def application(env, start_response): start_response('200 OK', [('Content-Type','text/html')]) return [b"Hello World"] # python3 #return ["Hello World"] # python2 and run the following command in the same directory where the test.py is : uwsgi --http :8000 --wsgi-file test.py I get the following error: *** Starting uWSGI 2.0.19.1 (64bit) on [Tue Nov 24 14:30:06 2020] *** compiled with version: 7.5.0 on 15 October 2020 10:51:33 os: Linux-4.4.0-18362-Microsoft #1049-Microsoft Thu Aug 14 12:01:00 PST 2020 nodename: DESKTOP-QPDTTFN machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 8 current working directory: /home/masih/projects/uw detected binary path: /home/masih/.conda/envs/uwsgi/bin/uwsgi *** WARNING: you are running uWSGI without its master process manager *** your processes number limit is 7823 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) TCP_DEFER_ACCEPT setsockopt(): Protocol not available [core/socket.c line 744] TCP_DEFER_ACCEPT setsockopt(): Protocol not available [core/socket.c line 744] uWSGI http bound on :8000 fd 4 spawned uWSGI http 1 (pid: … -
Using cmd line under django server
To make it easier to understand, i will use simple command line as 'ls' How can i use a command line like 'pwd' or 'ls' into a django server ? For example, my django server is running 'python manage.py runserver' And into my code i would like to run a cmd command like 'pwd' and get the output of this command : @login_required def history(request): list_file = print('ls') #i would like to do 'ls' command return render(request, 'history.html') Is it possible ? Thank for your help ! -
Form couldn't save in Django
Please help me. I'm trying to make the company users can assign the status of the applicants and give feedback, but it doesn't save the form. Could someone tell me where i did wrong?? I'm a beginner please help.. forms.py` ** class StatusForm(forms.ModelForm): class Meta: model = ApplicantsJobMap fields = ['applicant', 'status', 'feedback'] models.py class Applicants(models.Model): name = models.CharField(max_length=100) age = models.CharField(max_length=10) gender = models.CharField(max_length=20, default=GENDER_MALE, choices=GENDER_CHOICES) mobile_phone = models.CharField(max_length=20) city = models.CharField(max_length=30) expected_salary = models.IntegerField() will_relocate = models.BooleanField(default=False) for_cv = models.FileField(verbose_name='CV') def __str__(self): return "{} - {}".format(self.name, self.mobile_phone) class ApplicantsJobMap(models.Model): applicant = models.ForeignKey(Applicants, on_delete=models.CASCADE) job = models.ForeignKey('jobs.Job', on_delete=models.CASCADE, related_name='applicants', null=True) status = models.CharField( max_length=20, choices=STATUS_CHOICES, default=STATUS_PENDING ) feedback = models.TextField(blank=True, null=True) def __str__(self): return "{} - {}".format(self.applicant.name, self.job.position_name) views.py def update(request, pk): #applicant_form = inlineformset_factory(Applicants, ApplicantsJobMap, fields=('applicant', 'status', 'feedback')) applicants = Applicants.objects.filter(id=pk).first() formset = StatusForm(initial={'applicant': applicants}) #formset = applicant_form(instance=applicants) if request.method == 'POST': formset = StatusForm(request.POST) if formset.is_valid(): formset.applicant = formset.cleaned_data['applicant'] formset.status = formset.cleaned_data['status'] formset.feedback = formset.cleaned_data['feedback'] formset.save() return redirect('home') context = {'formset': formset} return render(request, 'jobs/status.html', context) html <div class="row"> <div class="col-md-6"> <div class="card card-body"> <form action="" method="POST"> {% csrf_token %} {% for field in formset %} {{field}} <hr> {% endfor %} <input type="submit" name="Submit"> </form> </div> </div> -
Django N+1 problem with serpy.MethodField
I use nplusone to detect N+1 queries. I have a serpy serializer that serializes Order instances. An Order has a cart consisting of OrderComponent instances, as shown below. Code simplified: class Order(models.Model): objects = OrderManager() listings = models.ManyToManyField(to=Listing, through="OrderComponent", related_name="orders") class OrderComponent(models.Model): listing = models.ForeignKey(to=Listing, on_delete=models.PROTECT, related_name="order_components") order = models.ForeignKey(to=Order, on_delete=models.PROTECT, related_name="cart") nb_units = models.PositiveIntegerField() A list of serialized Order instances is gotten through OrderListView: class OrderListView(SimplePaginatedListView): # Custom base class model = Order serializer_class = OrderSerializer deserializer_class = OrderDeserializer def get_queryset(self): return super().get_queryset().select_related( "fulfillment", # Used for order.is_fulfilled() "cancellation", # Used for order.is_cancelled() ).prefetch_related( "cart", # I don't believe the first two are necessary, but added for testing purposes "cart__listing", "cart__listing__product", "cart__listing__service", ) @http_get(required_permissions=ShopRolePermission.MANAGE_ORDERS) def get(self, *args, **kwargs): return super().get(*args, **kwargs) @http_post(required_permissions=ShopRolePermission.MANAGE_ORDERS) def post(self, *args, **kwargs): return super().post(*args, **kwargs) OrderSerializer is defined below. nplusone does not say where an N+1 query was detected, so I have commented out every possible culprit and found the true culprits. I have indicated in comments where they are. class OrderSerializer(BaseSerializer): class SimpleOrderComponentSerializer(BaseSerializer): id = serpy.IntField() listing_id = serpy.IntField() product_name = serpy.MethodField(required=False) # No N+1 service_name = serpy.MethodField(required=False) # No N+1 nb_units = serpy.IntField() def __init__(self, instance=None, many=False, data=None, context=None, **kwargs): # Should this … -
Python Django NoReverseMatch Error When I {% url 'crm_client_detail' client.id %}
I know my question seems fimiliar to others but it's not. I'm stuck on in the error in the below when I visit my homepage. The problem is that {% url 'crm_client_detail' client.id %}. I'm pretty sure that I'm doing right but it's not happening. NoReverseMatch at / Reverse for 'client_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['client/(?P[0-9]+)/$'] Any help is so appreciated models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Client(models.Model): client_name= models.CharField(max_length=100) client_sector= models.CharField(max_length=100) client_phone= models.CharField(max_length=100) client_city= models.CharField(max_length=100) client_district= models.CharField(max_length=100) client_adress= models.TextField() client_type= models.CharField(max_length=100) client_priority= models.CharField(max_length=100) client_first_contacted_date=models.DateTimeField(default=timezone.now) # author = models.ForeignKey(User, on_delete=models.CASCADE) views.py from django.shortcuts import render from .models import Client from django.views.generic import ListView, DetailView def ClientView(request): context = {'client_aranacak': Client.objects.all()} return render(request, 'crm/crm_home.html', context) class ClientListView(ListView): model = Client template_name = 'crm/crm_home.html' context_object_name = 'client_aranacak' ordering = ['-client_first_contacted_date'] class ClientDetailView(DetailView): model = Client urls.py from django.urls import path from . import views from .views import ClientListView, ClientDetailView urlpatterns = [ path('', ClientListView.as_view(), name='crm_client'), path('client/<int:pk>/', ClientDetailView.as_view(), name='client_detail'), ] # {% url 'crm_client_detail' client.id %} crm_home.html {%extends "base.html"%} {%block content%} <div class="card mb-4"> <div class="card-header"> <i class="fas fa-table mr-1"></i> Customers </div> <div class="card-body"> <div class="table-responsive"> <table …