Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple small API call vs single API call in Django Rest Framework
I have an application with user data associated with multiple models. All associated models need to be populated with certain data when a user is created. Should I create multiple APIs called at the same time from frontend or should I create a single API that does it all -
Handling notification Redirects to mobile apps and the frontend with Django Rest Framework
My project is in Django rest framework. It have web with react as well as android and ios. I am using Firebase push notification for notification purpose. Since I have to show my notification in app also, I have stored the notification in database and the notification database is as below: class Notification(models.Model): """ model to manage all notification """ receiver = models.UUIDField(max_length=255) title = models.CharField(max_length=255) body = models.TextField(blank=True, null=True) type = models.CharField(max_length=255) # order_type, registration_type is_read = models.BooleanField(default=False) redirect_url = models.CharField(max_length=255) Now the main problem I am facing is setting a redirect url for every notification. I want to redirect to specific page for different type of notification. For example for order_type notification i want to redirect user to order page, for comment_type notification I want to redirect user to comment page. How can I do that since i cannot just simply redirect to html url since there is react app, ios app as well as android app. I did not find much resource regarding this. Any help will be very much appreciated. Thanks. -
Does Django Headless CMS provide fronted Interface Templates?
I am new in Python/Django Framework and i want use CMS for my website so i can use fronted and admin ready-made templates. please suggest. -
Only Owner of the Profile able to Update the data
Using class Based (APIView) in Django rest framework for Getting and Patch (Updating) UserInfo data. views.py class getUserInfo(APIView): permission_classes = [permissions.IsAuthenticated] def get(self, request, format=None): user = request.user userinfos = user.userinfo_set.all() serializer = UserInfoSerializers(userinfos, many=True) return Response(serializer.data) def patch(self, request, pk, format=None): user = UserInfo.objects.get(id=pk) serializer = UserInfoSerializers(instance=user, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py from django.contrib.auth.models import User from .models import UserInfo class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'first_name', 'username') class UserInfoSerializers(serializers.ModelSerializer): user = UserSerializer(many=False, required=True) class Meta: model = UserInfo fields = ('id', 'picture', 'profession', 'user') Everything is working so far so good. Able to GET and PATCH (Update) logged-in user data. While Testing the API in Postman, I found out that if User1 is logged in he can change the data of User2 by only using the pk of User2. urls.py urlpatterns = [ path('userinfo/', views.getUserInfo.as_view(), name="UserInfo"), path('userinfo/<str:pk>/', views.getUserInfo.as_view()), path('api/token/', views.MyTokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('register/', views.RegisterView.as_view(), name='auth_register'), ] Using rest_framework_simplejwt for Auth models.py from django.contrib.auth.models import User class UserInfo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) picture = models.ImageField(upload_to="profile_pics", null=True) profession = models.CharField(max_length=200, null=True) def __str__(self): return "%s's Profile Picture" % self.user Any help would be appreciated -
How to compare two serializer field and show whichever is higher in django rest
I have product serializer which return category_offer_price & product_offer_price, before getting this response I want to compare both price and only return whichever is highest price. #Serilaizer.py class ProductSerializer(ModelSerializer): category = CategorySerializer() product_offer_price = SerializerMethodField() category_offer_price = SerializerMethodField() class Meta: model = Products fields = [ "id", "product_name", "slug", "category", "description", "category_offer_price", "product_offer_price", "base_price", "stock", "is_available", "created_date", "images", "images_two", "images_three", ] def get_product_offer_price(self, obj): try: product_offer = ProductOffer.objects.get(product=obj) if product_offer.is_active: offer_price = product_offer.product_offer_price() return offer_price except Exception: pass return None def get_category_offer_price(self, obj): try: category_offer = CategoryOffer.objects.get(category=obj.category) if category_offer.is_active: offer_price = category_offer.category_offer_price(obj) return offer_price except Exception: pass return None #Models.py class Products(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) product_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=100, unique=True) description = models.TextField(max_length=500) base_price = models.IntegerField() images = models.ImageField(upload_to="photos/products") images_two = models.ImageField(upload_to="photos/products") images_three = models.ImageField(upload_to="photos/products") stock = models.IntegerField() is_available = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Products" def __str__(self): return self.product_name I'd like to know is it possible to compare serializer fields in a serializer class? -
dfr TypeError: unsupported operand type(s) for +: 'Office' and 'str'
I'm trying to concatenate some fields ex. When I do this in postman { "sem": "2", "sy": "2021-2022", "remarks": "test", "resolution": "test", "studid": "2012-5037" } this is the customuser I made The cl_itemid shoud be OSA-2021-2022-2 class ClearanceItemSerialize(serializers.ModelSerializer): class Meta: model = ClearanceItem fields = '__all__' def create(self, validated_data): validated_data["office"] = self.context["request"].user.officeid validated_data["recorded_by"] = self.context["request"].user.userid validated_data["cl_itemid"] = self.context["request"].user.officeid + '-' + validated_data.get('sy') + '-' + validated_data.get('sem') return super().create(validated_data) above is the code but it's throwing me an error TypeError: unsupported operand type(s) for +: 'Office' and 'str' if I use userid instead validated_data["cl_itemid"] = self.context["request"].user.userid + '-' + validated_data.get('sy') + '-' + validated_data.get('sem') it's working 321-05 2021-2022-2 What's happening here can somebody explain? Edit: I added the models incase that's the problem class ClearanceItem(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=20, default=get_default_id) studid = models.CharField(max_length=9, blank=True, null=True) office = models.ForeignKey('Office', models.DO_NOTHING, blank=True, null=True) sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) remarks = models.TextField(blank=True, null=True) -
django postgres different values
Hi Django + Postgresql While studying aware datetime, I had a question and asked a question. Postgresql document For timestamp with time zone, the internally stored value is always in UTC (Universal Coordinated Time, traditionally known as Greenwich Mean Time, GMT). An input value that has an explicit time zone specified is converted to UTC using the appropriate offset for that time zone. If no time zone is stated in the input string, then it is assumed to be in the time zone indicated by the system's TimeZone parameter, and is converted to UTC using the offset for the timezone zone. Are you changing only the output differently according to the timezone setting value? (internally stored value is UTC ?) SET TIME ZONE 'KST' (Asia/Seoul +9) Why is the same query but different values? Django Settings TIME_ZONE = "Asia/Bangkok" # ( +7 ) USE_TZ = False Postgres Settings SET TIME ZONE 'KST' (Asia/Seoul +9) Django Server TimeZone UTC Django ORM Create Query INSERT INTO "timezone_timezone" ("datetime") VALUES ('2022-11-22T01:58:14.373201'::timestamp) RETURNING "timezone_timezone"."id"; args=(datetime.datetime(2022, 11, 22, 1, 58, 14, 373201),) psql select query psql insert Django ORM Query INSERT INTO "timezone_timezone" ("datetime") VALUES ('2022-11-22T01:58:14.373201'::timestamp) RETURNING "timezone_timezone"."id"; psql select query -
Django - Get ID before ensuring form is valid
I am facing an issue where I have multiple forms on one page. What I am trying to do is update an item using an update form. When I request the pk, it comes from a different model that is not related to this one. I need to get the ID before ensuring that the form is valid so I can filter and get the correct item based on the ID in order to display the data that I need. models.py class DevIssues(models.Model): ISSUE_CODE = [ ('BUG', 'Bug'), ('BACKLOG', 'Backlog'), ('REQUEST', 'Request'), ('TODO', 'To-Do'), ] ISSUE_STATUS = [ ('NEW', 'New'), ('WIP', 'In Progress'), ('Complete', 'Complete'), ] project = models.ForeignKey(DevProjects, on_delete=models.CASCADE, related_name='issue') issue = models.CharField(max_length=100) issue_desc = models.CharField(max_length=500) issue_code = models.CharField(max_length=9, choices=ISSUE_CODE, null=True, blank=True) issue_status = models.CharField(max_length=15, choices=ISSUE_STATUS, default='New') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateField(auto_now=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) forms.py class AddProjectIssues(forms.ModelForm): class Meta: model = DevIssues fields= ["issue", "issue_desc", "issue_code"] labels = { 'issue': 'Issue', 'issue_desc': 'Issue Description', 'issue_code': 'Issue Code', } class UpdateProjectIssues(forms.ModelForm): class Meta: model = DevIssues fields= ["issue_status"] views.py issue_project = get_object_or_404(DevProjects, pk=pk) issues = DevIssues.objects.filter(project=issue_project).order_by('-created_at') if request.method == 'POST' and 'addissue' in request.POST: issue_form = AddProjectIssues(request.POST or None) if issue_form.is_valid(): content = request.POST.get('issue') content2 = request.POST.get('issue_desc') … -
how to solve ValueError at /register in django
I am trying to create a sign up with Django but after filling the form, I keep getting this ValueError at /register as an error requesting that the username be set. I am new to Django and I don't seem to understand what is expected Below are my codes for signup form, the views.py and the resulting error respectively Signup form: {% for message in messages %} <h5>{{message}}</h5> {% endfor %} <form method="POST" action="register" name="registerForm"> {% csrf_token %} <p>Username:</p> <input type="text" name="username "/> <p>Email:</p> <input type="email" name="email "/> <p>Password:</p> <input type="password" name="password"/> <p>Repeat Password:</p> <input type="password" name="confirm_password"/><br> <input type="submit"/> </form> views.py def register(request): if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') confirm_password = request.POST.get('confirm_password') if password==confirm_password: if User.objects.filter(username=username).exists(): messages.info(request, 'Username Taken') return redirect('register') elif User.objects.filter(email=email).exists(): messages.info(request, 'Email Taken') return redirect('register') else: user = User.objects.create_user(username=username, email=email, password=password) user.save() return redirect('/') else: messages.info(request, 'Password does not match') return redirect('register') else: return render(request, 'register.html') Error: ValueError at /register The given username must be set Request Method: POST Request URL: http://127.0.0.1:8000/register Django Version: 4.1.3 Exception Type: ValueError Exception Value: The given username must be set Exception Location: C:\Users\User\Envs\myapp\lib\site-packages\django\contrib\auth\models.py, line 144, in _create_user Raised during: myapp.views.register Python Executable: C:\Users\User\Envs\myapp\Scripts\python.exe Python … -
Django logging missing while testing through the interactive shell
We added the below to show the SQL queries on the console. And, as a proof of concept, we are following the online tutorial to build a testing project. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django.db.backends': { 'level': 'DEBUG', 'handlers': ['console'], } }, } At the step of "Explore the free admin functionality", for example, the console SQL logging works as exacted. So, when clicking on the button, we see sample SQL logs like attached below. However, when using the interactive shell through the command python manage.py shell, and calling python commands like Choice.objects.filter(question__pub_date__year=current_year), we did not see any SQL log. We wonder if we missed anything for the backend logging on the interactive shell. We are testing with Django v3.1.4 and Python v3.7.6. Just let us know if you need more details. Sample Django backend logging records: ... (0.000) SELECT "django_session"."session_key", "django_session"."session_data", "django_session"."expire_date" FROM "django_session" WHERE ("django_session"."expire_date" > '2022-11-21 23:03:45.762894' AND "django_session"."session_key" = 'dd9uy7q873cijz0603l5uu9zl3wujr2f') LIMIT 21; args=('2022-11-21 23:03:45.762894', 'dd9uy7q873cijz0603l5uu9zl3wujr2f') (0.000) SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = 1 LIMIT 21; args=(1,) (0.000) BEGIN; args=None (0.000) SELECT … -
UnboundLocalError - local variable 'emprendedores' referenced before assignment
I can't figure out why am I getting this error message: "UnboundLocalError - local variable 'emprendedores' referenced before assignment" enter image description here Hey fellows, i'm building an app in Django and almost is pretty well. However, I cannot find solution to a problem in my search view. The main idea is allowing the user to indicate the word and to select the desired fields to search into from an form, and returning the registered users that satisfy the criteria. The html file looks like this: enter image description here This is the model: enter image description here and this is the view I'm working on: enter image description here But I can't figure out why am I getting this error message: "UnboundLocalError - local variable 'emprendedores' referenced before assignment" enter image description here I'll be glad if someone can help my out. -
Django login fails because of too many redirect
I have a pretty basic instance of a Django app serving an hybrid React app. I wanted to protected this app behind a login using the default authentification module of Django but when I try to access the app on http://127.0.0.1:8000/ I get redirected to: http://127.0.0.1:8000/accounts/login/?next=/accounts/login/%3Fnext%3D/accounts/login/%253Fnext%253D/accounts/login/%25253Fnext%25253D/accounts/login/[...] And the browser display ERR_TOO_MANY_REDIRECTS. Python 3.11.0 Django 4.1.3 config/urls.py from django.contrib import admin from django.urls import include, path from rest_framework import routers from maapi import views router = routers.DefaultRouter() router.register(r'users', views.UserViewSet) router.register(r'groups', views.GroupViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('routers/', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('api/', include('maapi.urls')), path('', include('frontend.urls')), ] frontend/urls.py from django.urls import path from . import views urlpatterns = [ path(r'', views.ReactAppView.as_view(), name='react_app'), path(r'<path:path>', views.ReactAppView.as_view(), name='react_app_with_path'), ] frontend/views.py from django.views.generic import TemplateView from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required # Create your views here. @method_decorator(login_required, name='dispatch') class ReactAppView(TemplateView): template_name = 'app.html' # Get url parameter (Note that removing this doesn't solve the issue) def get_context_data(self, **kwargs): return {'context_variable': 'value'} Can you identify what is wrong or point me to what to test? Thank you. -
Python calling a property from inside a class
I'm trying to call the property protocolo on a new imagefield's upload_to argument What I'm trying to accomplish is to have the saved images use a custom filename. class biopsia(models.Model): paciente = models.CharField(max_length=50) creado = models.DateTimeField(auto_now_add=True) foto = models.ImageField(upload_to=f'fotos_biopsias/%Y/{*protocolo*}', blank=True) def __str__(self): return str(self.protocolo) @property def protocolo(self): return 'BIO' + str(self.creado.year) + '-' + str(biopsia._base_manager.filter( creado__year=self.creado.year, creado__lt=self.creado ).count() + 1) File "C:\Users\LBM\Documents\virtualenviorements\clinico\biopsia\models.py", line 30, in biopsia foto = models.ImageField(upload_to=f'fotos_biopsias/%Y/{protocolo}', blank=True) NameError: name 'protocolo' is not defined* I've tried defining an outside method for upload_to but still I cannot use it inside my class -
How to skip if empty item in column in Django DB
I;m new to learning Django and ran into a small issue: I'm working on a product display page where some products are in a subcategory. I want to be able to display this subcategory when needed but I do not want it to show up when unused. Right now it will show up on my page as 'NONE' which I do not want. How do I fix this? My model looks like this: class Category(models.Model): category_name = models.CharField(max_length=200) sub_category = models.CharField(max_length=200,blank=True,null=True) On my webpage I use the {{category}} in a for loop to display the different categories. Unfortunately is shows 'NONE' when there is no subcategory. -
Form Submitting with Jquery in Django
I wanna submitting form with jquery append. But it doesn't work. I am adding fields but when i click the submit, only original fields sent. Duplicate fields not sending. How can i fix this. And also when i delete the fields, it only delete one field instead of three fields. first image is original fields. Seconda image is clone the fields with jquery Third is datas which are sent with form Here is my codes... models.py from django.db import models # Create your models here. class Contact(models.Model): full_name=models.CharField(max_length=100) email=models.CharField(max_length=200) mesaj=models.CharField(max_length=200) def __str__(self): return self.full_name views.py from django.shortcuts import render from .models import Contact #from django.contrib import messages # Create your views here. def contact(request): if request.method=='POST': full_name=request.POST['full_name'] email=request.POST['email'] mesaj=request.POST['mesaj'] contact=Contact.objects.create(full_name=full_name,email=email,mesaj=mesaj) # messages.success(request,'Data has been submitted') return render(request,'contact.html') contact.html <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> </head> <body> <div class="input_fields_wrap"> <form method="post" action=""> {% csrf_token %} <input type="text" name="full_name" class="field-long" /> <input type="text" name="email" class="field-long" /> <input type="text" name="mesaj" class="field-long" /> <button type="button" class="add_field_button">Add Field</button> <button type="button" class="remove_field_button">Remove Field</button> </div><input type="submit" value="Submit" /></form> </body> <script> var max_fields = 10; var wrapper = $(".input_fields_wrap"); var add_button = $(".add_field_button"); var remove_button = $(".remove_field_button"); $(add_button).click(function(e){ e.preventDefault(); var total_fields = wrapper[0].childNodes.length; if(total_fields < max_fields){ $(wrapper).append('<input type="text" name="full_name" class="field-long" … -
Hi! I need help. I'm trying to figure it out how I can do this and I'm getting frustrated because I know that it will be solve with just little thing
I explain: I have two models called Diagram and Parts respectability. manage.py This is my Diagram Model: from django.db import models import random, string def id_generator(size=10, chars=string.digits): return ''.join(random.choice(chars) for _ in range(size)) class Diagram(models.Model): fuel_type_choices = [('liquid_propane', 'L.P.'), ('natural_gas','N.G.'),] item_type_choices = [ ('conversion_kits','CONVERSION KITS'), ('griddle_parts','GRIDDLE PARTS'), ('grill_parts','GRILL PARTS'), ('kegorator_parts','KEGORATOR PARTS'), ('outdoor_kitchen_parts','OUTDOOR KITCHEN PARTS'), ('pizza_oven_parts','PIZZA OVEN PARTS'), ('power_burner_parts','POWER BURNER PARTS'), ('refrigerator_parts','REFRIGERATOR PARTS'), ('rotisserie_parts','ROTISSERIE PARTS'), ('searing_station_parts','SEARING STATION PARTS'), ] diagram_id = models.CharField(primary_key=True, max_length = 10, blank = True, unique = True) mpn = models.CharField(max_length = 50, blank = False, unique=True) model = models.CharField(max_length = 50, blank = False) name = models.CharField(max_length = 500, blank = False) image = models.ImageField(upload_to = 'img/diagrams/') number_of_references = models.IntegerField(null=True, blank=False) fuel_type = models.CharField(max_length = 15, choices = fuel_type_choices, default = False) item_type = models.CharField(max_length = 25, choices = item_type_choices, default = False) map_area = models.TextField(null=True) def save(self): if not self.diagram_id: # Generate ID once, then check the db. If exists, keep trying. self.diagram_id = id_generator() while Diagram.objects.filter(diagram_id=self.diagram_id).exists(): self.diagram_id = id_generator() super(Diagram, self).save() def __str__(self): return self.name And this is my Part Model: from django.db import models import random, string def id_generator(size=10, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for _ in range(size)) class Part(models.Model): warranty_choices = ( ('0','0'), … -
How to implement a user customizable and personalized dashboard with django
I've created a django website with user accounts and a database containing data and I would like each user to be able to create their own personalized dashboard to view only the data that they care about. How can this be implemented where each dashboard is connected to the specific user that created it? My question is a little vague because I don't know how to implement a feature that is created by a user, is viewable only by that user, and is persistent. Any help or guidance would be much appreciated! I haven't tried anything yet because I don't know how to get started. Online search results are things like creating a custom admin dashboard or a dashboard that is shared across all users, which is not what I'm looking for. -
Problem with redirecting to login page after successful authorization in django-microsoft-auth
I am using django-microsoft-auth to log in with Microsoft account. The problem I am facing is that I want to use it in my login.html and I've managed to add this button to my html, however it redirects me to admin page. My URL that I added in Azure is default one: https://<mydomain_name>.com/microsoft/auth-callback/ I found this solution on Stackoverflow but it requires changing URL on Azure AD. Is there any other way to change reditect from /admin to /home other than changing URL in Azure AD? I was thinking if I could change it somehow directly in library. -
django does not load CSS file in HTML-file which extends from "base.html"
I have a base.html which my options.html extends from like this //options.html {% extends "webpage/base.html" %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'webpage/options.css' %}"> {% block content %} <div class="test"> foo </div> {% endblock content %} //base.html {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'webpage/base.css' %}"> <!-- jQuery--> <script src="https://code.jquery.com/jquery-3.6.1.slim.js" integrity="sha256-tXm+sa1uzsbFnbXt8GJqsgi2Tw+m4BLGDof6eUPjbtk=" crossorigin="anonymous"></script> <title>:)</title> </head> <body> hello world {% block content %} {% endblock content %} <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> </body> </html> the issue is that the CSS is not loaded/applied. In the web-console (when I run python manage.py runserver) and go to the "options" page, then I can see that the webpage/base.css is loaded (i.e GET /static/webpage/base.css is printed), but the webpage/options.css is not. I thought I had something wrong in the static- path, but if I move the <link rel="stylesheet" type="text/css" href="{% static 'webpage/options.css' %}"> into my base.html(and go to my home page) then I see that GET … -
Django - ModelForm(request.POST) is not valid (field with default value is required)
Trying to test ModelForm by passing request.POST in it. The Model has created field with default value defined: created = DateTimeField(default=timezone.now) which works correctly when submitting the form manually in the admin interface. In unit tests, when I test it, it says that created is required: request = HttpRequest() request.POST = { "somefield": "value", } form = ModelForm(request.POST) self.assertTrue(form.is_valid()) Apparently, form.errors contains created: <ul class="errorlist"><li>This field is required.</li></ul> Why and how to fix it? -
How to run external python file in html
I want to use my html file to take user input and then I want to use my python program to process my input and then I want my html shows the answer HTML Part ` {% extends 'base.html' %} {% block title %}Home{% endblock title %}Home {% block body %} <style> #body { padding-left:100px; padding-top:10px; } </style> <div id="body"> <br> <marquee width="750px"> <h4>My name is ChatXBot. I'm your Childs Friend. Talk to me. If you want to exit, type Bye!</h4> </marquee> <br> <form action="/external" method="post"> {% csrf_token %} <textarea id="askchat" name="askchat" rows="10" cols="100" placeholder="Start Typing Here" required></textarea> {{data_external}}<br><br> {{data1}} <br> <input class="btn btn-secondary btn-lg" type="submit" value="Ask"> </form> </div> {% endblock body %} ` Python part ` #importing the neccesary libraries import nltk import numpy as np import random import string # to process standard python strings nltk.download('omw-1.4') #wow.txt is text collected from https://en.wikipedia.org/wiki/Pediatricsn f=open('F:\Ayan\WORK STATION (III)\Python\Python Project\chatbot.txt','r',errors = 'ignore') raw = f.read() raw=raw.lower()# converts to lowercase nltk.download('punkt') # first-time use only nltk.download('wordnet') # first-time use only sent_tokens = nltk.sent_tokenize(raw)# converts to list of sentences word_tokens = nltk.word_tokenize(raw)# converts to list of word sent_tokens[:2] word_tokens[:2] lemmer = nltk.stem.WordNetLemmatizer() #WordNet is a semantically-oriented dictionary of English included in NLTK. def LemTokens(tokens): … -
How to Test ValidationError in a function using assertRaises()
I found this assertRaises() for testing validators in pytest but I am not able to use it in my test function because all examples use classes. Every example I found use self.assertRaises() but I cannot use self. Examples I've tried to understand: Testing for a ValidationError in Django How to correctly use assertRaises in Django model.py - model I am testing for validators ` class AdTextTemplate(models.Model): adtext_template_headline_1 = models.CharField(max_length=270, validators=[headline_with_keyword_validation]) adtext_template_headline_2 = models.CharField(max_length=270, validators=[headline_with_keyword_validation]) adtext_template_description_1 = models.CharField(max_length=810, validators=[description_with_keyword_validation]) adtext_template_description_2 = models.CharField(max_length=810, validators=[description_with_keyword_validation]) campaign = models.ManyToManyField(Campaign, blank=True) conftest.py @pytest.fixture def campaigns(users): lst = [] for user in users: lst.append(Campaign.objects.create(campaign_name='test_campaign', user=user)) return lst @pytest.fixture def adtext_templates_headline_exceed_char_limit(campaigns): lst = [] for campaign in campaigns: x = AdTextTemplate.objects.create( adtext_template_headline_1='test template headline1 that have 41char', adtext_template_headline_2='test template headline2 that have 41char', adtext_template_description_1='test template description 1', adtext_template_description_2='test template description 2', ) x.campaign.add(campaign) lst.append(x) return lst tests.py @pytest.mark.django_db def test_validation_error(adtext_templates_headline_exceed_char_limit): adtext_template = adtext_templates_headline_exceed_char_limit[0] with adtext_template.assertRaises(ValidationError): assert adtext_template.full_clean() I know that the part adtext_template.assertRaises() is not good because there suppose to be self.assertRaises(ValidationError) but my test is not a class. I would like it to stay that way because my mentor said that data for testing should be in fixtures in conftest.py and tests should be in test … -
django.urls.exceptions.NoReverseMatch URLS path seem to be correct
Normally this would be a simple problem to solve and perhaps I'm missing something very basic. But I have been pounding my head against this problem all morning. I receive the error message: django.urls.exceptions.NoReverseMatch: Reverse for 'journalrep' with arguments '('',)' not found. 2 pattern(s) tried: ['reports/journalrep/(?P<column>[^/]+)/(?P<direction>[^/]+)\\Z', 'reports/journalrep/\\Z'] I the debug log of my application. My urls.py contains: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='reports'), path('sumlist/', views.summary_list,name='sumlist'), path('overallsummary',views.overallsummary,name='overallsummary'), path('checkreg', views.checkreg, name='checkreg'), path('checkdet/<chkno>/', views.checkdet, name='checkdet'), path('journalrep/', views.journalrep, name='journalrep'), path('journalrep/<column>/<direction>', views.journalrep, name='journalrep'), path('journaldet/<tranid>', views.journaldet, name='journaldet'), path('accountrep', views.accountrep, name='accountrep') ] The view that renders the template is a function view: @login_required def journalrep(request,column = 'date', direction = 'D'): ''' Produce journal register Will display information for a chart of accounts account if provided. If the value is 0 all journal entries will be shown ''' # # Get list of accounts (Chart of acconts) to be used for account selection box coa = ChartOfAccounts.objects.all().filter(COA_account__gt=0) coa_account = request.session.get('coa_account', None) if len(request.GET) != 0: coa_account = request.GET.get('coa_account') else: if coa_account == None: coa_account = '0' if direction == 'D': direction = '-' else: direction = "" if coa_account == '0': journal = Journal.objects.all().order_by(direction + column) else: journal = Journal.objects.filter(account__COA_account … -
django python ajax java script html
Hello every one , my problem is in django and ajax i want to use two block one for django and the other for ajax but the ajax code is not reading , why ? {% extends 'store/main.html' %} {% load static %} {% block content %} // code html {% endblock content_ajax %}` block content_ajax your text%} //code ajax {% endblock content_ajax %}` # -
How to do a costum SQL Query in Django
I have an external database wich is registered in the settings.py. No I want query some information. But it doesn't work. In the Terminal I can see that the query doesn`t start. I hope you can help me. view.py from django.db import connections def userquery(request): currentuser = request.user userinfoquery = "SELECT * FROM 'userinformation' WHERE 'username' = %s", [currentuser] with connections['mysql-server'].cursor() as cursor: cursor.execute(userinfoquery) userdata = cursor.fetchall() return render(request,'account_settings.html', {'userdata' : userdata}) call in html-file <label>{{userdata.name}}</label>