Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
RingCentral OAuth with Django
I'm working through RingCentral's Authorization Flow Quick Start App using Django. This required making a few changes to the Flask code provided, but most of the flow is working. The index page sends me to RingCentral login, which then sends me back to the test page as it should. But when I click on any of the three links on that page I get the same error: AttributeError at /test/ 'bytes' object has no attribute 'get' Here's the Django view that handles the test page (slightly modified from the Flask code provided): def test(request): platform = SyncConfig.rcsdk.platform() platform.auth().set_data(request.session['sessionAccessToken']) if platform.logged_in() == False: return index(request) api = request.GET.get('api') if api == "extension": resp = platform.get("/restapi/v1.0/account/~/extension") return resp.response()._content elif api == "extension-call-log": resp = platform.get("/restapi/v1.0/account/~/extension/~/call-log") return resp.response()._content elif api == "account-call-log": resp = platform.get("/restapi/v1.0/account/~/call-log") return resp.response()._content else: return render(request, 'sync/test.html') And sync/test.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <b><a href="/logout">Logout</a></b> <h2>Call APIs</h2> <ul> <li><a href="/test?api=extension">Read Extension Info</a></li> <li><a href="/test?api=extension-call-log">Read Extension Call Log</a></li> <li><a href="/test?api=account-call-log">Read Account Call Log</a></li> </ul> </body> </html> Has anyone setup a Django authorization flow for RingCentral and can show me where this is breaking? -
Transform function view in Class Based View in Django
I have an archive page with a form that has 2 select option inputs with year and months and I want to select from the database the objects that were created at the year and month selected from the page, I have this function view that works fine but I need the CBV version, I tried with View but it's not working, please a little of help. def archive(request): if request.method == 'POST': year = datetime.strptime(request.POST.get('year'), '%Y') month = datetime.strptime(request.POST.get('month'), '%m') incomes = Income.objects.filter( user=request.user, created_date__year=year.year, created_date__month=month.month) spendings = Spending.objects.filter( user=request.user, created_date__year=year.year, created_date__month=month.month) else: incomes = Income.objects.filter(user=request.user) spendings = Spending.objects.filter(user=request.user) year, month = False, False context = { 'title': 'Archive', 'spendings': spendings, 'incomes': incomes, 'currency': Profile.objects.get(user=request.user).currency, 'total_incomes': round(assembly(incomes), 2), 'total_spendings': round(assembly(spendings), 2), 'total_savings': round(assembly(incomes) - assembly(spendings), 2), 'year': year, 'month': month, } return render(request, 'users/archive.html', context) -
how can i fix django form validation error?
I created a login view and i have this user in database(email:john@gmail.com,password:123) when i filled out my form i got message error means this user wasn't exist, but i have this user in database. what do i do to fix it? my views.py: class User_Login(View): def get(self,request): form = UserLoginForm() return render(request,'login.html',{'form':form}) def post(self,request): form = UserLoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(request,email=cd['email'],password=cd['password']) if user is not None: login(request,user) messages.success(request,'شما با موفقیت وارد شدید','success') return redirect('product:home') else: messages.error(request,'نام کاربری و یا رمز عبور اشتباه است','danger') return redirect('users:login') my forms.py: class UserLoginForm(forms.Form): email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'}), label="ایمیل") password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}),label='رمز عبور') -
Django: How to filter a subset in a querset?
How can I filter the elements in a subset? class Order(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) ... class Bill(models.Model): order = models.ForeignKey(Order, blank=True, null=True, on_delete=models.SET_NULL)) billdate = models.DateTimeField(default=timezone.now) payed = models.BooleanField(default=False) ... order = Orders.objects.all() order[0].bill_set will return all Bills. But I just want to get the latest 3 elements, ordererd by billdate. How can I do this? I want to use the result in Django Rest Framework in my viw: class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = ( 'id' 'bill_set' ) class AffiliateOrderViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): serializer_class = OrderSerializer def get_queryset(self): return Order.objects.filter(bill_set__filter_somehow_only_the_last_3_entries_ordered_by_date) Any idea? -
Automatically populating HTML attributes with Django for-loop
I am making a website using Django and Wagtail CMS, and have a way of filtering posts by a custom attribute called "data-group" in the html template. It works when I hard-code everything, but I would like to use some logic to have that attribute filled dynamically for each post. Basically, I want the post tags to be populated there, but I am having a problem doing this. I will highlight relevant lines of the code with -------------------------- An example of hard-coded filter buttons: <ul class="portfolio-filters"> <li class="active"> <a class="filter btn btn-sm btn-link" data-group="category_all">All</a> </li> <li> <a class="filter btn btn-sm btn-link" data group="category_detailed">Detailed</a> </li> <li> <a class="filter btn btn-sm btn-link" data-group="category_direct-url">Direct URL</a> </li> <li> <a class="filter btn btn-sm btn-link" data-group="category_image">Image</a> </li> <li> <a class="filter btn btn-sm btn-link" data-group="category_soundcloud">SoundCloud</a> </li> <li> <a class="filter btn btn-sm btn-link" data-group="category_video">Video</a> </li> <li> <a class="filter btn btn-sm btn-link" data-group="category_vimeo-video">Vimeo Video</a> </li> <li> <a class="filter btn btn-sm btn-link" data-group="category_youtube-video">YouTube Video</a> </li> </ul> When any of the above buttons are clicked, it filters posts/items with similar values in the data-group attribute. An example of the items it is filtering are below in the figure data-groups list: --------------------------<figure class="item standard" data-groups='["category_all", "category_detailed"]'> -------------------------- <div class="item"> <div class="blog-card"> <div … -
Dockerizing Django & Gunicorn - Docker-compose up error - env vars not set
Launching Django app via docker build + docker run works fine. However, by docker-compose up: I get the error: File "/usr/src/api/api/settings.py", line 39, in <module> api_1 | DEBUG = bool(int(os.environ.get('DJANGO_DEBUG', 0))) api_1 | ValueError: invalid literal for int() with base 10: '' Within my settings.py, I set them as shown below. When hardcoding the vars SECRET KEY & DEBUG in settings.py the docker-compose up works fine. Thus, it seems that the env-vars, as set in manage.py are not comming throug. SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', "testing") DEBUG = bool(int(os.environ.get('DJANGO_DEBUG', 0))) set env vars error descriptiption -
preventDefault() not working after use of ajax in Django 3.1.4
I know javascript a little. But in a tutorial I have to add some jquery and ajax functionality. here is a form: <form class="form-product-ajax" method="POST" action="{% url 'carts:update' %}" class="form"> {% csrf_token %} <input type="hidden" name="product_id" value=" {{p roduct.id}} "/> {% if in_cart %} <button type="submit" class="btn btn-link btn-sm" style="padding:0px;cursor:pointer;" name="button">Remove?</button> {% else %} <span class="submit-span"> {% if product in cart.products.all %} In cart<button type="submit" class="btn btn-danger" name="button">Remove?</button> {% else %} <button type="submit" class="btn btn-success" name="button">Add to cart</button> {% endif %} </span> {% endif %} </form> my jquery and ajax: <script type="text/javascript"> $(document).ready(function(){ var productForm=$(".form-product-ajax") productForm.submit(function(event){ event.preventDefault(); var thisForm=$(this) var actionEndpoint=thisForm.attr("action"); var httpMethod=thisForm.attr("method"); var formData=thisForm.serialize(); $.ajax({ url:actionEndpoint, method:httpMethod, data:formData, type : 'POST', success: function(data){ var submitSpan = thisForm.find(".submit-span") if(data.added){ submitSpan.html("<button type="submit" class="btn btn-danger" name="button">Remove?</button>") }else{ submitSpan.html("<button type="submit" class="btn btn-success" name="button">Add to cart</button>") } }, error: function(errorData){ } }) }) }) </script> Here is my views.py's function: def cart_update(request): #print(request.POST) product_id=request.POST.get('product_id') if product_id is not None: try: product_obj=Product.objects.get(id=product_id) except Product.DoesNotExist: print("Produuct does not exists") return redirect("cart:home") cart_obj,new_obj=Cart.objects.new_or_get(request) if product_obj in cart_obj.products.all(): cart_obj.products.remove(product_obj) added=False else: cart_obj.products.add(product_obj) added=True request.session['cart_items']=cart_obj.products.count() if request.is_ajax(): print("Ajax request") json_data={ "added": added, "removed": not added, } return JsonResponse(json_data) #return redirect(product_obj.get_absolute_url()) return redirect("carts:home") jquery and ajax version: {% load static … -
'AdminSiteTests' object has no attribute 'user' Django unit tests
I can't seem to figure out why my unit test is failing for the following Traceback (most recent call last): File "/app/core/tests/test_admin.py", line 26, in test_users_listed self.assertContains(res, self.user.name) AttributeError: 'AdminSiteTests' object has no attribute 'user' test_admin.py from django.test import TestCase, Client from django.contrib.auth import get_user_model from django.urls import reverse class AdminSiteTests(TestCase): def setup(self): self.client = Client() self.admin_user = get_user_model().objects.create_superuser( email='admin@test.com', password='test123' ) self.client.force_login(self.admin_user) self.user = get_user_model().objects.create_user( email='test@test.com', password='test123', name='test name' ) def test_users_listed(self): """Test that users are listed on user page""" url = reverse('admin:core_user_changelist') res = self.client.get(url) self.assertContains(res, self.user.name) self.assertContains(res, self.user.email) admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from core import models class UserAdmin(BaseUserAdmin): ordering = ['id'] list_display = ['email', 'name'] admin.site.register(models.User, UserAdmin) models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Creates and saves a new user""" if not email: raise ValueError('Users must have a email address') user = self.model(email=self.normalize_email(email), **extra_fields) # Must encrypt password using set_password() that comes with BaseUserManager user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """Creates and saves new superuser""" user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): """Custom user model that supports using … -
How to load new template using ajaxed data in django?
I have posted a list using ajax to a view but i can not load the next template to show the posted list in the template.Any Idea? Here is my code: view.py def meter_view (request): data = [] list = request.POST.getlist('list[]') for each in list: d = Meter.objects.get(id = each) data.append(d) print(data) context = { 'data' : data } return render(request,'selectedMeters.html',context) ajax part and the button: <button type="button" class="btn" id="export"> Export </button> $('#export').on('click', function() { $.ajax({ type: 'POST', url: '{% url 'meters-list' %}', data: {'list[]': list }, });}) I want to load selectedMeters.html template after after posting data to it. How can I do that? Thanks. -
Django Installed apps
Why does Django installed apps end with a comma at the end eg INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'dj ango.contrib.staticfiles', 'rest_framework', ] Is the extra comma necessary? -
Adding an element that is not part of a model to Django admin page
I am trying to add a date that displays at the top of every page in Django admin but I haven't been able to find any documentation that discusses this. It needs to be a date that populates based on a script that says when the data was last pulled. Would anyone have any ideas on how to do this? -
Django can not connect to MySQL container?
I have a docker-compose like a bellow: version: '3' services: mysql: image: mysql ports: - 3306:3306 env_file: ./src/.environment volumes: - mysql_data:/var/lib/mysql web: build: context: ./src dockerfile: Dockerfile command: bash -c "python manage.py collectstatic --no-input && python manage.py makemigrations --no-input && python manage.py migrate --no-input" env_file: ./src/.environment ports: - 8001:8001 depends_on: - mysql volumes: - ./src:/var/www/project/src - staticfiles:/var/www/project/src/statics .environment content as follow: DATABASE_MYSQL_NAME=dataCollection DATABASE_MYSQL_HOST=mysql DATABASE_MYSQL_USER=user1 DATABASE_MYSQL_PASSWORD=user123456 DATABASE_MYSQL_PORT=3306 Then in django setting I have follow database configuration: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.getenv('DATABASE_MYSQL_NAME'), 'HOST': os.getenv('DATABASE_MYSQL_HOST'), 'USER': os.getenv('DATABASE_MYSQL_USER'), 'PASSWORD': os.getenv('DATABASE_MYSQL_PASSWORD'), 'PORT': os.getenv('DATABASE_MYSQL_PORT'), } } But, when I run docker-comose up it throws the following error: MySQLdb._exceptions.OperationalError: (2002, "Can't connect to MySQL server on 'mysql' (115)") I don't know what the problem is? -
ERROR: Could not find a version that satisfies the requirement ipython==7.18.1
Getting this error while pushing to heroku ERROR: Could not find a version that satisfies the requirement ipython==7.18.1 (from -r /tmp/build_bd03014c/requirements.txt (line 36)) (from versions: 0.10, 0.10.1, 0.10.2, 0.11, 0.12, 0.12.1, 0.13, 0.13.1, 0.13.2, 1.0.0, 1.1.0, 1.2.0, 1.2.1, 2.0.0, 2.1.0, 2.2.0, 2.3.0, 2.3.1, 2.4.0, 2.4.1, 3.0.0, 3.1.0, 3.2.0, 3.2.1, 3.2.2, 3.2.3, 4.0.0b1, 4.0.0, 4.0.1, 4.0.2, 4.0.3, 4.1.0rc1, 4.1.0rc2, 4.1.0, 4.1.1, 4.1.2, 4.2.0, 4.2.1, 5.0.0b1, 5.0.0b2, 5.0.0b3, 5.0.0b4, 5.0.0rc1, 5.0.0, 5.1.0, 5.2.0, 5.2.1, 5.2.2, 5.3.0, 5.4.0, 5.4.1, 5.5.0, 5.6.0, 5.7.0, 5.8.0, 5.9.0, 5.10.0, 6.0.0rc1, 6.0.0, 6.1.0, 6.2.0, 6.2.1, 6.3.0, 6.3.1, 6.4.0, 6.5.0, 7.0.0b1, 7.0.0rc1, 7.0.0, 7.0.1, 7.1.0, 7.1.1, 7.2.0, 7.3.0, 7.4.0, 7.5.0, 7.6.0, 7.6.1, 7.7.0, 7.8.0, 7.9.0, 7.10.0, 7.10.1, 7.10.2, 7.11.0, 7.11.1, 7.12.0, 7.13.0, 7.14.0, 7.15.0, 7.16.0, 7.16.1) remote: ERROR: No matching distribution found for ipython==7.18.1 (from -r /tmp/build_bd03014c/requirements.txt (line 36)) remote: ! Push rejected, failed to compile Python app. -
inlineformsetfactory validate_min validate other form than first
I want to write a form that contains a question and at least 2 answer choices. A user should provide at least 2 choices for the question to validate. To do that I am using inlineformsetfactory with the kwargs: { ... 'min_num': 2, 'validate_min': True, 'max_num': 20, 'validate_max': True, 'extra': 2 } The problem I am facing is: Django does not look if 2 answers are given but rather if answer[0] and answer[1] are filled. This is what I see upon submitting my form. Possible duplicate of this post - that unfortunately does not have an answer either. It seems that Djangos method of checking out-of-order forms does not really exist. In case that you are wondering why I don't provide my full inlineformsetfactory - I use a the extra-views package that allows for class based InlineFormSetFactory but works just like the normal django function. -
Why am I obtaining this error message trying to migrate a Django application from SQL Lite DB to Postgres DB?
I am pretty new in Django and Python and I am trying to follow this videotutorial about how to migrate a Django application from SqlLite to Postgres database: https://www.youtube.com/watch?v=lR4N4rhGdjo But I am finding some problem. Following the details on what I have done: I am working on Ubuntu 20.04 and I have a Django application made by someone else that uses SQLLite and that have to be migrated on Postgres. Following the previous tutorial I have done the following steps: First of all I installed Postegres and PgAdmin4 on my Ubuntu system. Then I created a DB named dgsrgdb that have to be my new database for my application: It have defined 2 users: one is the "root" user and the other one an user that can operate only on this specific DB. I installed this package to let Python\Django operate with Postgres: pip3 install psycopg2-binary I performed the backup of my original SqlLite DB by this command: python3 manage.py dumpdata > datadump.json and I obtained the datadumo.json file that should contains the data inside the original DB that have to moved on the new Postgres DB. Into the Django settings.py file I replaced this configuration: DATABASES = { 'default': … -
Local React app pointing to hosted Django server CORS no 'Access-Control-Allow-Origin' header
I am running a local version of my react app on localhost:3000 and am trying to hit endpoints on a Django server hosted on heroku Error encountered on each axios request: Access to XMLHttpRequest has been blocked by CORS policy: no 'Access-Control-Allow-Origin' header is present Current settings.py for Django server: ALLOWED_HOSTS=['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'corsheaders', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'accounts', 'blog', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', # Whitenoise 'whitenoise.middleware.WhiteNoiseMiddleware', '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', # Machina #'machina.apps.forum_permission.middleware.ForumPermissionMiddleware', ] # CORS CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = False Since I am allowing all origins to make requests, it seems like this type of CORS issue should be disabled. I have tried removing all other middleware except CorsMiddleware and it it did not make a difference. A bit stumped at this point because my configuration seems correct as per https://github.com/adamchainz/django-cors-headers Here is an example api call from my react app that is causing the "no 'Access-Control-Allow-Origin' header" function callCSRFApi(){ return axios.request({ method: 'GET', url: 'http://example.com/csrf/', }); } One thing to note is that I am hitting endpoints on the Django server even though it is not configured as a django_rest api. I have also tried setting a custom … -
DRF auth_token "non_field_errors": [ "Unable to log in with provided credentials." ] using custom user model
I'm trying to create a rest api using an existing database. I am also using drf token authentication and have created tokens for all existing users. When I try to enter my username and password to get my token from my ObtainAuthToken View I receive the following error: "non_field_errors": [ "Unable to log in with provided credentials." ] My code is as follows: Views.py from django.shortcuts import render from django.db import connection from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets from rest_framework.authentication import TokenAuthentication from rest_framework import filters from rest_framework import generics from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.settings import api_settings from rest_framework.permissions import IsAuthenticatedOrReadOnly from rest_framework.permissions import IsAuthenticated from rest_framework.renderers import JSONRenderer from api import serializers from api import models from itertools import chain # Create your views here. class UserLoginApiView(ObtainAuthToken): """Handle creating user authentication tokens""" renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES urls.py from django.urls import path, include from rest_framework.routers import DefaultRouter, SimpleRouter from api import views urlpatterns = [ path('login', views.UserLoginApiView.as_view()), ] models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager, UserManager from django.conf import settings from django.dispatch import receiver from django.urls import reverse class UserProfileManager(BaseUserManager): … -
destroyable server for dev integration
A little background: In my company we develop multiple features in parallel and test each feature individually. So typically what happens is: - Multiple backend devs work on a feature by the time frontend devs work on some feature. - Stagings are busy for testing and UAT of previous features. - Its not advisable to use stagings for integration and dev testing. - Backend is micro-service architecture mostly in python (Django) which requires migrations and two features can not be merged every time on stagings. - Frontend devs need to wait for staging to be free for integration and dev testing which delays productivity. - Having more stagings will not fix the issue since there are many developers waiting in the queue. - Dev testing and integration can take more than a day. - Using Ngrok has a issue, backend dev will be blocked and can not change branches for next feature. Any suggestions how we can be more productive and tackle this issue? -
'str' object has no attribute 'is_authenticated'
I am using Django 3.8.5. I am building a chat app. AND i am stuck on an Error. views.py def chat(request): if request.method == 'GET': if request.method.is_authenticated: chat_boxes = ChatBox.objects.filter(Q(user_1=request.user) | Q(user_2=request.user)) groups = ChatGroup.objects.filter(members=request.user) else: chat_boxes = [] groups = [] return render(request, 'chathome.html', {'chat_boxes':chat_boxes,'groups':groups}) else: form = ChatGroupForm(data=request.POST,files=request.FILES) group = form.save(commit=False) group.author = request.user group.save() group.members.add(request.user) group.group_admins.add(request.user) return redirect('profile',pk=group.id) The Problem When i open browser it is showing 'str' object has no attribute 'is_authenticated' Any Help would be appreciated. Thank You In Advance -
django-seed generates more data than I request
I'm trying yo generate fake data for my app but I need to generate specific type of users, I check docs for django-seed and I get this code from his page django-seed from django_seed import Seed seeder = Seed.seeder() from myapp.models import Game, Player seeder.add_entity(Game, 5) seeder.add_entity(Player, 10) inserted_pks = seeder.execute() and I tried to generate data of this way seeder = Seed.seeder() seeder.add_entity(User, 1, { 'first_name': lambda x: seeder.faker.name(), 'last_name': lambda x: seeder.faker.name(), 'email': lambda x: seeder.faker.email(), 'country': lambda x: self.get_random_country(language=1), 'is_admin': lambda x: False, }) seeder.add_entity(User, 10, { 'first_name': lambda x: seeder.faker.name(), 'last_name': lambda x: seeder.faker.name(), 'email': lambda x: seeder.faker.email(), 'country': lambda x: self.get_random_country(language=1), 'is_admin': lambda x: True, }) seeder.execute() So, I need to generate 10 admins and 1 no admin, but I get only 20 admin, then try creating 2 instances of the seeder. seeder = Seed.seeder() seeder.add_entity(User, 1, { 'first_name': lambda x: seeder.faker.name(), 'last_name': lambda x: seeder.faker.name(), 'email': lambda x: seeder.faker.email(), 'country': lambda x: self.get_random_country(language=1), 'is_admin': lambda x: False, }) seeder.execute() admin_seeder = Seed.seeder() admin_seeder.add_entity(User, 10, { 'first_name': lambda x: admin_seeder.faker.name(), 'last_name': lambda x: admin_seeder.faker.name(), 'email': lambda x: seeder.faker.email(), 'country': lambda x: self.get_random_country(language=1), 'is_admin': lambda x: True, }) admin_seeder.execute() this time I get 20 admins and … -
How to select an object automatically FK item (django)
I have a question and answer quiz and when I put it in HTML I have such a result image To save a question, I must first manually select the question. So I want this to happen automatically. Each question will appear automatically. But I could not understand the view I have to change if html and what I have to change this is my code --> models.py from django.db import models # Create your models here. class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE) answer=models.CharField(max_length=100,blank=True) def __str__(self): return str(self.questin) forms.py from django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Question,Answer class QuestionForm(forms.ModelForm): class Meta: model=Question fields="__all__" class AnswerForm(forms.ModelForm): class Meta: model=Answer fields="__all__" views.py from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from .forms import QuestionForm,AnswerForm from .models import Question def home(request): form=QuestionForm if request.method=='POST': form=QuestionForm(request.POST) if form.is_valid(): form.save() return render(request, "question/base.html", {"form":form}) def ans(request): form=AnswerForm e=Question.objects.all() if request.method=="POST": form=AnswerForm(request.POST) if form.is_valid(): form.save() return render(request, "question/ans.html", {"form":form, "e":e}) base.html <!DOCTYPE html> <html> <head> <title>question</title> </head> <body> {% for i in e %} <form method="POST" novalidate> {% … -
How can I filter already generated django products?
I am using Product class in my models, and in the html I am going through for loop of products. So my question is can you recomand any tutorial or course for that. Filter by category, type, min and max price. Plz dont ban this question. Its very importnant for me ) -
DJANGO: is there any kind of limit with the post requests?
I'm developing an app which you upload an excel file with a lot of rows(could be 10.000 or more rows) and it has to process all those rows. That means that I have to ask through ajax for some data per row. The thing is that when I try this with a big file (arround 5000 rows) it just stops after a lot of requests and doesnt give me any clue, no errors, no warning, nothing. This is the log i receive -----a lot of these more...------ [13/Jan/2021 16:54:46] "POST /consumos/obtener_datos_cliente HTTP/1.1" 200 168 [13/Jan/2021 16:54:46] "POST /consumos/obtener_datos_curso HTTP/1.1" 200 196 [13/Jan/2021 16:54:47] "POST /consumos/obtener_datos_cliente HTTP/1.1" 200 168 [13/Jan/2021 16:54:47] "POST /consumos/obtener_datos_curso HTTP/1.1" 200 196 [13/Jan/2021 16:54:47] "POST /consumos/obtener_datos_cliente HTTP/1.1" 200 168 [13/Jan/2021 16:54:48] "POST /consumos/obtener_datos_curso HTTP/1.1" 200 196 [13/Jan/2021 16:54:48] "POST /consumos/obtener_datos_cliente HTTP/1.1" 200 168 [13/Jan/2021 16:54:48] "POST /consumos/obtener_datos_curso HTTP/1.1" 200 196 [13/Jan/2021 16:54:49] "POST /consumos/obtener_datos_cliente HTTP/1.1" 200 168 [13/Jan/2021 16:54:49] "POST /consumos/obtener_datos_curso HTTP/1.1" 200 196 [13/Jan/2021 16:54:50] "POST /consumos/obtener_datos_cliente HTTP/1.1" 200 168 [13/Jan/2021 16:54:50] "POST /consumos/obtener_datos_curso HTTP/1.1" 200 196 [13/Jan/2021 16:54:50] "POST /consumos/obtener_datos_cliente HTTP/1.1" 200 168 [13/Jan/2021 16:54:51] "POST /consumos/obtener_datos_curso HTTP/1.1" 200 196 --- Here it just reload the page --- [13/Jan/2021 16:55:10] "GET /consumos/importar_consumos HTTP/1.1" 200 67866 … -
can't access data from front-end "MultiValueDictKeyError"
Here is My Views from django.contrib import messages from django.contrib.auth import authenticate from django.contrib.auth.models import * from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import * from .models import * def login(request): if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('username') password = request.POST.get('password') User._meta.get_field('email')._unique = True # username verification if User.objects.filter(username=username).exists(): user = auth.authenticate(username=username, password=password) # Email Verification elif User.objects.filter(email=email).exists(): username = User.objects.get(email=email.lower()).username user = authenticate(username=username, password=password) # Forign key data collect from Phone model to User model else: messages.info(request, 'Enter valid username/email/Phone') return render(request, 'login.html') # authenticate if user is not None: auth.login(request, user) return redirect('user_search') else: messages.info(request, 'incorrect password.') return render(request, 'login.html') else: return render(request, 'login.html') def logout(request): auth.logout(request) return redirect('login') @login_required def register(request): if request.method == 'POST': username = request.POST['username'] email = request.POST['email'] phone = request.POST['phone'] if Customer.objects.filter(c_phone=phone).exists(): messages.info(request, 'Phone number already registered') return render(request, 'register.html') else: user = Customer.objects.create(c_name=username, c_email=email, c_phone=phone) user.save() return redirect('product_list', id=user.pk) else: return render(request, 'register.html') @login_required def product_list(request, id): product = Products.objects.all() customer = Customer.objects.get(pk=id) form = CustomForm() return render(request, 'product_list.html', {'product': product, 'customer': customer}) @login_required def user_search(request): if request.method == 'POST': phone = request.POST['phone'] if Customer.objects.filter(c_phone=phone).exists(): user = Customer.objects.get(c_phone=phone) print(user.pk) return redirect('product_list', id=user.pk) else: return redirect('register') … -
django_filters: How to make DateTimeFromToRangeFilter inline fields?
I have two questions: I am using django_filters and the field DateTimeFromToRangeFilter. This field appears like two fields aligned vertically (see picture). How can i make this fields display inline? I also would like to add a text before of every field. Is there a way to do this in django? Thank you.