Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to creating Django projeckt directory in VS-Code
enter image description hereI work with Git Bash, Python, Django in a virtual environment under VS-Code and I have such a problem. When I use the $ python -m django startproject mysite command in the djangogirls directory, two nested mysite directories are created under the djangogirls directory, see a picture. But I would need only one under the djangogirls directory. How should I do that ? everything I could think of -
Roadmap for me:provide feedback and insights please
I am 16 years old studying in college but also working on my skills.After much research i have created this roadmap for me.If you are an industry professional,please consider giving some words about this roadmap so i can have the relaxation that i am doing the right thing.Your feedback will matter a lot as you are in the tech industry so i will be highly grateful to you, this is the roadmap note that i am dedicating 1 hour daily to learning and i cannot give more due to my studies and also self learning is difficult: This is my roadmap: Basics and Intermediate Python(6 weeks) Scripting and Automation With Python (18 weeks learning from Automate the boring stuff with python's part 2 (automating tasks)) Advanced Python and Object Oriented Programming(8 weeks) Html css and basic Javascript(8 weeks) Intermediate Javscript and Reactjs(8 weeks) Sql with Postgresql and Git (8 weeks) Django Backend Development(12 weeks) How is this roadmap Provide feedback insights,do constructive criticism,whats wrong with it give some words about the syllabus do i need to adjust it like somthing before or after a thing I have completed the first phase and now i am in the second phase -
How to serve InMemoryStorage media files during Django tests
I have some Selenium-based integration tests (subclassed under django.contrib.staticfiles.testing.StaticLiveServerTestCase) for my Django app that require a functioning user-uploaded media configuration. I've been using S3 storage (django_s3_storage.storage.S3Storage from etianen/django-s3-storage) and that works just fine, but it incurs S3 costs each time I run my tests, plus the network overhead of going out to S3 is a lot during some of my media-heavy tests. The newly added (in Django 4.2) InMemoryStorage solves both of these problems (S3 costs and overhead) perfectly, but I can't get the test server to actually serve the uploaded media files. I've added: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to my urlpatterns.py, but that has no effect since Django tests are always run with DEBUG=False. But even if I force it in to my urlpatterns by inlining the relevant portion of django.conf.urls.static.static like so: import re from django.views.static import serve urlpatterns += [ re_path( r"^%s(?P<path>.*)$" % re.escape(settings.MEDIA_URL.lstrip("/")), serve, kwargs={"document_root": settings.MEDIA_ROOT}, ), ] it still doesn't work since the serve function looks like it's not storage-aware; it only works with media files on the filesystem. The result is that my media files all return 404s when my Selenium browser requests them. Is there a storage-aware equivalent to django.views.static.serve that I can … -
How do i fix this id?
i was watching a youtube tutorial about django and got an error. i was making login page and forms.py, and got an error which one the guy on youtube didnt get. its an 'invalid id reference error' in login.html, and i dont know how to fix it. code looks like this: forms.py: from django import forms from django.contrib.auth.forms import AuthenticationForm from users.models import User class UserLoginForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control py-4', 'placeholder': 'Введите имя пользователя'})) password = forms.CharField(widget=forms.PasswordInput(attrs={ 'class': 'form-control py-4', 'placeholder': 'Введите пароль'})) class Meta: model = User fields = ('username', 'password') login.html: (part of the code) {% csrf_token %} <div class="form-group"> <label class="small mb-1" for="{{ form.username.id_for_label }}">Username</label> {{ form.username }} </div> <div class="form-group"> <label class="small mb-1" for="{{ form.password.id_for_label }}">Password</label> {{ form.password }} </div> <div class="form-group d-flex align-items-center justify-content-between mt-4 mb-0"> <a class="small" href="#">Forgot password?</a> <input class="btn btn-primary" type="submit" value="Registrate"> </div> error in this line: <label class="small mb-1" for="{{ form.username.id_for_label }}">Username</label> and this: <label class="small mb-1" for="{{ form.password.id_for_label }}">Password</label> please help me im too stoopid -
IntegrityError at /save-comment/
Good evening everyone I'm really stuck facing this Django problem for days thank you for helping me to unblock the problem, I created an opinion platform where the user can put the stars and give their opinion in comments, but when he wants to do it I always get an error please help me resolve the problem here is the error that appears all the time: IntegrityError at /save-comment/ (1048, "Le champ 'concours_id' ne peut être vide (null)") concours.views.save_comment .utilisateur}"``` class AvisConcours(models.Model): concours = models.ForeignKey('concours.Concours', on_delete=models.CASCADE, related_name='avis_concours') note = models.ManyToManyField('concours.Note', related_name='avis_note', blank=True,) commentaire = models.TextField(blank=True) utilisateur = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = "Avis de concours" verbose_name_plural = "Avis de concours" def __str__(self): return f"{self.concours}" + " - " + f"{self.utilisateur}" def save_comment(request): if request.method == 'POST': commentaire = request.POST.get('commentaire') concours_id = request.POST.get('concours') utilisateur = request.user notes_to_create = [] for note_type in NoteType.objects.all(): rating_value = request.POST.get(f'rating_{note_type.id}') if rating_value is not None: # Only create notes for non-empty ratings notes_to_create.append(Note(note_type=note_type, valeur=rating_value)) # Save bulk Note created_notes = Note.objects.bulk_create(notes_to_create) # Save AvisConcours and link notes avis_concours = AvisConcours.objects.create( concours_id=concours_id, commentaire=commentaire, utilisateur=utilisateur ) avis_concours.note.set(created_notes) # Use set() to set ManyToManyField directly return redirect('merci_commentaire') # return redirect('merci_commentaire') return render(request, "page_commentaire.html") <div … -
Runtime error in the GET methord and while submiting the form
I am just done the migration, then i want to store the data in the database after hit the submit button it show the error like this in the picture so gide me how to clear the error model.py from django.db import models # Create your models here. class register(models.Model): your_name = models.CharField(max_length=30) Email= models.EmailField(max_length=254) phone= models.IntegerField(max_length=13) account = models.CharField(max_length=10) message = models.CharField(max_length=300) error page Internal Server Error: /register Traceback (most recent call last): File "J:\good\test\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\utils\deprecation.py", line 136, in __call__ response = self.process_response(request, response) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\middleware\common.py", line 108, in process_response return self.response_redirect_class(self.get_full_path_with_slash(request)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "J:\good\test\Lib\site-packages\django\middleware\common.py", line 87, in get_full_path_with_slash raise RuntimeError( RuntimeError: You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/register/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. [29/Sep/2023 20:35:21] "POST /register HTTP/1.1" 500 70661 In this view file it contain the register file. views.py from django.shortcuts import render,redirect from django.contrib.auth.models import User # Create your views here. def index(request): return render(request,"index.html") def contact(request): return render(request,"contact.html") def … -
in django in my porfolio detail the picture of portfolios are similar
in my django project in the index page in portfolio part everything is ok and the picture of each portfolio is correct but when i open a portfolio detail the picture of all portfolio in detail is a similar picture for example my firsts portfolio picture is pic3.jpg and my seconds portfolio image is pic4.jpg in the index page i havent any problem but when i open detail the first and second portfolio image is similar both of them is pic3.jpg it is my template: {% for item in porto %} <div class="col-xl-4 col-md-6 portfolio-item filter-app"> <div class="portfolio-wrap"> <a style="display: inline-block; max-width: 360px; max-height: 200px; overflow: hidden;" href="{{ item.image.url }}" data-gallery="portfolio-gallery-app" class="glightbox"> <img src="{{ item.image.url }}" class="img-fluid" alt=""> </a> <div class="portfolio-info"> <h4><a href="{% url 'root:portfolio' id=item.id %}" title="More Details">{{ item.title }}</a></h4> <p>{{ item.content|truncatewords:3 }}</p> </div> </div> </div><!-- End Portfolio Item --> {% endfor %} it is urls.py: from django.urls import path from .views import * app_name = 'root' urlpatterns = [ path("",home,name="home"), path("portfolio/<int:id>",port_folio,name="portfolio"), path('category/<int:category_id>',home,name='portfilter'), ] it is views: def port_folio(request,id): cat = Category.objects.all() portos = PortFolio.objects.get(id=id) porto = PortFolio.objects.filter(status = True) context = { 'cat':cat, 'portos':portos, 'porto':porto, } return render(request,'root/portfolio-details.html',context=context) and it is my modules.py: class PortFolio(models.Model): image = models.ImageField(upload_to='port',default='default.jpg') … -
Django Admin - Proxy model loses edit/add on Foreign Key fields and no auto-complete?
Goal: I want to group some of my models inside of other apps on the Admin page. How: I created a proxy model for each of my models and defined app_label to be that of the app I want. class MyModelProxy(MyModel): class Meta: proxy = True app_label = 'auth' # specify a different app for the model to be grouped with verbose_name = MyModel._meta.verbose_name verbose_name_plural = MyModel._meta.verbose_name_plural I registered the proxy model together with the custom admin model I created for each. admin.site.register(MyModelProxy, MyModelAdmin) Issue 1: My Foreign Key fields lose the icons to edit/add another object in the view/change pages. If I register the original model with the admin model, it displays fine. (original)--> (proxy) Issue 2: If I set autocomplete_fields inside the corresponding admin models, I get an error that the original model should be registered. But I want to only register the proxy model, not both ? -
Get subscription ID with new Paypal Webhooks
I use the following endpoint for receiving the Paypal webhooks: @method_decorator(csrf_exempt, name='dispatch') class ProcessWebHookView(View): def post(self, request): if "HTTP_PAYPAL_TRANSMISSION_ID" not in request.META: return HttpResponse(status=400) auth_algo = request.META['HTTP_PAYPAL_AUTH_ALGO'] cert_url = request.META['HTTP_PAYPAL_CERT_URL'] transmission_id = request.META['HTTP_PAYPAL_TRANSMISSION_ID'] transmission_sig = request.META['HTTP_PAYPAL_TRANSMISSION_SIG'] transmission_time = request.META['HTTP_PAYPAL_TRANSMISSION_TIME'] webhook_id = settings.PAYPAL_WEBHOOK_ID event_body = request.body.decode(request.encoding or "utf-8") valid = notifications.WebhookEvent.verify( transmission_id=transmission_id, timestamp=transmission_time, webhook_id=webhook_id, event_body=event_body, cert_url=cert_url, actual_sig=transmission_sig, auth_algo=auth_algo, ) if not valid: return HttpResponse(status=400) webhook_event = json.loads(event_body) event_type = webhook_event["event_type"] print(event_type) return HttpResponse() Well in the metadata no information about the subscription id can be found. Does anyone have experience how to get this information from the request? -
Guys help me, to make a chat webapp to encrypted chat webapp in django
How hard to make a end to end encrypted chat using django and react, I mean using django channels and web socket, I already builded a chat web app, how hard to change my chat app to encrypted chat app, and also those encrypted chat needs to also be store as encrypted in Database, is any library out there?? -
Migration file errors when trying to get rid of a third party Django app
I'm working on a Django Project that currently uses the third party app Oscar. We're in the process of migrating away from Oscar, to a custom-built shop, and for this we want to get rid of a bunch of old files, models and of course the actual third party dependencies. But I am having a hard time doing this because the migration files keep throwing up errors. The situation is that we have first-party models that depend on Oscar's models. For example: from oscar.apps.catalogue.models import Product class Executable(Model): exec_hash = CharField(max_length=64, unique=True) product = ForeignKey(Product, blank=True, null=True, on_delete=CASCADE) version = CharField(max_length=32) os = CharField(max_length=32) update_url = CharField(max_length=128, blank=True) This means we have a migration file that contains the code to create this table: migrations.CreateModel( name="Executable", fields=[ ("id", models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID")), ("exec_hash", models.CharField(max_length=64, unique=True)), ("version", models.CharField(max_length=32)), ("os", models.CharField(max_length=32)), ("update_url", models.CharField(blank=True, max_length=128)), ( "product", models.ForeignKey( blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to="catalogue.product" ), ), ], ), The product field from this Executable needs to be removed, so I removed the field from the model and created a new migration. Now I want to remove all the Oscar apps from my INSTALLED_APPS list, but this is causing a whole lot of headaches because when I … -
libc error with UWSGI for Django, UWSGI fails on site load
I am receiving a segmentation fault error in UWSGI that seems to be related to libc.so.6 in my linux system. I have no idea where to even start with this error. The error happened after pushing code, but did not disappear after re-pushing the older code. We have 2 servers running this code, but only one is receiving this error. The error is as follows: Fri Sep 29 14:34:25 2023 - DAMN ! worker 2 (pid: 57544) died, killed by signal 11 :( trying respawn ... Fri Sep 29 14:34:25 2023 - Respawned uWSGI worker 2 (new pid: 57759) Fri Sep 29 14:34:47 2023 - !!! uWSGI process 57545 got Segmentation Fault !!! Fri Sep 29 14:34:47 2023 - !!! uWSGI process 57545 got Segmentation Fault !!! Fri Sep 29 14:34:47 2023 - !!! uWSGI process 57545 got Segmentation Fault !!! Fri Sep 29 14:34:47 2023 - !!! uWSGI process 57545 got Segmentation Fault !!! Fri Sep 29 14:34:47 2023 - *** backtrace of 57545 *** website.com(uwsgi_backtrace+0x35) [0x560449e94825] website.com(uwsgi_segfault+0x23) [0x560449e94bd3] /lib/x86_64-linux-gnu/libc.so.6(+0x33060) [0x7ffad1d63060] *** end of backtrace *** Fri Sep 29 14:34:47 2023 - *** backtrace of 57545 *** website.com(uwsgi_backtrace+0x35) [0x560449e94825] website.com(uwsgi_segfault+0x23) [0x560449e94bd3] /lib/x86_64-linux-gnu/libc.so.6(+0x33060) [0x7ffad1d63060] *** end of backtrace *** I … -
want to add validation on authenticate in django form
i created a login form is ther some thing are already validated but i can't validate is the username and pass word was correct view.py from django import forms as actualform from . import forms from django.shortcuts import render,redirect from django.contrib.auth import authenticate,login,logout from django.core import validators def user_login(request): if request.method == 'POST': form = forms.LoginForm(request.POST.dict()) if form.is_valid(): # Handle valid form submission username=form.cleaned_data['name'] password=form.cleaned_data['password'] user=authenticate(username=username,password=password) if user is not None: login(request,user) return redirect(home) elif user is None : return render(request, "login.html", context={'form': form}) else: form = forms.LoginForm() return render(request, "login.html", context={'form': form}) def home(request): if request.user.is_authenticated: return render(request,"home.html") return redirect(user_login) def user_logout(request): if request.user.is_authenticated and request.META.get('HTTP_REFERER') is not None: logout(request) return redirect(home) login.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>login</title> {% load bootstrap5 %} {% bootstrap_css %} {% bootstrap_javascript %} </head> <body> <div class=" w-50 container " style="border-radius: 20px; background-color: darkgrey;"> <h1 class="mt-5 pt-5 mb-0 text-center ">login</h1> <div class="h-100 d-flex align-items-center justify-content-center "> <form class="w-50 m-5 container" method="post" autocomplete="on"> {% csrf_token %} {{ form.name.label_tag }} {{ form.name }} <div class="error-message" style="color:red">{{ form.name.errors }}</div> {{ form.password.label_tag }} {{ form.password }} <div class="error-message">{{ form.password.errors }}</div> <button type="submit" class="btn btn-primary mt-1">Login</button> </form> <!-- <form class="w-50 m-5 container" … -
How to notify multiple separate cached Django read-only instances when a view has changed?
I am considering a Django stack for a site with high-frequency read (GET) events and low-frequency write (POST) events. Suppose there are a large number of read-only instances which are all serving GET events and caching various views. There are a smaller number of non-cacheing writeable instances which handle POST events. These instances are all independent and might be running on separate machines, although they access the same central database. Now suppose there is a POST event which invalidates, say, a user's e-mail address. Then various views across the various read-only instances need to invalidate their caches. Is there a standard way to implement this pattern within the Django framework, or do I need to do this myself? (Or there a much better totally different way to do this?) -
Django/Channels: AppRegistryNotReady error when deploying ASGI application on Heroku
I'm encountering an issue when deploying my Django application with Channels (ASGI) on Heroku. I've set up my ASGI configuration and routing as per the documentation, and the application works fine locally. However, when I deploy it on Heroku, I'm getting the following error: heroku log `2023-09-29T13:50:20.958856+00:00 heroku[web.1]: State changed from crashed to starting 2023-09-29T13:50:24.630050+00:00 heroku[web.1]: Starting process with command `daphne nanochat.asgi:application --port 16299 --bind 0.0.0.0 -v2` 2023-09-29T13:50:25.627718+00:00 app[web.1]: Traceback (most recent call last): 2023-09-29T13:50:25.627755+00:00 app[web.1]: File "/app/.heroku/python/bin/daphne", line 8, in <module> 2023-09-29T13:50:25.627769+00:00 app[web.1]: sys.exit(CommandLineInterface.entrypoint()) 2023-09-29T13:50:25.627785+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/daphne/cli.py", line 171, in entrypoint 2023-09-29T13:50:25.627826+00:00 app[web.1]: cls().run(sys.argv[1:]) 2023-09-29T13:50:25.627827+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/daphne/cli.py", line 233, in run 2023-09-29T13:50:25.627875+00:00 app[web.1]: application = import_by_path(args.application) 2023-09-29T13:50:25.627876+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/daphne/utils.py", line 12, in import_by_path 2023-09-29T13:50:25.627909+00:00 app[web.1]: target = importlib.import_module(module_path) 2023-09-29T13:50:25.627909+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/importlib/__init__.py", line 126, in import_module 2023-09-29T13:50:25.627951+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2023-09-29T13:50:25.627952+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1050, in _gcd_import 2023-09-29T13:50:25.628008+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1027, in _find_and_load 2023-09-29T13:50:25.628030+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked 2023-09-29T13:50:25.628055+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 688, in _load_unlocked 2023-09-29T13:50:25.628081+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 883, in exec_module 2023-09-29T13:50:25.628117+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed 2023-09-29T13:50:25.628142+00:00 app[web.1]: File "/app/./nanochat/asgi.py", line 16, in <module> 2023-09-29T13:50:25.628169+00:00 app[web.1]: … -
Error while reading a csv file in django rest framework
I am simply trying to read a csv file in django rest framework but its giving me this error and I can't seem to find what is the issue because I also tried reading the file in 'r' mode. Error _csv.Error: iterator should return strings, not bytes (the file should be opened in text mode) Views.py (csv reading code) csv_file = request.FILES["Bus"] data = [] with csv_file.open('r') as file: reader = csv.DictReader(file) for r in reader: print(r) I am using postman to send the csv file for testing -
AttributeError at / type object 'Basket' has no attribute 'values'
I've been stuck for a while trying to figure why Django throws this AttributeError.what shall i do? I've posted the necessary code below. basket/basket.py: class Basket(): def __init__(self, request): self.session = request.session basket = self.session.get('skey') if 'skey' not in request.session: basket = self.session['skey'] = {} self.basket = basket def add(self, product, qty): product_id = str(product.id) if product_id in self.basket: self.basket[product_id]['qty'] = qty else: self.basket[product_id] = {'price': str(product.price), 'qty': qty} self.save() def __len__(self): return sum(item['qty'] for item in self.basket.values()) basket/views.py: def basket_summary(request): basket = Basket(request) return render(request, 'store/basket/summary.html', {'basket': basket}) def basket_add(request): basket = Basket(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) product_qty = int(request.POST.get('productqty')) product = get_object_or_404(Product, id=product_id) basket.add(product=product, qty=product_qty) basketqty = basket.__len__() response = JsonResponse({'qty': basketqty}) -
How to Implement Payout Functionality in Django using Stripe API?
I am building a Django web application and I want to implement a payout functionality using the Stripe API(test mode). Here's what I need to achieve: 1.User clicks on the "Withdraw" button. 2.User enters their account details (such as bank account number, routing number, etc.) Then transfer the money to that account I have already installed the Stripe Python library and set up my Stripe API key. How can I achieve this functionality in my Django application? Any guidance on the Django views, forms, and Stripe API integration would be highly appreciated. -
“'AttributeError: ‘WSGIRequest’ object has no attribute ‘is_ajax’” when trying to use django with google map api when developing a website
I am currently following along with a tutorial (https://www.youtube.com/watch?v=wCn8WND-JpU) that utilizes Django, python, and front-end languages to develop a website with Google Maps API. This is for a project I want to pursue, but when I finished all the code it gave an error of ‘WSGIRequest’ object has no attribute ‘is_ajax’ when trying to get past the sign-in page. I reached out to the YouTuber and he gracefully told me I needed to replace the 'request.is_ajax()' to request.META. on the views.py. I tried doing that but it is still not working. Could anyone be able to help me resolve this problem? Here is the file he told me I needed to change the is_ajax: https://github.com/bobby-didcoding/did_django_google_api_tutorial/blob/main/users/views.py If anyone needs more information, please let me know! I 100% followed along the tutorial from start to finish. -
Small django form with only one checkbox and without submit button
I am doing a simple to do appin django and I want to be able to change the status of task to done after clicking the checkbox next to the task. I decied to do it using django forms but have trubble implementing it(the input has type="hidden" and even while trying diffrent method and I could see the checkbox but it wasnt working). As you can probably see I am new to django so feel free to point out my mistakes, even those unrelated to the question. Thanks forms.py from django import forms from django.forms import ModelForm from .models import ListItem class DateInput(forms.DateInput): input_type = 'date' class NewItemForm(ModelForm): # We can create here new fields for our form or use ones already created in models class Meta: model = ListItem fields = ['text', 'deadline', 'status'] widgets = { 'deadline': DateInput(), } class UpdateStatusForm(ModelForm): class Meta: model = ListItem fields = ['status'] widgets = { 'status': forms.CheckboxInput(), } models.py from django.db import models # Create your models here. class ListItem(models.Model): text = models.TextField(max_length=200) deadline = models.DateField(null = True, blank = True) status = models.BooleanField(null = False, default = False) def __str__(self): return self.text views.py from django.shortcuts import render, redirect from django.http … -
How to use select2 to change the default browser hover color?
Okay I have literally no clue what I'm doing but I've been trying to change the default blue color to a different custom color but I'm struggling with attaching the select2 to the properties, since it's in a loop: {% for field in form1 %} <tr> <th>{{ field.label_tag }} </th> <td>{{ field }}</td> {% if field.help_text %} <td><small class="text-muted">{{ field.help_text|safe }}</small></td> {% endif %} </tr> {% endfor %} {% for field in form_user_form %} <tr> <th>{{ field.label_tag }} </th> <td>{{ field }}</td> {% if field.help_text %} <td><small class="text-muted">{{ field.help_text|safe }}</small></td> {% endif %} </tr> {% endfor %} this is the script i tried using to access the propeties: <script> $("#id_hub").select2(); $(".form-control").select2(); # tried with a div class, and it doesn't work </script> In the example above I tried 2 approaches - using the id of one of the selects called id_hub and it doesn't work and the other is by using a div class which the selects are part from, no sucess. Here's the css for script2: .select2-results .select2-highlighted { background: red; color: #fff; } I've added those libraries to make sure it works but I might have something missing, please tell me if it's correct (I've never done anything … -
How to implement nested serializers in django rest framework
i'm trying to implement nested serializers. Serializers.py class BranchSerializer(serializers.ModelSerializer): class Meta: model = Branch fields = '__all__' class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = '__all__' to override branch in studentserializers and import branch details. -
How to use same serializer class for get and post method in Django 4.2?
I have been trying, but fail miserably, to use only a single serializer class for both post and get api call. I have a team model that has many to many relationship with the project model. I want to only use the id when am doing the post but when doing the GET request am able to view the details of the team team model from django.db import models from django.contrib.auth import get_user_model from . import Project class Team(models.Model): name = models.CharField(max_length=70) description = models.TextField() members = models.ManyToManyField(get_user_model()) projects = models.ManyToManyField(Project, blank=True, related_name='teams_projects') def __str__(self) -> str: return str(self.name) project model from django.db import models class Project(models.Model): PENDING = 'Pending' IN_PROGRESS = 'In Progress' COMPLETED = 'Completed' STATUS_CHOICES = [ (PENDING, 'Pending'), (IN_PROGRESS, 'In Progress'), (COMPLETED, 'Completed'), ] name = models.CharField(max_length=70) description = models.TextField() start_date = models.DateField() end_date = models.DateField() teams = models.ManyToManyField('Team', related_name='team_projects') status = models.CharField(max_length=20, choices=STATUS_CHOICES, default=PENDING) def __str__(self) -> str: return str(self.name) I have tried to use 'depth' but now am required provide team information instead of only id when doing the post. POST request body { "name": "string", "description": "string", "members": [ 0 ], "projects": [ { "name": "string", "description": "string", "start_date": "2023-09-29", "end_date": "2023-09-29", "status": … -
Digitalocean build stuck
I want to run a Python Django app on Digital Ocean and use this tutorial. It worked in the spring, but now the build stops (stuck) in the app upload stage. Any ideas? -
Access many-to-many field in Django template
I have a model Post and a model User, any User can leave one like to a post. class User(AbstractUser): pass class Post(models.Model): liked = models.ManyToManyField('User', blank=True, related_name='liked_post') How can I check in the django template if the current user liked the specific post or not? Previously I just wrote {% if user in post.liked.all %} without thinking, and now I understand that this must be a terrible implementation, because if the post has like 5000 likes, then django will have to iterate through a huge list. I could probably make an additional dictionary in the view (where the key is the ID of the post and value is a result of additional query), then pass this dictionary in the context, but there might be a better implementation. Can I just check in the template if user liked the post efficiently?