Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why one of my components does not work in my django-react app?
I'm new to react and for my project i need carousel which i used react-multi-carousel package for that.after that i connected my react app to my django app with using npm run build and now the problem is that this component (named it slider.js )dosen't work fine it just render the buttoms but not images and even styles of it i but it's work just fine in react didn't find solutions by my searches heres the project directory tree and heres the view of how my component looks like and django static in settings.py: STATIC_URL = '/assets/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [os.path.join(BASE_DIR, '../frontend/build/assets')] and in fronted/build/index.html: <!doctype html> <html lang="en"> <head> {% load static %} <meta charset="utf-8"/> <link href="favicon.ico"/> <meta name="viewport" content="width=device-width,initial-scale=1"/> <meta name="theme-color" content="#000000"/> <meta name="description" content="Web site created using create-react-app"/> <link href="./logo192.png"/> <link href="./manifest.json"/> <link type="text/css" href="{%static 'styles.css' %}" rel="stylesheet" > <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css"> <link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700,800,900" > <title>React App</title><script defer="defer" src="{% static 'js/main.891355db.js'%}"> </script> <link href="{% static 'css/main.450b181d.css'%}" > </head> <body style="padding:0;margin:0"> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script> </body> </html> -
request.user not available in Streamblocks subtemplate
In my main template I can call: {% load static wagtailuserbar wagtailcore_tags %} {% load navigation_tags %} {% if request.user.is_authenticated %} You're logged in {% endif %} but if I call this in my StreamBlock sub-template, it doesn't work. {% load wagtailcore_tags wagtailimages_tags %} {% if request.user.is_authenticated %} <div class="container"> ... </div> {% endif %} Any ideas? -
requests.exceptions ConnectionError Connection aborted.', ConnectionResetError(104, 'Connection reset by peer')
We have implemented a program to broadcast the commentary of sports, which will take data from firebase when firebase is triggered by data and send data to telegram channel. Everything has been good for so long. But recently we have been facing this connection reset issue? Can anyone please help? I have already tried to use time.sleep() function. But still there is issue. This problem exactly happens after running commentary for some time. It works well for sometime and then comes this error. Note: During commentary we may send 4/5 request per second. [2022-07-05 17:15:34,842: WARNING/ForkPoolWorker-2] Traceback (most recent call last): [2022-07-05 17:15:34,843: WARNING/ForkPoolWorker-2] File "/usr/local/lib/python3.9/site-packages/urllib3/connectionpool.py", line 703, in urlopen [2022-07-05 17:15:34,845: WARNING/ForkPoolWorker-2] [2022-07-05 17:15:34,846: WARNING/ForkPoolWorker-2] httplib_response = self._make_request( [2022-07-05 17:15:34,846: WARNING/ForkPoolWorker-2] [2022-07-05 17:15:34,847: WARNING/ForkPoolWorker-2] File "/usr/local/lib/python3.9/site-packages/urllib3/connectionpool.py", line 386, in _make_request [2022-07-05 17:15:34,848: WARNING/ForkPoolWorker-2] [2022-07-05 17:15:34,849: WARNING/ForkPoolWorker-2] self._validate_conn(conn) [2022-07-05 17:15:34,849: WARNING/ForkPoolWorker-2] [2022-07-05 17:15:34,850: WARNING/ForkPoolWorker-2] File "/usr/local/lib/python3.9/site-packages/urllib3/connectionpool.py", line 1040, in _validate_conn [2022-07-05 17:15:34,851: WARNING/ForkPoolWorker-2] [2022-07-05 17:15:34,852: WARNING/ForkPoolWorker-2] conn.connect() [2022-07-05 17:15:34,852: WARNING/ForkPoolWorker-2] [2022-07-05 17:15:34,853: WARNING/ForkPoolWorker-2] File "/usr/local/lib/python3.9/site-packages/urllib3/connection.py", line 414, in connect [2022-07-05 17:15:34,854: WARNING/ForkPoolWorker-2] [2022-07-05 17:15:34,855: WARNING/ForkPoolWorker-2] self.sock = ssl_wrap_socket( [2022-07-05 17:15:34,855: WARNING/ForkPoolWorker-2] [2022-07-05 17:15:34,856: WARNING/ForkPoolWorker-2] File "/usr/local/lib/python3.9/site-packages/urllib3/util/ssl_.py", line 449, in ssl_wrap_socket [2022-07-05 17:15:34,857: WARNING/ForkPoolWorker-2] [2022-07-05 17:15:34,858: WARNING/ForkPoolWorker-2] ssl_sock = _ssl_wrap_socket_impl( [2022-07-05 … -
Adapt global PAGE_SIZE setting in Django REST Framework's browsable API to a different local PAGE_SIZE setting
We are using the Django REST Framework with pagination and a browsable API. The global parameter for the page size in settings.py is set to 10000 in order to get higher performance when accessing the API via HTTP requests which works well: REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", "rest_framework.authentication.TokenAuthentication", ], "DEFAULT_FILTER_BACKENDS": ["django_filters.rest_framework.DjangoFilterBackend"], "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination", "PAGE_SIZE": 10000, } Now the problem is that this is directly linked to the browsable API which also lists 10000 entries per page. This of course takes very long or even breaks within certain browsers. Is there a way to change this behaviour locally for the browsable API? Thanks in advance! -
Writing to Firestore with Firebase Admin SDK causes app to freeze
I am trying to use Firebase Admin SDK in a Django app using a service account. I followed the instructions as per the official documentation. However, the app gets stuck at the point when Firebase Admin is attempting OAuth2 using Google APIs. My code is as follows: import firebase_admin from firebase_admin import credentials from firebase_admin import firestore cred = credentials.Certificate(key_path)# path to serviceAccountKey firebase_admin.initialize_app(cred) db = firestore.client() doc_ref = db.collection(u'users').document(u'alovelace') # The following causes the app to freeze doc_ref.set({ u'first': u'Ada', u'last': u'Lovelace', u'born': 1815 }) The last message displayed in logs is: 2022-07-06 06:23:38,519 DEBUG Making request: POST https://oauth2.googleapis.com/token The app freezes after that message with no additional info. Any ideas why is this happening? -
Problems with connecting django codebase which in wsl to mysql database on xampp in windows
A few weeks ago I was working on an old laptop on a project in wsl connected to mysql database in xampp on windows which had no problems. I had to switch to a new laptop in which im facing the error. ERROR 2003 (HY000): Can't connect to MySQL server on 'localhost:3306' (111) [![Xampp control panel][1]][1] Configuration settings in settings.py file DATABASES = { 'default': { 'NAME': 'care_new', 'ENGINE': 'django.db.backends.mysql', 'USER': 'Canopus', 'PASSWORD': 'care', 'HOST': '127.0.0.1', 'PORT': 3306, 'OPTIONS': { 'autocommit': True, }, } } I'm using a venv. python - 3.8.10 pip - 22.1.2 using the command sudo lsof gives this output (venv) vishal@BatComputer:~/caremigration$ sudo lsof -i :3306 (venv) vishal@BatComputer:~/caremigration$ Please help me connect to this database in windows. I have tried out different stackoverflow answers such as editing my.cnf file and such. Also worth mentioning, in my linux folders, my.cnf file has no content, its actually named as mysqld.cnf [1]: https://i.stack.imgur.com/va6DF.png -
Django import-export error reporting for rows
I am using Django Import export for creating a data upload endpoint. However, in case there is an error while uploading the data, I want to know which row numbers have an issue and what the issue is. If there is an error on line 50 and line 60, then it should tell me that both lines 50 and 60 have errors. Currently, if I use raise_errors method then it only shows the error on line 50 and then stops checking. I can do a line-by-line iteration but that method is considerably slow. How can I achieve this? -
default=Ture not working in BoloeanField using Django
class SoftDeleteTimeStampMixin(TimeStampedModel): is_active = models.BooleanField(default=True) class Meta: abstract = True i created an abstract class for using for all models here model where I use class Schedule(SoftDeleteTimeStampMixin): day_of_week = models.CharField(max_length=200) partner = models.ForeignKey(User, on_delete=models.PROTECT, related_name="schedules") def __str__(self): return f"Schedule of {self.partner.username} on {self.day_of_week}" when I create an instance of my model is_active value is false, but it should be True -
Django DB Migration InconsistentMigrationHistory when running migrate
I am unable to migrate my django after running python ./manage.py migrate. This is what showmigrations is displaying customerweb [X] 0001_initial [X] 0002_user_industry [X] 0003_auto_20220209_1737 [X] 0004_userconfiguration_night_surcharge_exempt [ ] 0005_auto_20220614_1100 [X] 0006_orderdelivery_is_order_unique [ ] 0007_orderdelivery_client_reference_no I have tried --fake as well as trying to move back by one migrate using python ./manage.py migrate <app_name> <000x_migrate_file> all these is not working as the exeception keeps prompting InconsistentMigrationHistory. I have tried deleting the migration folders as well (keeping init only) but does not work as well. -
How to host django project in production
I created a Django project with the PHPMyAdmin(MySQL) database. Now I want to host my project so that my client from the USA can use it very easily. Can anyone explain to me the steps to hosting a website? -
Change DjangoRestFramework default logging format
Currently, every request I send to the django app, it auto logs the same as shown below: "GET /api/v1/account/test_1 HTTP/1.1" 200 5586 "POST /api/v1/account/test_2 HTTP/1.1" 201 5586 How can I change the above log format to look like this instead: '{"api_method":"GET", "api_endpoint":"/api/v1/account/test_1", "api_status": 200}' '{"api_method":"POST", "api_endpoint":"/api/v1/account/test_2", "api_status": 201}' -
Python Django User Access to Custom Dashboard
I developing a web application using DJANGO python lib the super admin dashboard has the USER creation, Group Creation and Permission Access in the Backend. I have to embed the same access in the custom Dashboard Is there any default function which we can alter the font-end and access the backend for user and group permission -
Django error value error: The view sub_categories.views.insert_sub_categories didn't return an HttpResponse object. It returned None instead
I am tasked with making a shopping crud project with models Products,categories,sub_categories,size,colors. Categories and subcategories are connected via foreign keys and I am using SERAILIZERS.the problem is that when I try to insert the data into sub Categories it doesnt come in both the database and the webpage below are the models class Categories(models.Model): category_name = models.CharField(max_length=10) category_description = models.CharField(max_length=10) isactive = models.BooleanField(default=True) class SUBCategories(models.Model): category_name = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories_name = models.CharField(max_length=20) sub_categories_description = models.CharField(max_length=20) isactive = models.BooleanField(default=True) show and insert function of sub_categories def show_sub_categories(request): showsubcategories = SUBCategories.objects.filter(isactive=True) #print(showsubcategories) serializer = SUBCategoriesSerializer(showsubcategories,many=True) print(serializer.data) return render(request,'polls/show_sub_categories.html',{"data":serializer.data}) def insert_sub_categories(request): if request.method == "POST": insertsubcategories = {} insertsubcategories['sub_categories_name']=request.POST.get('sub_categories_name') insertsubcategories['sub_categories_description']=request.POST.get('sub_categories_description') form = SUBCategoriesSerializer(data=insertsubcategories) if form.is_valid(): form.save() print("hkjk",form.data) messages.success(request,'Record Updated Successfully...!:)') print(form.errors) return redirect('sub_categories:show_sub_categories') else: print(form.errors) else: insertsubcategories = {} form = SUBCategoriesSerializer(data=insertsubcategories) category_dict = Categories.objects.filter(isactive=True) category = CategoriesSerializer(category_dict,many=True) hm = {'context': category.data} if form.is_valid(): print(form.errors) return render(request,'polls/insert_sub_categories.html',hm) html of the insert page and show page respectively <tr> <td>category name</td> <td> <select name="category_name" id=""> {% for c in context %} <option value="{{c.id}}">{{c.category_name}}</option> {% endfor %} </select> </td> </tr> <tr> <td>sub categories Name</td> <td> <input type="text" name="sub_categories_name" placeholder="sub categories "> </td> </tr> <tr> <td>Sub categories Description</td> <td> <textarea name="sub_categories_description" id="" cols="30" rows="10"> </textarea> </td> </tr> <tr> … -
How to fix cannot find Chrome binary using webdriver-manager
I use webdriver-manager==3.7.1 driver = webdriver.Chrome(ChromeDriverManager().install()) I run on Local in Visual Studio Code, it's normal But when I deploy the project to cPanel hosting, when I run it, I get an error Message: unknown error: cannot find Chrome binary Full error here: You go to the website https://gettainguyen.com/ You paste the link for example: https://lovepik.com/image-401335339/summer-summer-elements.html into the input box and click the Get Link button It will show an error I don't know how to fix it. Help me please. Thank you. -
django channels trigger websocket send in http view
I am a beginner on web socket and channels, experimenting with a simple notification app. notification model class Note(models.Model): profile = models.ForeignKey('users.Profile', on_delete=models.CASCADE, related_name='notes', blank=1, null=1) createTime = models.DateTimeField(default=now) url = models.CharField(max_length=255, blank=True, null=True) type = models.CharField(max_length=50, blank=True, null=True) title = models.CharField(max_length=50, blank=True, null=True) content = models.CharField(max_length=255, blank=True, null=True) read = models.BooleanField(default=False) @staticmethod def trigger(url, type, title, content, profile): try: notes = Note.objects.filter(url=url, type=type, title=title, content=content) flag = 1 for note in notes: if note in profile.notes.all(): flag = 0 if flag: raise Note.DoesNotExist except Note.DoesNotExist: note = Note(url=url, type=type, title=title, content=content) note.save() profile.notes.add(note) profile.save() return note @staticmethod def dismiss(**kwargs): try: Note.objects.filter(**kwargs).delete() except Note.DoesNotExist: pass static method trigger is called in other http views to generate notification after duplication validation. For instance: @csrf_exempt def articleLikePost(request): if request.is_ajax() and request.method == 'POST': try: article = Article.objects.get(pk=request.POST['article']) if article in request.user.likedArticle.all(): # unlike article.like.remove(request.user) article.save() Note.dismiss( sender=request.user, points=5, accepter=article.author, url=str(reverse_lazy('article-detail', kwargs={'pk': article.pk})), type='up', title='Aritcle receives likes', content=f'{request.user.username} liked your article {article.title}', ) return JsonResponse({'action': 'unlike'}, status=200) else: # like article.like.add(request.user) article.save() Note.trigger( sender=request.user, points=5, accepter=article.author, url=article.detailLink(), type='up', title='Aritcle receives likes', content=f'{request.user.username} liked your article {article.title}', ) return JsonResponse({'action': 'like'}, status=200) except Article.DoesNotExist: return JsonResponse({'e': 'Article not found'}, status=400) return JsonResponse({}, status=400) I … -
python django image not found in object imagefield url
Sorry if this question is dumb, I am very new to programming and django. I hope I have given enough information below, but please ask for more information if needed. I have two object types, user and profile, with a one to one relationship. I am trying to access the profile photo through, {{ user.profile.photo.url }} in my html. the url: /media/profile_pics/stock_user_image_GKS3UxI.jpg I have tried changing media root, changing dir placement, and have checked that pillow is installed correctly. but pillow is not in my INSTALLED_APPS list, as i do not know how to call it. is that necessary? The get request is sent but finds no file. The file is there, and is correct. but I receive this in console. [05/Jul/2022 21:58:57] "GET /user/myprofile HTTP/1.1" 200 3485 Not Found: /media/profile_pics/stock_user_image_GKS3UxI.jpg views: from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm from django.contrib.auth.decorators import login_required # Create your views here. def user_register_view(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, 'Your account is now active!') return redirect('user-login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def user_myprofile_view(request): return render(request, 'users/profile.html') models: from django.db import models from django.contrib.auth.models import … -
NoReverseMatch at /force-password-change/ when changing password
I am using django user system, There comes the error like this when user trying to change the password, It looks like some url routing is wrong. NoReverseMatch at /force-password-change/ Reverse for '' not found. '' is not a valid view function or pattern name. Request Method: POST Request URL: http://localhost.example.jp:8010/force-password-change/ Django Version: 3.2.7 Exception Type: NoReverseMatch Exception Value: Reverse for '' not found. '' is not a valid view function or pattern name. Exception Location: /Users/whitebear/.local/share/virtualenvs/example-admin-mg9y4sUV/lib/python3.9/site-packages/django/urls/resolvers.py, line 694, in _reverse_with_prefix Python Executable: /Users/whitebear/.local/share/virtualenvs/example-admin-mg9y4sUV/bin/python Python Version: 3.9.10 Python Path: ['/Users/whitebear/MyCode/httproot/suntory_cdk/example-admin', '/Users/whitebear/MyCode/httproot/suntory_cdk/example-admin/example-shared-models', '/Users/whitebear/MyCode/httproot/suntory_cdk/example-admin/$PYTHONPATH', '/Users/whitebear/.pyenv/versions/3.9.10/lib/python39.zip', '/Users/whitebear/.pyenv/versions/3.9.10/lib/python3.9', '/Users/whitebear/.pyenv/versions/3.9.10/lib/python3.9/lib-dynload', '/Users/whitebear/.local/share/virtualenvs/example-admin-mg9y4sUV/lib/python3.9/site-packages'] This error happens arround here, in users/views.py class PasswordChangeView(LoginRequiredMixin, FormView): template_name = "users/password_change.html" form_class = PasswordChangeForm success_url = reverse_lazy("") def get(self, request, *args, **kwargs): form = self.form_class() user = get_object_or_404(User, username=self.request.user.username) return render(request, self.template_name, {"form": form, "email": user.email}) def post(self, request, *args, **kwargs): print("password is posted") form = self.form_class(request.POST) if form.is_valid(): data = form.cleaned_data user = get_object_or_404(User, username=request.user.username) user.set_password(data["new_password1"]) user.is_require_pwd_change = False user.save() return super(PasswordChangeView, self).form_valid(form) return super(PasswordChangeView, self).form_invalid(form) -
Merch() missing 1 required positional argument: 'merch_id' django
I'm making a bandpage and trying to have merchandise items show up on the page but I'm getting a Merch() missing 1 required positional argument: 'merch_id' I've tried to change my views.py and urls.py any halp would be awesome. views.py from django.shortcuts import render from django.http import HttpResponse from .models import merch from django.template import loader # Create your views here. def index(request): return HttpResponse("Hello you're at the Nowhere fast homepage.") def about(request): return HttpResponse("This is the about band.") def contact(request): return HttpResponse("This is the contact page.") def songs(request, song_id): return HttpResponse("%s." % song_id) def shows(request, show_id): return HttpResponse("%s." % show_id) def Merch(request, merch_id): merch_list = merch.objects.get(pk=merch_id) context = {'merch_list': merch_list} return render(request, 'bandpage/index.html', context) # def index(request, merch_id): # merch_list = Merch.objects.order_by('name', merch_id)[:5] # output = ', '.join([p.name for p in merch_list]) # return render(request, 'bandpage/index.html', {'merch_list':merch_list}) # def index(request): # merch_list = Merch.objects.order_by('name')[:5] # template = loader.get_template('bandpage/index.html') # context = { # 'merch_list': merch_list, # } # return HttpResponse(template.render(context, request)) you can see some of the comment out code of things I've tried here. urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('about/', views.about, name='about'), path('contact/', views.contact, name='contact'), path('songs/', views.songs, name='songs'), … -
How to get data from different models in Django Rest-API
I have three models, Student, Course and Homework: What is happening is that I have a front end that the user inputs those fields in ie. all fields from Student, Course and Homework and once those fields are filled out they suppose to click submit to perform CREATE operation. And that's triggers the CreatedData function in views.py. I have found some relevant examples but still, my serializer is only returning the fields from the Student model for CRUDoperation. I'm not able to get the Course & Homework models fields. Return different serializer after create() in CreateAPIView in Django REST Framework Django Rest API. Get all data from different models in a single API call How to retrieve and create data from model via DJANGO REST API? how to post multiple model data through one serializer in django rest api models.py class Student(models.Model): student_id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) firstName = models.CharField(max_length=20) age = models.IntegerField(default=18) class Course(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) courseName = models.CharField(max_length=20) courseYear = models.IntegerField(default=2021) student = models.ManyToManyField(Student, related_name='courses') class Homework(models.Model): student_id = models.ForeignKey(Student, on_delete=models.CASCADE) hwName = models.CharField(max_length=20) hwPossScore = models.IntegerField(default=100) course = models.ForeignKey(Course, related_name='homeworks', on_delete=models.CASCADE, null=True, blank=True) students = models.ManyToManyField(Student) For these three models I have three serializer … -
javascript only works when embedded in html [duplicate]
I have a JavaScript function to toggle visibility of a password. The feature works correctly when the JS is embedded straight in the html with <script> tags, but does not work when I run it from a separate JS file in the static/hello/_js folder. The console logs an error: login.js:3 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') HTML: {% extends "hello/layout.html" %} {% block style %} <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200" /> {% endblock %} {% block scripts %} {% load static %} <script src="{% static 'hello\_js\login.js' %}"></script> {% endblock %} {% block content %} <hr> <div class="form"> <form> <h2 style="text-align:center">Login</h2> <div> <label for="username">Username:</label> <input type="text" name="username" id="username" class="field"> </div> <br> <div> <label for="user-pw">Password:</label> <input type="password" id="user-pw" name="user-pw" class="password"> <i id="visibilityBtn"><span id="icon" class="material-symbols-outlined">visibility_off</span></i> </div> <button style="text-align: center;">login</button> </form> </div> {% endblock %} and the JavaScript: const visibilityBtn = document.getElementById("visibilityBtn"); visibilityBtn.addEventListener("click", toggleVisibility); function toggleVisibility() { const passwordInput = document.getElementById("user-pw"); const icon = document.getElementById("icon") if (passwordInput.type === "password") { passwordInput.type = "text"; icon.innerText= "visibility" } else { passwordInput.type = "password"; icon.innerText = "visibility_off" } } -
Click the front of the button to execute the command line in django admin website
I'm new to Django. There are the following scenarios: In Django admin website, There is an open button in the front interface, clicked the button need to run the code "notepad fileName". How to write this code in adimn.py or in other py file? -
Why is my table not filtering? django-filters
So yeah, it isn´t filtering. I enter the search and the table doesn't filter. I have checked my code numerous times and it just ain't working. I need someone else's feedback because I'll go crazy. It probably is a very stupid mistake but you know how these things go. So, I've got my: #filters.py import django_filters from .models import * class ContratosFilter(django_filters.FilterSet): class Meta: model = Contratos fields = ['id', 'name', 'contractor', 'contractee'] #views.py def contratostabla(request): contract=Contratos.objects.all() paginator = Paginator(contract, 12) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) myFilter= ContratosFilter(request.GET, queryset=Contratos.objects.all()) return render(request, 'contracts.html', {'contract':contract, 'myFilter':myFilter, 'page_obj':page_obj}) #contracts.html <form method="get"> {{myFilter.form}} <button class="btn btn-primary btn-sm" type="submit">Search</button> </form> My view also includes paginator and the table as you can see. The terminal says GET /contracts/?id=3&name=&contractor=&contractee=& . I would guess it is not posting it. I have no idea what is stopping it from working. -
Django mercadopago integracion ejemplo
Hola necesito ayuda con la integracion de mercadopago con django... si alguien tendria algun repositorio de ejemplo que se funcional agradecerias -
Wagtail - selected_related on fieldpanels?
I've registred a snippet which has a foreign key to a somewhat huge table in wagtail 3. When attempting to click on an entry to see the detail view which displays the fieldpanels, I have about 5-10 seconds of loading which tells me massive amounts of queries are being made. Is there any way to use select_related() on a fieldpanel field? In this particular case I'd like to use select_related on "day" @register_snippet class EventSnippet(index.Indexed, Event): panels = [ FieldPanel('name'), FieldPanel('day'), ] search_fields = [ index.SearchField('name', partial_match=True), index.RelatedFields('day', [index.SearchField('calendar_year')]), ] class Meta: proxy = True -
How do you add one object to a Django Model that has a ManyToManyField?
I am trying to create a social media type site that will allow a user to follow and unfollow another user. followers has a ManyToManyField because a user can have many followers. models.py class Follower(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default="") followers = models.ManyToManyField(User, related_name="followers") views.py def username(request, user): #get user user = get_object_or_404(User.objects, username=user) posts = Post.objects.filter(user=user).order_by('-date_and_time') #follow button code follow_or_unfollow = '' try: following = get_object_or_404(Follower, Q( user=user) & Q(followers=request.user)) print(following) except: following = False if following: follow_or_unfollow = True else: follow_or_unfollow = False if request.POST.get('follow'): follower = Follower.objects.create(user=request.user) follower.followers.add(*user) follow_or_unfollow = False elif request.POST.get('unfollow'): follow_or_unfollow = True #following.delete() When it gets the 'follow' POST request, I want it to add the user who sent it (the one that is logged in) to be added to the followers. Right now, I am getting this error when I try to do that. TypeError: django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager.add() argument after * must be an iterable, not User I know it says that it has to be iterable, but is there any way to just add one object at a time. Also, how would you delete this particular object?