Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Two submit buttons for one form in Django to use two diffrent functions from views
I'm new in Django and now I'm working on my first project. My home.html file includes form (bootstrap class) witch contains entries to fill with data. These data are integer type. method='GET At the bottom of the form i have two submit buttons. My intention is that first of them is going to grab data from entries, calculate them and show results on site of browser using home function from views. Second button is going to grab the same data, calculate them and use them for conversion to pdf by ReportLab by some_view function in views. My questions are. How to keep imputed values in entries (now these fields are cleared after clicking submit button) How can I use these two buttons separately as I mentioned above. Now I can make only one button active and I have to choose If I want use one function or another. views.py import reportlab import io from django.http import FileResponse from reportlab.pdfgen import canvas #================================== from django.shortcuts import render from . import slownie def home (request): ls='' ls1='' ls3='' liczba= request.GET.get("li200") liczba1=request.GET.get("li100") liczba3=request.GET.get("li50") if liczba and liczba.isdigit(): liczba=int(liczba)*200 ls=slownie.slownie(int(liczba)) if liczba1 and liczba1.isdigit(): liczba1=int(liczba1)*100 ls1=slownie.slownie(int(liczba1)) if liczba3 and liczba3.isdigit(): liczba3=int(liczba3)*50 ls3=slownie.slownie(int(liczba3)) suma=0 if … -
ProgrammingError at /search/ function similarity
I am trying to add full text search to my django website, but I am getting this error: ProgrammingError at /search/ function similarity(character varying, unknown) does not exist LINE 1: SELECT COUNT(*) FROM (SELECT SIMILARITY("blog_post"."title",... Here is my SearchForm: class SearchForm: query = forms.CharField() And here is my post_search view function: def post_search(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] results = Post.published.annotate( similarity=TrigramSimilarity('title', query), ).filter(similarity__gt=0.1).order_by('-similarity') return render(request, 'blog/post/search.html', {'form': form, 'query': query, 'results': results}) I am using a Postgres database(version 13.1.1), Django 3.1 and Python 3.7.5 What is the problem here? -
Django Xhtml2PDF TypeError
I am trying to generate and force download a PDF from an HTML file in Django. Here are the steps I took and the codes I did: views.py: class GeneratePDF(GenericView): def get(self, request, *args, **kwargs): template = get_template('dashboard/generated.html') context = { "invoice_id": 123, "customer_name": "John Cooper", "amount": 1399.99, "today": "Today", } html = template.render(context) pdf = render_to_pdf('invoice.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" %("12341231") content = "inline; filename='%s'" %(filename) download = request.GET.get("download") if download: content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") utils.py: from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None The issue here is when I run the view, I get this error: TypeError at /pdf/ __init__() takes 1 positional argument but 2 were given Here is the full Traceback: Environment: Request Method: GET Request URL: http://localhost:8000/pdf/ Django Version: 2.2.3 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'dashboard.apps.DashboardConfig', 'crispy_forms', 'debug_toolbar', 'wkhtmltopdf', 'easy_pdf'] Installed Middleware: ['debug_toolbar.middleware.DebugToolbarMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: … -
Show results on the same page - Django class based views
First of all i wish Happy New Year to everyone! Keep spreading knowledge to the world! The last question of the year is related to Django CBV. I'm working on a portfolio project and currently i successfully listing all projects and all categories on a single page. Next step is when clicking on a category i would like to show/list all projects for this category but to return to the same page. So far i've created the following: urls.py urlpatterns = [ path('', WorkProjectsView.as_view(), name='work'), path('project/<slug:slug>', WorkProjectsDetailView.as_view(), name='project-detail'), path('project/<slug:slug>', CategoryDetail.as_view()), ] views.py class WorkProjectsView(ListView): model = Project template_name = 'work/work.html' queryset = Project.objects.all() context_object_name = 'projects' ordering = ['-date_created'] def get_context_data(self, *, object_list=None, **kwargs): context = super(WorkProjectsView, self).get_context_data(**kwargs) context['categories'] = Category.objects.all() return context class WorkProjectsDetailView(DetailView): model = Project template_name = 'work/project-detail.html' context_object_name = 'single_project' def get_context_data(self, **kwargs): context = super(WorkProjectsDetailView, self).get_context_data(**kwargs) return context class CategoryDetail(ListView): model = Category context_object_name = 'projects' def get_queryset(self): self.category = get_object_or_404(Category, pk=self.kwargs['pk']) return Project.objects.filter(category=self.category).order_by('-id') def get_context_data(self, **kwargs): context = super(CategoryDetail, self).get_context_data(**kwargs) return context work.html template <!--Project's list--> <div class="wrapper"> <div class="root-work"> <div class="container"> <div class="box-title" data-dsn-title="cover"> <h2 class="title-cover" data-dsn-grid="move-section" data-dsn-move="-70">Projects</h2> </div> <div class="filterings"> <div class="filtering-wrap"> <div class="filtering"> <div class="selector"></div> <button type="button" data-filter="*" class="active"> All </button> … -
I cannot run django project on new windows
I was creating a project using django. And I wanted to change the OS from 64 bit to 32 bit. On the new system, I installed a 32-bit version of Python, and when I ran the local server, I got this error: (venv) C:\Users\titooka\Desktop\django>python manage.py runserver This version of C:\Users\titooka\Desktop\django\venv\Scripts\python.exe is not compatible with the version of Windows you're running. Check your computer's system information and then contact the software publisher. So what are the correct steps to run the project on the new system so as not to lose it? -
Write a django ORM query to searcha value in the whole postgresql database
Write a query in the django ORM which perform the search in the each and every coloumn of the database the database's type is the -
throttle with function based views using Django Rest Framework
I am trying to throttle my API routes but I am unable to do it with functions using Django Rest Framework. All the documentations are for class-based views. I even tried a workaround as suggested here: Django Rest Framework Scope Throttling on function based view but it did not work. Here is my code snippets: Views: from django.core.paginator import Paginator from rest_framework.throttling import UserRateThrottle, AnonRateThrottle # Create your views here. def home(request): throttle_scope = 'perday' return render(request, 'home.html') def search(request): throttle_scope = 'search' query = request.GET['query'] response = requests.get('https://api.stackexchange.com//2.2/search/advanced?order=desc&sort=activity&q=' + query + '&site=stackoverflow') apiResponse = response.json() allData = [] for eachtitle in apiResponse['items']: allData.append(eachtitle) paginator = Paginator(allData, 10) pageNumber = request.GET.get('page', 1) page = paginator.get_page(pageNumber) return render(request, 'search.html', {"eachdata": page, "query": query}) Settings of my project: REST_FRAMEWORK = REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': [ 'example.throttles.BurstRateThrottle', 'example.throttles.SustainedRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'perday': '2/min', 'search': '5/day' } } I am not getting any errors, it just does not work. I have also added rest-framework in installed apps. -
Why am I obtaining "NoReverseMatch at /catalog/borrowed/" error in this Django application?
I am very new in Python and Django and I am finding some difficulties trying to implement what is shown by this Mozilla Django tutorial related to how to handle users\groups and permissions in Django framework: https://developer.mozilla.org/it/docs/Learn/Server-side/Django/Authentication I am following the steps illustrated in this tutorial. First of all, by the Django admin panel, I created the two groups of users: Then I created two user and I put the first one into the Librarian group and the second one into the Library Members group: Then following the previous tutorial I worked on the model\view related to the list of books borrowed by an user (an user belonging to the Library Members group). So into my catalog/models.py file I defined this BookInstance model class: import uuid # Required for unique book instances from datetime import date from django.contrib.auth.models import User # Required to assign User as a borrower class BookInstance(models.Model): """Model representing a specific copy of a book (i.e. that can be borrowed from the library).""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular book across whole library") book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True) imprint = models.CharField(max_length=200) due_back = models.DateField(null=True, blank=True) borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) @property def is_overdue(self): … -
search a value or keyword in the Entire postgres database from django ORM
I want to search the value in the whole or Entire database from the django ORM queries and the database's type is postgresql . there is a solution from the postgresql to search all the field but not from django ORM i know it is possible but can not find out anywhere . -
Total user in a day and in a week
I want to get the total number of users joined in a day and in a week, what I tried is as follows member_in_day = User.objects.exclude(is_staff=True)\ .annotate(day=TruncDay('date_joined')).values('date_joined') \ .annotate(total_members=Count('date_joined')) \ .order_by('-date_joined') member_in_week = User.objects.exclude(is_staff=True)\ .annotate(week=TruncWeek('date_joined')).values('date_joined') \ .annotate(total_members=Count('date_joined')) \ .order_by('-date_joined') The model is user the output I am getting is same for both queries, instead of a day it is giving other queryset also. <QuerySet [{'date_joined': datetime.datetime(2020, 12, 28, 16, 47, 40, 509134, tzinfo=), 'total_members': 1}, {'date_joined': datetime.datetime(2020, 12, 23, 11, 8, 19, 241355, tzinfo=), 'total_members': 1}, {'date_joined': datetime.datetime(2020, 12, 23, 11, 6, 14, 20673, tzinfo=), 'total_members': 1}, {'date_joined': datetime.datetime(2020, 12, 22, 9, 25, 45, 14632, tzinfo=), 'total_members': 1}, {'date_joined': datetime.datetime(2020, 12, 22, 9, 24, 25, 819750, tzinfo=), 'total_members': 1}, {'date_joined': datetime.datetime(2020, 12, 20, 12, 7, 37, 59113, tzinfo=), 'total_members': 1}]> members -
What is the best way to run a background process in Django?
I need to do the following things in Django Rest API. When the user sends a request, update the database with request info and run a Python process in the background, which will update the database after completion (Here I, No need to wait until the process has been completed). Need to return a response quickly to the user. Described in Steps: When the request comes in Update the database with request info Call python process (no need to wait) Return response I want to know what is the best way to achieve this (Running background task). Here I want to run the task in the background. not in a scheduled manner. Kindly let me know the best possible way. Thanks -
NoReverseMatch at /options/ Reverse for 'sales' with arguments '('',)' not found. 1 pattern(s) tried: ['sales/(?P<pk>\\d+)/$']
I am trying to learn django and I have encountered this error. It has persisted irrespective of the fact that I have tried the available SO remedies but for some reason, it refuses to go away. Can someone please see an error anywhere. show_options.html <a class="btn btn-sm btn-block bg-dark" style="color: black;" href="{% url 'Management:addProduct' %}"> Add </a> **<a class="btn btn-sm btn-danger" href="{% url 'Management:sales' add_user_sales.pk %}"> Add Sales </a>** <a class="btn btn-sm btn-danger" href="{% url 'Management:total' %}"> View Total </a> function to render my show_options page def show_options(request): return render(request, 'show_options.html', {}) function add_user_sales @login_required def add_user_sales(request , pk): current_user = request.user context = {} context["data"] = MadeSale.objects.get(id=pk) profiles = UserProfile.get_profile() for profile in profiles: if profile.profile_name.id == current_user.id: if request.method == 'POST': form = SalesForm(request.POST) if form.is_valid(): upload = form.save(commit=False) upload.posted_by = current_user upload.profile = profile upload.save() messages.success(request, f'Hi, Your data has successfully been updated' ) return redirect('addProduct') else: form = SalesForm() return render(request,'addProduct.html',{"user":current_user,"form":form}, context) my app urls from django.conf.urls import url from . import views from django.conf import settings from django.conf.urls.static import static from rest_framework.authtoken.views import obtain_auth_token app_name = 'Management' url(r'^sales/(?P<pk>\d+)/$', views.add_user_sales, name='sales') , -
Django Application stops launching
I am trying to launch my Django app that I deployed on heroku some month ago. It has been working all these days until today after I added some pictures. When I tried to launch it, I got an Application Error message. I tried to push it again and it was successfully deployed but it is not launching. What could be the problem, please? Here are the logs. 2020-12-31T10:06:41.595301+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 119, in init_process 2020-12-31T10:06:41.595302+00:00 app[web.1]: self.load_wsgi() 2020-12-31T10:06:41.595302+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-12-31T10:06:41.595303+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-12-31T10:06:41.595304+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-12-31T10:06:41.595304+00:00 app[web.1]: self.callable = self.load() 2020-12-31T10:06:41.595305+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2020-12-31T10:06:41.595305+00:00 app[web.1]: return self.load_wsgiapp() 2020-12-31T10:06:41.595305+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2020-12-31T10:06:41.595306+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-12-31T10:06:41.595306+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 358, in import_app 2020-12-31T10:06:41.595307+00:00 app[web.1]: mod = importlib.import_module(module) 2020-12-31T10:06:41.595307+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module 2020-12-31T10:06:41.595312+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2020-12-31T10:06:41.595313+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 994, in _gcd_import 2020-12-31T10:06:41.595314+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 971, in _find_and_load 2020-12-31T10:06:41.595314+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked 2020-12-31T10:06:41.595314+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 665, in _load_unlocked 2020-12-31T10:06:41.595315+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 678, in … -
How to fix 502 Bad Gateway Error in production(Nginx)?
When I tried to upload a big csv file of size about 600MB in my project which is hosted in the digital ocean, it tries to upload but shows 502 Bad Gateway Error (Nginx). This works fine while working locally. sudo tail -30 /var/log/nginx/error.log shows [error] 132235#132235: *239 upstream prematurely closed connection while reading response header from upstream, client: client's ip , server: ip, request: "POST /submit/ HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/submit/", host: "ip", referrer: "http://ip/" sudo nano /etc/nginx/sites-available/myproject shows server { listen 80; server_name ip; client_max_body_size 999M; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /root/static/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } nginx.conf user root; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; How can I fix this? -
Django 3 Routers with multiples schema in database
I have one database with multitples schemas, and I try to use routers to manage record informations. (https://www.amvtek.com/blog/posts/2014/Jun/13/accessing-multiple-postgres-schemas-from-django/) In my django settings: # myproject/myproject/settings.py ... DATABASE_ROUTERS = [ BASE_DIR / 'routers.sharingRouter.SharingRouter', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'options': '-c search_path=django' }, 'NAME': 'myproject', 'USER': 'user1', 'PASSWORD': 'pwd', 'HOST': '127.0.0.1', 'PORT': '5433', 'CHARSET': 'UTF8', }, 'sharing_writers': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'options': '-c search_path=sharing' }, 'NAME': 'myproject', 'USER': 'user2', 'PASSWORD': 'pwd', 'HOST': '127.0.0.1', 'PORT': '5433', 'CHARSET': 'UTF8', }, 'sharing_readers': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'options': '-c search_path=sharing' }, 'NAME': 'myproject', 'USER': 'user3', 'PASSWORD': 'pwd', 'HOST': '127.0.0.1', 'PORT': '5433', 'CHARSET': 'UTF8', }, } ... In my router: (like in official documentation: https://docs.djangoproject.com/en/3.1/topics/db/multi-db/) # myproject/routers/sharingRouter.py class SharingRouter(object): """. A router to control all database operations on models in the auth and contenttypes applications. """ route_app_labels = { 'sharing', } def db_for_read(self, model, **hints): """. Attempts to read sharing models go to sharing_readers. """ if model._meta.app_label in self.route_app_labels: return 'sharing_readers' return None def db_for_write(self, model, **hints): """. Attempts to write sharing model go to sharing_writers. """ if model._meta.app_label in self.route_app_labels: return 'sharing_writers' return None def allow_relation(self, obj1, obj2, **hints): """. Allow relations if a model in the sharing app is … -
django prevent models from updating based on conditions
I have a django model structured like this. class Role(models.Model): """ Represents a Global-Role object. Roles have their own: - Hex Color Code [Integer Representation] - Name [&] - Position - Permissions. A null positional value indicates a default role. As of now, clusters only have a single default role [@everyone]. """ class Meta: ordering = ['position', 'cluster'] required_db_features = { 'supports_deferrable_unique_constraints', } constraints = [ models.UniqueConstraint( fields=['position', 'cluster'], name='deferrable_unique_role_position', deferrable=models.Deferrable.DEFERRED ), models.UniqueConstraint( fields=['id', 'cluster'], name='relatively_unique_role_id' ) ] # cluster and id must both be primary key # to make sure the endpoints make sense objects = api_managers.RolesManager() id = models.BigAutoField(primary_key=True, db_index=True, editable=False, auto_created=True) permissions = BitField(flags=permission_flags, default=default_perm_flags, db_index=True) position = models.PositiveSmallIntegerField(null=True, blank=True, db_index=True, editable=True) name = models.CharField(max_length=100, validators=[MinLengthValidator(2)], db_index=True, default='new role') color = ColorField(db_index=True, default='#969696') cluster = models.ForeignKey('api_backend.DataSheetsCluster', on_delete=models.CASCADE, editable=False) created_at = models.DateTimeField(auto_now=True, editable=False, db_index=True) REQUIRED_FIELDS = [name, cluster] I want to make sure that Role objects whose position is NONE cannot have their name colour [or] position updated. Only the permissions field can be changed. Is there any way I can implement this in django? -
how to make relationship in django model
models.py So,here i want to make Invoicemgmt model in which i can have multiple entries for Invoice table having customer,project and Invoice_amount. Basically,requirement is that whenever i see 'view_Invoice' of some id,first i will see all data of that specific id on that page and then i want to have small table below for invoice_mgmt,where i can add amount received for that specific id invoice. class Invoice(models.Model): company_choice = ( ('VT_India', 'VT_India'), ('VT_USA', 'VT_USA'), ) company = models.CharField( max_length=30, blank=True, null=True, choices=company_choice) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) project = models.ForeignKey(Allproject, on_delete=models.CASCADE) invoice_title = models.CharField(max_length=15) invoice_id = models.IntegerField(primary_key=True) invoice_amount = models.IntegerField() invoice_date = models.DateField( blank=True, null=True) invoice_duedate = models.DateField( blank=True, null=True) invoice_description = models.TextField() def __str__(self): return self.invoice_title class Paymentmethod(models.Model): paymentmethod_id = models.IntegerField(primary_key=True) paymentmethod_name = models.CharField(max_length=15) def __str__(self): return self.paymentmethod_name class Invoicemgmt(models.Model): invoicemanagement_id = models.IntegerField(primary_key=True) invoice_received = models.IntegerField() date = models.DateField( blank=True, null=True) payment_method = models.ForeignKey(Paymentmethod, on_delete=models.CASCADE) "So, basically i want to have multiple entries in invoice mgmt table for one specific invoice table id(one specific data)" -
relationship choices¶widget showing text
I would like to display choices of Test_Baustoff->art Model in my Test_Objekt Model Form. Right now i am trying to solve it with a Widget... Models: class Test_Objekt(models.Model): baustoffid = models.ForeignKey(Test_Baustoff, on_delete=models.CASCADE) bezeichnung = models.CharField(max_length=100, default='', blank=True) class Test_Baustoff(models.Model): art = models.CharField(max_length=100) wert = models.IntegerField(default='0') Forms: (found this code in the django docs... don't know if i am using it in the right way??) class BaustoffidSelect(forms.Select): def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): option = super().create_option(name, value, label, selected, index, subindex, attrs) if value: option['attrs']['data-wert'] = value.instance.wert return option class ObjektForm(forms.ModelForm): class Meta: model = Test_Objekt fields = ['bezeichnung', 'baustoffid', 'bauweiseid', 'dickeaussenwand', 'dickedaemmung', 'fensterqualitaet'] labels = {'bezeichnung': 'Objekt-Bez'} widgets = {'baustoffid': BaustoffidSelect} html template: <table class="table table-bordered table-light"> {{objekt_form.as_table}} </table> For the moment, I don't find a way to solve my problem. I looked some tutorials or StackOverflow questions but nothing up to now. Do you have any idea about this handling? -
How to filter DB query with OR in Django
I am trying to structure a WHERE question LIKE 'Who%' OR question LIKE 'What%' SQL query from inputs of a POST request. What is the correct way to do this? https://docs.djangoproject.com/en/3.1/topics/db/queries/#complex-lookups-with-q-objects from django.db.models import Q def getuserlist(request): if request.method == "POST": showall = request.POST['showall'] showfl_1 = request.POST['showfl_1'] showfl_2 = request.POST['showfl_2'] if showall: filt = Q(listing=any) elif showfl_1: filt = Q(listing="Filtered1") elif showfl_2: filt = filt | Q(listing="Filtered2") searchresult = list(User_data.objects.filter(listing=filt).values_list("Country","gender","listing").order_by('-added_date')) return searchresult -
LimitOffsetPagination with viewsets.ViewSet in Django Rest Framework
Can we use LimitOffsetPagination with viewsets.ViewSet in Django Rest Framework. Below is how my list view looks: def list(self, request): # serializer for validating list request serializer = UserIndexSerializer(data=request.query_params) if serializer.is_valid(): users = User.objects.all() serializer = UserGetSerializer(users, many=True) response = {"users": serializer.data, "total": len(serializer.data)} return AppResponse.success("User list found.", response) return AppResponse.error(serializer.errors, None, http_error_code=400) -
Django: no such table: create_genres
I have run makemigrations and migrate but both give the same error. I found that the code below is what causes the error. I have also deleted migrations folder and remade it with init file and deleted the database but doesn't seem to help. This code was working fine for a while but now it keeps giving the same error. models.py class Genres(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural = "Genres" class Post(models.Model): genres = models.ManyToManyField(Genres) -
Why are models having there parent class names in admin Django
I have created models like this class User(AbstractUser): login_count = models.PositiveIntegerField(default=0) class Supplier(User): company_name= models.CharField(max_length=30) company_domain=models.CharField(max_length=30) class Worker(User): ACCOUNT_TYPE = ( ('1', 'Admin'), ('2', 'Regular'), ) account_type = models.CharField(max_length=1, choices=ACCOUNT_TYPE) and in the users.admin.py, I have admin.site.register(Supplier) admin.site.register(Worker) Why is it that I have all models names as Users in the Django Admin? instead of Workers and Suppliers? -
ASIC BRS SOAP API service Binding Bug
I was pulling my hair building ASIC(Australia) Business Registration (BRS) App for a client. ASIC SOAP API in UAT has an a bug in a service binding within a soap response. It returns an incorrect URL. -
'loginForm object has no attribute 'is_valid' in django why i'm getting this
'loginForm' object has no attribute 'is_valid' can anyone have solution why i'm getting this i just trey to get data and the form it shows error on this line is_valid() in django >login.py <form action ='' method ='POST' > {% csrf_token %} <div class="form-group"> <label for="formGroupExampleInput">User Name</label> <input type="text" id='username' name = 'username' class="form-control" id="formGroupExampleInput" placeholder=""> </div> <label for="inputPassword5">Password</label> <input type="password" name ='password' id="password" class="form-control" aria-describedby="passwordHelpBlock"> <input class="btn btn-primary my-3" type="submit" value="Submit"> </form> </div> > views.py def login(request): if not request.user.is_authenticated: if request.method == 'POST': form = loginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username , password=password) if user is not None: login(request , user) messages.success(request,'logged in Successfully !!') return HttpResponseRedirect('dashbord') else: form = loginForm() else: return HttpResponseRedirect('dashbord') return render(request,'login.html',{'form':form}) def logout(request): return HttpResponseRedirect('/') > models.py class loginForm(models.Model): username = models.CharField(max_length=50) password = models.EmailField(max_length=200 ) -
manyToMany django form
i have a class PhoneBook and a class Campaign and these tow have ManyToMany relation.... when i use Modelform for create Campaign it shows me all the Phonebooks in checkbox...but i want just show current user's PhoneBooks ..not all the PhoneBooks!!!! what can i do? class Campaign(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="کاربر") title = models.CharField(max_length=200, verbose_name="عنوان کمپین") phone_book = models.ManyToManyField(PhoneBook, verbose_name='دفترچه تلفن') message_price = models.PositiveBigIntegerField(verbose_name="نرخ هر پیام") daily_budget = models.PositiveBigIntegerField(verbose_name="سقف بودجه ی روزانه") class CreateCampaignForm(forms.ModelForm): class Meta: model = Campaign fields = ("title", "phone_book", "message_price", "daily_budget")