Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Beginner Django: How to order a queryset by a property
I have a model: class Project(models.Model): title = models.CharField("Project title", max_length=128) start_date = models.DateField("Project start date", blank=True, null=True) end_date = models.DateField("Project end date", blank=True, null=True) @property def has_ended(self): return self.end_date is not None and self.end_date < timezone.now().date() And I want to order projects by two fields: start_date (desc) and also show projects that have not ended first. I know I can't ordery by a property, so I tried the following solution: class ProjectViewSet(viewsets.ModelViewSet): queryset = Project.objects.all().order_by("-start_date") queryset = sorted(queryset, key=lambda a: a.has_ended) serializer_class = ProjectSerializer permission_classes = [permissions.IsAuthenticated] which is the one that has already been answered on other posts with this question. However, I still get the following error: AttributeError: 'list' object has no attribute 'model' I also tried using Django annotations like this: queryset = Project.objects.annotate(has_ended=F('start_date')-F('end_date')).order_by('has_ended', '-start_date') But server returns this error: File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 78, in __iter__ django_1 | setattr(obj, attr_name, row[col_pos]) django_1 | AttributeError: can't set attribute I ran out of ideas on how to achieve the behavior I want. Can someone please give me a hand on that? -
Can't delete django-vote
I am working on a small university project. And I want to add voting to my app. I've decided to use django-vote for it. Here is the documentation: https://pypi.org/project/django-vote/ Upvoting works fine. The problem is whenever I want to delete existing vote it doesn't work. I saw this thread Django model: delete() not triggered but I didn't understand it. from vote.models import UP, DOWN ... book = get_object_or_404(Book, id=pk) ... if 'upvote' in request.POST: print("I clicked upvote") if book.votes.exists(request.user.id): print("upvote exists") book.votes.delete(request.user.id) else: book.votes.up(request.user.id) if 'downvote' in request.POST: print("I clicked downvote") if book.votes.exists(request.user.id, action=DOWN): print("downvote exists") book.votes.delete(request.user.id) else: book.votes.down(request.user.id) My model: class Book(VoteModel, models.Model): .... -
Pip Version Upgrade
pip install --upgrade pip I want to update with the command, but I am getting an error, the error is below. Hello, pip install --upgrade pip I want to update with the command, but I am getting an error, the error is below. https://prnt.sc/X_R-RZHqRnzt -
Django Create Model Instance from an Object
I am working on a Django Daily Saving App where Staff User can create Customer Account, and from the list of the Customer Accounts there is link for Deposit where staff user can add customer deposit. The issue is that after getting the customer id to the customer deposit view, I want to create get the customer details from the ID and create his deposit but anytime I try it I see: Cannot assign "<django.db.models.fields.related_descriptors.ReverseOneToOneDescriptor object at 0x00000129FD8F4910>": "Deposit.customer" must be a "Profile" instance See below my Models: class Profile(models.Model): customer = models.OneToOneField(User, on_delete=models.CASCADE, null = True) surname = models.CharField(max_length=20, null=True) othernames = models.CharField(max_length=40, null=True) gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True) address = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=11, null=True) image = models.ImageField(default='avatar.jpg', blank=False, null=False, upload_to ='profile_images', ) def __str__(self): return f'{self.customer.username}-Profile' class Account(models.Model): customer = models.OneToOneField(User, on_delete=models.CASCADE, null=True) account_number = models.CharField(max_length=10, null=True) date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return f' {self.customer} - Account No: {self.account_number}' class Deposit(models.Model): customer = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) acct = models.CharField(max_length=6, null=True) staff = models.ForeignKey(User, on_delete=models.CASCADE, null=True) deposit_amount = models.PositiveIntegerField(null=True) date = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('create_account', args=[self.id]) def __str__(self): return f'{self.customer} Deposited {self.deposit_amount} by {self.staff.username}' Here are my views: def create_account(request): if searchForm.is_valid(): #Value of … -
how to create Python: Create automated strictly-designed multi-page .pdf report from .html
Can anyone design me Python: Create automated strictly-designed multi-page .pdf report from .html I have foudn this link usfeul but i need someone to do it for me please, here is the link: Python: Create automated strictly-designed multi-page .pdf report from .html not sure where to start? -
How can I detect a file is malicious during upload using VirusTotal API in Django Rest Framework
Working on a Django app. I have files being uploaded by users through the React front-end that end up in the Django/DRF back-end. How can I detect the file is malicious during upload using VirusTotal API in Django Rest Framework. Here are a few sources I am looking at. https://github.com/dbrennand/virustotal-python/blob/master/examples/scan_file.py -
How to get OTP in django admin panel only?
So i am working on REST API and doing KYC verification of aadhar card. This is my code: admin.py def save_model(self, request, obj, form, change): customer_id = obj.customer_id customer_object = Customer.objects.get(id=customer_id) first_name = customer_object.first_name middle_name = customer_object.middle_name last_name = customer_object.last_name customer_name = first_name + " " + last_name date_of_birth = customer_object.date_of_birth aadhar_card = obj.aadhar_card # Send OTP request url = AADHAR_AUTH_URL_OTP_SEND header = { "Content-Type":"application/json", "x-karza-key" : KARZA_TOKEN } payload = { "aadhaarNo": obj.aadhar_card, "consent": "Y" } result = requests.post(url, data=json.dumps(payload), headers=header, verify=False) result_json = result.json() request_id = result_json.get('requestId', '') # Verify OTP request if request_id: otp = input("Enter OTP received on registered mobile number: ") # ask the user to input the OTP url = AADHAR_AUTH_URL_VERIFIED_OTP payload = { "aadhaarNo": obj.aadhar_card, "consent": "Y", "requestId": request_id, "otp": otp } result = requests.post(url, data=json.dumps(payload), headers=header, verify=False) result_json = result.json() status = result_json.get('result', {}).get('message', '') # Save the results to the database if change: obj = aadhar_card.objects.get(pk=obj.pk) obj.aadhar_card = aadhar_card obj.aadhar_request_json = json.dumps(payload) obj.aadhar_response_json = json.dumps(result_json) obj.updated_by = request.user.id status_code = result_json.get('statusCode') if status_code == 101: obj.status = 101 # Verified else: obj.status = 3 # Not Verified obj.save() else: obj.aadhar_card = aadhar_card obj.aadhar_request_json = json.dumps(payload) obj.aadhar_response_json = json.dumps(result_json) obj.added_by = request.user.id … -
Django : use @property in success_url KO . while using it with get_success_url is OK (class based view)
I found a workaround for my issue but I need to know why the first above case doesn't work. I need to pass a parameter (reman_pk) to my view but when I try : class RepairCreateView(LoginRequiredMixin, CreateView): @property def reman_pk(self): return int(self.kwargs['reman_pk']) [...] success_url = reverse_lazy( 'reman:update-reman', kwargs={'pk': reman_pk}) [...] ... I got an error django.urls.exceptions.NoReverseMatch: Reverse for 'update-reman' with keyword arguments '{'pk': <property object at 0x10c20bbd0>}' not found. 1 pattern(s) tried: ['reman/update/(?P[0-9]+)/$'] But when in the same class based view I use : def get_success_url(self, **kwargs): if kwargs != None: return reverse_lazy('reman:update-reman', kwargs={'pk': self.reman_pk}) ... it's OK : an int is well passed in my URL. I tried to pass int(reman_pk) in the first method ... not better. I've already use @property in the past and always got a value (int/str) and not property object. -
what are the good python package for designing a search engine for database?
for example: End user enter a fuzzy input like "Telas", it should match with the database "Tesla" (Example: search a company from a large database) Autocomplete FuzzyMatch Can anyone help me to make a clear logic how to design this? Thank you so much~~ -
Python Django Module Connection promblem
What will i do when 3 modules in Python Django,they are User ,admin,super admin when super admin has power to do CRUD and User only View the product What will i do when 3 modules in Python Django,they are User ,admin,super admin when super admin has power to do CRUD and User only View the product -
How to implement a common function in Django for same URL pattern?
I want to have a common function for APIs' of the same pattern which should run that function and then the API's function. For example, I want to call the API - api/student/details which would return the user details and there are a lot of APIs with the pattern - api/student/*. For all the APIs with this pattern, I want to check if the user in request body is a valid student. And then it should call the function associated with api/student/details. How do I implement this in django? -
Django, Error 404, Not Found: /products/5 GIVE me Your hand
I have quation regarding Django, I tried to solve it myself during 2 days, but I haven't any ideas about this problem, can YOU help me? I read a book about Django, and there is example: urls.py from django.urls import re_path from django.urls import path from firstapp import views urlpatterns = [ re_path(r'^products/?P<productid>\d+/', views.contact), re_path(r'^users/(?P<id>\d+)/?P<name>\D+/', views.about), re_path(r'^about/contact/', views.contact), re_path(r'^about', views.about), path('', views. index), ] views.py from django.http import HttpResponse def index(request): return HttpResponse("<h2>Main</h2>") def about(request): return HttpResponse("<h2>About site</h2>") def contact(request): return HttpResponse("<h2>Contacts</h2>") def products(request, productid): output = "<h2>Product № {0}</h2>".format(productid) return HttpResponse(output) def users(request, id, name): output = "<h2>User</h2><h3>id: {О} " \ "Name:{1}</hЗ>".format(id, name) return HttpResponse(output) But after using this link(http://127.0.0.l:8000/products/5), I get this text: Using the URLconf defined in hello.urls, Django tried these URL patterns, in this order: ^products/?P\d+/ ^users/(?P\d+)/?P\D+/ ^about/contact/ ^about The current path, products/5, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. And this thing in terminal: Not Found: /products/5 [08/Feb/2023 12:17:13] "GET /products/5 HTTP/1.1" 404 2597 I need Your help! I tried to delet code about: re_path(r'^products/?P<productid>\d+/', views.contact), re_path(r'^users/(?P<id>\d+)/?P<name>\D+/', views.about), and I … -
How to send form data in POST request in Nuxt 3 to django DRF
I am trying to use Nuxt 3 as a server to pass through API requests. I would like to make FormData requests to a Django DRF API through my Nuxt server to POST data and images. basically, the usecase is filling a simple form with data and images and send the formdata to a django backend. Here are more details. In pages.vue: const taskData = reactive({ title: '', city: '', description: '', category: route.params.cat_slug, subCat: '', image_1: [], image_2: [], image_3: [] }) const submitTaskForm = async () => { let formData = new FormData() formData.append('title', taskData.title) formData.append('city', taskData.city) formData.append('description', taskData.description) formData.append('category', taskData.category) formData.append('subCat', taskData.subCat) taskData.image_1.forEach((fileItem) => { formData.append('image_1', fileItem.file) }) taskData.image_2.forEach((fileItem) => { formData.append('image_2', fileItem.file) }) taskData.image_3.forEach((fileItem) => { formData.append('image_3', fileItem.file) }) const data = await useFetch('/api/tasks/add/', { method: 'POST', body: formData }) return data } in /server/api/add.post.ts export default defineEventHandler(async (event) => { const body = await readBody(event) const access = getCookie(event, 'access') || null try { const data = await $fetch(process.env.API_BASE_URL + "/api/tasks/add/", { method: "POST", body: body, headers: { Authorization: "Bearer " + access, }, }) return data } catch (error) { console.log(error); return error } }) now the backend part with the view handling the … -
operator does not exist: bigint = uuid LINE 1: ...NER JOIN "users" ON
I decided to change my default id today because I thought of scalability of my project. Since I changed the user main primary key to UUID I ran into a series of errors, some of which I could fix thanks to some questions on stackoverflow. I'm using the "oauth2_provider_access token" for my authentication from the oauth2_provider. I don't really know again from where this other one came from but when ever I try my API I'm stuck. My error log below [08/Feb/2023 08:46:54] "POST /admin/login/?next=/admin/ HTTP/1.1" 302 0 Internal Server Error: /admin/ Traceback (most recent call last): File "/home/user_me/f_project/softwareAPI/software_venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedFunction: operator does not exist: bigint = uuid LINE 1: ...NER JOIN "users" ON ("django_admin_log"."user_id" = "users".... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/user_me/f_project/softwareAPI/software_venv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/user_me/f_project/softwareAPI/software_venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 220, in _get_response response = response.render() File "/home/user_me/f_project/softwareAPI/software_venv/lib/python3.10/site-packages/django/template/response.py", line 114, in render . . . . . . File "/home/user_me/f_project/softwareAPI/software_venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute with self.db.wrap_database_errors: File "/home/user_me/f_project/softwareAPI/software_venv/lib/python3.10/site-packages/django/db/utils.py", line 91, … -
Django annotate with dynamic value
Hi in my model i have property that fully is in cache, not in database class Model(models.Model): .... @property def _get_last_seen_cache_name(self) -> str: return f'{self.hostname.upper()}_last_seen' @property def last_seen(self) -> datetime | None: cached = cache.get(self._get_last_seen_cache_name, None) if isinstance(cached, datetime): return cached return None def update_last_seen(self) -> None: cache.set(self._get_last_seen_cache_name, get_now().replace(microsecond=0), None) How can i annotate with this value last_seen queryset. Want use sorting on this column in admin page. But for this, i need get values from cache on annotation, execute cache.get() with proper key name. Something like this, not working example: queryset = super().get_queryset(request) queryset = queryset.annotate(last_seen=Value(cache.get(Concat('hostname', Value('_last_seen')))), CharField())) or queryset = queryset.annotate(last_seen=Value(cache.get(f"{F('hostname')_last_seen}")), CharField())) I can annotate with literal value, but how annotate with dynamic value, that doesnt exist in database, but in cache or in memory only? How to do hostname substitution in a function? -
Correct Django serializer implementation for many to many field
I have two django models that are related with a many to many field: class Member(models.Model): user = models.OneToOneField(to=settings.AUTH_USER_MODEL) date_of_birth = models.DateField() bio = models.TextField() class Book(models.Model): name = models.CharField(max_length=255) author= models.CharField(max_length=255) description = models.TextField() read_by = models.ManyToManyField(to=Member, related_name='books_read') The serializers for these models are: class MemberSerializer(serializers.Model): id = serializers.IntegerField(read_only=True) user_id = serializers.IntegerField(read_only=True) class Meta: model = Member fields = ['id', 'user_id', 'date_of_birth', 'bio'] class BookSerializer(serializers.Model): id = serializers.IntegerField(read_only=True) class Meta: model = Book fields = ['id', 'name', 'author', 'bio'] I want to create an endpoint to be able to add a book to a member. The only way I could write a serializer for it was: class BookIdSerializer(serializers.Model): class Meta: model = Book fields = ['id'] def update(self, **kwargs): # logic to add book with passed id to the authenticated user's member profile This however feels very wrong for two obvious reasons: 1 - There is an entire serializer object just to receive a book id 2 - It is not even generic because it performs a very specific function of adding a book with passed book id to a member I am sure there is a better way of doing this. Kindly guide me if you know. -
Django images upload fails
I am using django to upload a image to the database (POST request) and show the same in the site. but for some reason my image is not uploading models.py - from django.db import models class image_classification(models.Model): pic=models.ImageField(upload_to='images') views.py from django.shortcuts import render from .models import image_classification from django.http import HttpResponse, HttpResponseRedirect # def home(request): # print('here you go ') # images=image_classification.objects.all() # url=images[len(images)-1].pic.url # return render(request,'home.html',{'print':'everything is ok','image':url}) def home(request): print('here you go ') images=[] images=image_classification.objects.all() if len(images) > 0: url=images[len(images)-1].pic.url else: url="place holder image url" return render(request,'home.html',{'print':'everything is ok','image':url}) #handles uploaded images def uploadImage(request): print('image handling ') img= request.FILES['image'] image=image_classification(pic=img) image.save() return HttpResponseRedirect('/') url of the app from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('',views.home,name='home') ] urlpatterns+= static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) url.py for project (incase you need this) from django.contrib import admin from django.urls import path, include from ImageClassifier import views from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path("admin/", admin.site.urls), path('', include('ImageClassifier.urls')), ] lastly settings.py (not sure if this is needed) MEDIA_ROOT= os.path.join(BASE_DIR,'ImageClassifier/media/') MEDIA_URL= '/media/' STATIC_URL = "/static/" STATIC_ROOT= os.path.join(BASE_DIR, 'static') and this is the error i am getting on the … -
django web server running with iis doesn't run static css js image files
enter image description herehi I have a django web server project running on ISP and static file is not working How do I make changes to Internet Information Services (IIS) and web cofig file for static files to work? ` <appSettings> <!-- Required settings --> <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> <!-- Your django path --> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\pax_web_server_app" /> <!-- Your djangoname.settings --> <add key="DJANGO_SETTINGS_MODULE" value="pax_web_server_app.settings" /> </appSettings> <system.webServer> <handlers> <add name="paxsite" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python311\python.exe|C:\Python311\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" /> </handlers> <staticContent> <mimeMap fileExtension=".tab" mimeType="static/css" /> </staticContent> </system.webServer> ` https://learn.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap I did the instructions on the microsoft website but it still didn't work -
Django Store Engine and Celery
Can I use django.contrib.sessions.backends.db with Celery in my Django project? I ask this because when I execute login(request, user, user.backend), request's session_key is not stored inside DjangoSession table. this is the piece of code: engine = import_module(settings.SESSION_ENGINE) # Create a fake request to store login details. request = HttpRequest() request.session = engine.SessionStore() login(request, user, user.backend) # Save the session values. request.session.save() -
django group by foreign key aggregation
i have models like this: class Coin(models.Model): symbol = models.Charfield() class User(models.Model): phone_number = models.Charfield() class Portfo(models.Model): class Meta: unique_together = ( "user", "coin", ) user = models.ForeignKey( to=User, on_delete=models.CASCADE, null=False, related_name="portfo", ) coin = models.ForeignKey( to=Coin, on_delete=models.CASCADE, null=False, related_name="owners", ) available = models.DecimalField( max_digits=40, decimal_places=20, default=Decimal(0), ) blocked = models.DecimalField( max_digits=40, decimal_places=20, default=Decimal(0) ) i want to aggregate portfo grouped by users like this: [ { "user_id":1, "portfo":{ "coin_1_symbol":Decimal("1"), "coin_2_symbol":Decimal("2"),... } }, { "user_id":2,... },... ] or this: [ { "user_id":1, "portfo":[ {"coin_symbol":"some_symbol","total":Decimal("1")}, {"coin_symbol":"some_symbol","total":Decimal("2")},... ] },... ] i tried aggregation with values but it returns this result: >> Portfo.objects.exclude(available=0,blocked=0).annotate(total=Sum(F("available")+F("blocked"))).values("user_id","total","coin__symbol") [{"user_id":1,"coin_1_symbol":"some_symbol","total":"Decimal("1")},{"user_id":1,"coin_2_symbol":"some_symbol", "total":Decimal("2")},...] is there any way to do this with django orm? Thanks for your help:) -
How to connect views with forms and save it in db Django
I have a form which trying to connect to multiple views where i get multipleModelChoice form-select and i actually dont know how to save them in db or connect them to my "WorkLog" model I got validation error which i called in "create_worklog" func with messages.error Any advices pls? models.py class WorkLog(models.Model): worklog_date = models.DateField(verbose_name='Дата', ) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, blank=True, related_name='contractor_user',on_delete=models.CASCADE) contractor_counter = models.ForeignKey(CounterParty, blank=True, related_name='contractor_user', on_delete=models.CASCADE) contractor_object = models.ForeignKey(ObjectList, blank=True, related_name='contractor_user', on_delete=models.CASCADE) contractor_section = models.ManyToManyField(SectionList, default=None, related_name='contractor_user' description = models.TextField(blank=True,) forms.py class WorkLogForm(forms.ModelForm): worklog_date = forms.DateField(label='Дата', widget=forms.DateInput( attrs={'type': 'date', 'class': 'form-control', 'placeholder': 'Введите дату'})) description = forms.CharField(label='Описание', widget=forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Описание'})) class Meta: model = WorkLog fields = ( 'worklog_date', 'contractor_counter', 'contractor_object', 'contractor_section', 'description' ) views.py def object_list(request): get_counter = request.GET.get('counter') objects = ObjectList.objects.filter(contractor_guid__in=[get_counter]) context = {'objects': objects, 'is_htmx': True} return render(request, 'partials/objects.html', context) def sections_list(request): get_object = request.GET.get('objects') sections = SectionList.objects.filter(object=get_object) context = {'sections': sections} return render(request, 'partials/sections.html', context) def create_worklog(request): counter_party = CounterParty.objects.filter(counter_user=request.user) if request.method == 'POST': form = WorkLogForm(request.POST) if form.is_valid(): work_log = form.save(commit=False) work_log.author = request.user work_log.contractor_counter = counter_party work_log.contractor_object = object_list(request).objects work_log.contractor_section = sections_list(request).sections work_log = form.save() messages.success(request, 'Everything okay', {'work_log': work_log}) return redirect('create_worklog') else: messages.error(request, 'Validation error') … -
Django Wagtail dynamic Menu's based on User and User Role
Using Django-Wagtail and Wagtail Menu's. I want to build a system with the following types of characteristics. I have a class of user (Vendor, Supplier) Each created user would need to be one of these two classes. Each class of user has different roles and the roles differ from class to class. e.g. Vendor: finance, stock, admin Supplier: finance, stock, admin, driver. What I have done is create a class called UserType and both "Vendor" & "Supplier" inherit from this class. Then added a field to the User class that selects which type of user they are. class UserType(model.Model): common fields....... class Vendor(UserType): child_vendor_only_fields..... class Supplier(UserType): child_supplier_only_fields..... class User(AbstractUser): userVar = models.ForeignKey(UserType, on_delete=models.SET_NULL, null=True, blank=True) I have also used the wagtail admin to create custom roles for each of these classes as described above. Clearly what "Vendors" can create, read, update and delete varies from that of a "Supplier". And still within that what the finance role can do within the "Vendor" differs from what "Stock" can do. How would I create a dynamic menu that displays different menu's for these permutations? My initial thoughts were inspired by this. Simply adding a choicefield USER_TYPE_CHOICES = ( ('Vendor', 'Vendor'), ('Supplier', 'Suplier')) … -
Join and get queryset accordring to many to many field
I have MyUser model with ForeignKey and ManyToMany related fields city and skills: class MyUser(AbstractBaseUser): email = models.EmailField() skills = models.ManyToManyField('jobs.Skill') class Skill(models.Model): name = models.CharField() suppose this my table data in database {'email': 'some@email.com', 'skills': ['Python', 'Java']}, {'email': 'another@email.com', 'skills': ['JavaScript', 'C#', 'Python']} >>> MyUser.objects.all().count() output is 2 but iwant MyUser.objects. .......... answer to 5 my like following data {'email': 'some@email.com', 'city': 'London', 'skills': 'Python'}, {'email': 'some@email.com', 'city': 'London', 'skills': 'Java'}, {'email': 'another@email.com', 'city': 'Berlin', 'skills': 'JavaScript'}, {'email': 'another@email.com', 'city': 'Berlin', 'skills': 'C#'}, {'email': 'another@email.com', 'city': 'Berlin', 'skills': 'Python'}, -
Django-Pass data from html to python and wise versa
Index.html <form class="grid" method="POST" action={% url 'result' %}> {% csrf_token %} <textarea name="name" /></textarea> <button type="submit"">Detect</button> </form> <label>{{name}}</label> view.py def result(request): name = request.POST['name'] name=preprocessing(name) return render( request, "index.html", name=name ) urls.py urlpatterns = [ path("", views.homePage, name='result'), ] i am making a website using django where i have to get data from html page in python file and after getting data i have to perform some preprocessing on data. and after that again return back to the same page with some new information when i press a button. The problem is that i when i press button than i move to the same page button the new information is not displaying after clicking on a button -
Unit testing a unittest custom test runner in Django
I am trying to unit test a custom test runner using unittest framework but I get this error. File "/usr/local/lib/python3.7/dist-packages/django/test/runner.py", line 466, in setup_test_environment setup_test_environment(debug=self.debug_mode) File "/usr/local/lib/python3.7/dist-packages/django/test/utils.py", line 111, in setup_test_environment "setup_test_environment() was already called and can't be called " RuntimeError: setup_test_environment() was already called and can't be called again without first calling teardown_test_environment(). I understand that this error message is pretty self explanatory but the problem with running teardown_test_environment within the unit test ends up in this error message File "/usr/local/lib/python3.7/dist-packages/django/test/runner.py", line 588, in teardown_test_environment teardown_test_environment() File "/usr/local/lib/python3.7/dist-packages/django/test/utils.py", line 144, in teardown_test_environment saved_data = _TestState.saved_data AttributeError: type object '_TestState' has no attribute 'saved_data' Has anyone encountered something like this before?