Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django models how to fix circular import error?
I read about solution for the error (write import instead of from ...) but it doesn't work I think because I have a complex folder structure. The folder structure quiz/models.py import apps.courses.models as courses_models class Quiz(models.Model): lesson = models.ForeignKey(courses_models.Lesson, on_delete=models.DO_NOTHING) # COURSE APP MODEL IMPORTED courses/models.py import apps.quiz.models as quiz_models class Lesson(models.Model): ... class UserCompletedMaterial(models.Model): ... lesson = models.ForeignKey(lesson) quiz = models.ForeignKey(quiz) # QUIZ APP MODEL IMPORTED How you can see I just can't keep it together or something else.. Because I think the UserCompletedMaterial model is a part of courses app -
How can I upload multiple files in to a Django model?
I'm trying to make an LMS system with Django and now I need to upload multiple pdf files to the curriculum of the class. I can upload one file with the OnetoOne field in the Django model but not more. When I try to add another material for the same class it says Upload materials with this Uploaded class already exists. This is my model code. class UploadMaterials(models.Model): name = models.CharField(max_length=255) uploaded_class = models.OneToOneField(Class, on_delete=models.CASCADE, related_name='upload_materials') upload_material = models.FileField(upload_to=rename, null=True) class Meta: verbose_name_plural = "Materials" I need to upload the materials and be able to view them in the template. like...... {% for material in class.materials %} <h1>{{ material.name }}</h1> {% endfor %} I tried the Django ForeignKey instead of OnetoOne and was able to create multiple materials for the same class but could not figure out how to access them from the template. What I want to know is how to upload multiple files to the same class and how to access them in the template. Thank you! -
Why am I getting "page not found" error in Django?
I am new in Django Framework having no previous experience with any other framework. After writing these code and hitting the url http://127.0.0.1:8000/MyApp/f2/400 I get the error "Page not found " This is the code of my Project's main urls.py file : from django.contrib import admin from django.urls import path from django.conf.urls import include,url urlpatterns = [ path('admin/', admin.site.urls), path('MyApp', include('MyApp.urls')), ] This is the code of my MyApp.urls file : from django.urls import path from django.conf.urls import include,url from MyApp import views urlpatterns = [ url('test', views.Index, name='Index'), url('f2/<int:guess>', views.F.as_view()), ] I have attached the image of erroneous page. -
Problem with timezone in Django ORM, datetime value differs from the value stored in the table
I have stored some data into PostgreSQL database. Here is the corresponding Django model: from django.contrib.gis.db import models class PrecipitationContourDjango10d(models.Model): value = models.FloatField(blank=True, null=True) geometry = models.PolygonField(blank=True, null=True) date = models.DateTimeField(blank=True, null=True) window_no = models.CharField(max_length=10, blank=True, null=True) color = models.CharField(max_length=20, blank=True, null=True) def __lt__(self, other): if self.date < other.date: return True return False class Meta: db_table = 'precipitation_contour_web_service10d' Here is some rows that are stored in the table: As you can see the datetime value for the row with id=5921 is 2021-05-07 21:00:00-07. However when I retrieve that row using the Django ORM, its datetime field will change: from data.models import PrecipitationContourDjango10d row = PrecipitationContourDjango10d.objects.get(id=5921) How can I solve this issue? Thanks. -
Forms are not getting displayed on django
models.py from django.db import models Create your models here. class dhiraj(models.Model): title=models.CharField(max_length=200, default="" ) completed=models.BooleanField(default=False) created_at=models.DateTimeField(auto_now=True) def __str__(self): return self.title forms.py from django import forms from django.forms import ModelForm from . models import dhiraj class dhirajForm(forms.ModelForm): class meta: model=dhiraj fiels='__all__' index.html <h1>this is</h1> <form> {{form}} </form> {% for taskk in dhiraj %} <div> <p>{{taskk}}</p> </div> {% endfor %} the coming error is Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Dhiraj Subedi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\Dhiraj Subedi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site- packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module return … -
Implementing notifications in django with MySQL
I am developing a web app using django.I need to check database continuously and if the database(mySQL) value is less than X, the user should get notification.what should I do? I have read about celery,dramatiq, django channels and many more but still confused how to implement them. Can anyone help me with this -
HTML code from one to another file is not extending in Django project
I am getting this issue from start of my project. I spent a day to solve but nothing happened. Code from base.html is showing on the page but the code from shop.html is not. base.html shop.html -
Passing a variable from javascript to Django view
I want to send a variable I got from a javascript function to my Django view. The function is as below: <script> function googleSignin() { firebase.auth().signInWithPopup(provider).then(function(result) { var token = result.credential.accessToken; var user = result.user; console.log(token) console.log(user) var uid = user.uid; return uid; }).catch(function(error) { var errorCode = error.code; var errorMessage = error.message; console.log(error.code) console.log(error.message) }); } </script> I used a onclick tag to call this function and the values properly show up in the console. I just need to send the value returned to my views somehow. I've tried using ajax to call on the view but I can't figure out how to make it work. The ajax code is below: $.ajax({ // points to the url where your data will be posted url: /gsignin/, // post for security reason type: "POST", // data that you will like to return data: {uid : uid}, // what to do when the call is success success:function(response){ console.log(sid); }, // what to do when the call is complete ( you can right your clean from code here) complete:function(){ window.location.href = "/gsignin/" }, // what to do when there is an error error:function (xhr, textStatus, thrownError){} }); I'm really new to this stuff … -
how to show all orders amount respective to every user in a table without duplicating a username twice
i have this order model: class Order(models.Model): productType = [ ('Document', 'Document'), ('Parcel', 'Parcel'), ('Box', 'Box') ] serviceType = [ ('Home', 'Home delivery'), ('Office', 'Office delivery'), ('Pick up from office', 'Pick up from office'), ] delivery_StatusType = [ ('Return', 'Return'), ('Delivering', 'Delivering'), ('Pending', 'Pending'), ('Complete', 'Complete') ] statustype = [ ('Paid', 'Paid'), ('Cash on delivery', 'Cash on delivery') ] status = [ ('Instant', 'Instant'), ('Same Day', 'Same Day'), ('Others', 'Others') ] payment_types = [ ('Cash', 'Cash'), ('Wallet', 'Wallet'), ('Online', 'Online') ] CHOICE_AREA = [ ('Inside Dhaka', 'Inside Dhaka'), ('Dhaka Suburb', 'Dhaka Suburb'), ('Outside Dhaka', 'Outside Dhaka') ] user = models.ForeignKey(User, on_delete=models.CASCADE) receiver = models.CharField(max_length=100, blank=False, unique=False) receiver_Contact = models.CharField( max_length=20, blank=False, unique=False) receiver_Email = models.CharField( max_length=100, blank=False, unique=False) payment = models.CharField( max_length=100, choices=payment_types, blank=False) area = models.CharField( max_length=100, choices=CHOICE_AREA, blank=True, null=True) weight = models.CharField(max_length=100, blank=True, null=True) service = models.CharField(choices=serviceType, max_length=100) product_Type = models.CharField(choices=productType, max_length=100) contents = models.CharField(max_length=100, blank=False, unique=False) quantity = models.CharField(max_length=100, blank=False, unique=False) package = models.ForeignKey( Package, on_delete=models.CASCADE, default=0) priority = models.CharField( choices=status, blank=True, null=True, max_length=20) amount = models.CharField(max_length=100, blank=True, unique=False) delivery_Status = models.CharField( choices=delivery_StatusType, blank=True, null=True, max_length=50) paid = models.BooleanField(default=False) reference_id = models.CharField(max_length=100, blank=True, unique=True) delivery_time = models.DateField(blank=True, null=True) created = models.DateField(auto_now_add=True) tran_id = models.CharField(max_length=20, blank=True, null=True) driver … -
How to achieve Waiting Room to match people 1-on-1 with Django Channels?
I could not find any starter basic solution for this problem. My thought process right now that when users join to the queue they will be added temporarily to a WaitingRoom model. Then there is a 10 seconds delay for waiting, the next step that they will be randomly match with each other. My problem with this that it won't prevent that multiple users would be matched up with each other. This is my current messy solution. It sends out to everyone in the queue and checks on the frontend if the current user is actually in the pair. class WaitingRoomConsumer(AsyncConsumer): @database_sync_to_async def get_waiting_room(self, user): room = WaitingRoom.objects.all().exclude(user=user) serializer = WaitingRoomSerializer(room, many=True) return serializer.data @database_sync_to_async def add_to_waiting_room(self, user): if (WaitingRoom.objects.filter(user=user).count() == 0): return WaitingRoom.objects.create(user=user) @database_sync_to_async def get_user_id(self, username): return User.objects.get(username=username).id @database_sync_to_async def remove_from_waiting_room(self, user): room = WaitingRoom.objects.get(user=user) return room.delete() async def websocket_connect(self, event): current_user = self.scope['user'] self.room_obj = await self.add_to_waiting_room(current_user) self.room_name = "WAITING_ROOM" #f'waiting_room{self.room_obj.id}' await self.channel_layer.group_add(self.room_name, self.channel_name) await self.send({ 'type': 'websocket.accept' }) msg = json.dumps({ 'type': 'joined', 'username': current_user.username, }) await self.channel_layer.group_send( self.room_name, { 'type': 'websocket.message', 'text': msg } ) print(f'[{self.channel_name}] - You are connected.') await self.recommend_candidate() async def websocket_receive(self, event): print(f'[{self.channel_name}] - Recieved message. - {event["text"]}') msg = event.get('text') … -
Anyone knows how to properly create subscriptions (real time api )in django graphene?
I am using Django graphene and I successfully created queries and mutations, but when it comes to the subscription I find out the graphene doesn't sopported officially but it suggesting few libraries with very vague documentations and not working examples at all. However, I created a web socket chat app before but when it came to subscription it never works with me. any ideas any working exampes please? -
How to test a django rest url with query parameter?
My URL has 'nutritionist' query parameter, in this case, it will get profiles that has nutritionist with id=1 /profiles?nutritionist=1 When I tried to test this 'filtering' like this: def test_get_user_belonging_to_a_nutritionist(self): response = self.client.get("/profiles?nutritionist=1/",secure=True) users = CustomUser.objects.filter(nutritionist=1) serializer = CustomUserDetailsSerializer(users, many=True) self.assertEqual(response.data, serializer.data) The response contains HttpResponsePermanentRedirect object, instead of the normal response This is my Views.py if it helps class GetProfilesViewSet(generics.ListAPIView): serializer_class = CustomUserDetailsSerializer def get_queryset(self): """ Optionally restricts the returned purchases to a given user, by filtering against a `username` query parameter in the URL. """ queryset = CustomUser.objects.all() nutritionist_id = self.request.query_params.get('nutritionist') if nutritionist_id is not None: queryset = queryset.filter(nutritionist=nutritionist_id) return queryset How can I test this case? -
Adding your own link to the header of the django admin panel
I need to add a link to my page in the admin panel of the django framework How can this be done? Perhaps you can somehow add it here -
Change site address http://127.0.0.1:8000/ to something like http://www.rajSite.com in Django
I have tried python manage.py runserver www.rajSites.com but didnt work I searched in google for more than 1 hr. No info is available. I am using the development server that comes with Django. How to change https://127.0.0.1 to https://rajSites.com(Own Url).. Please Share your Ideas regarding this... Advance Thanks for helping... -
In Django there is some thing wrong with my code I cant retrieve the fields of value={{ i.cv}}, value={{ i.status}}, value={{ i.gender}} see the html
This is my edit.html code and during retrieving the values from database it shows only the text fields like value={{ i.full_name}} but when I am writing value={{ i.cv}}, value={{ i.status}}, value={{ i.gender}} it does not shows the value which needs to bed edited I have two choice fields and one file field. this is my edit.html <section class="site-section"> <div class="container"> <div class="row"> <div class="col-lg-12 mb-5"> <h2 class="mb-4 text-center">Update Candidate Details</h2> <form method="POST" action="/update/ {{i.id}}/" enctype="multipart/form-data" class="p-4 border rounded" onsubmit="myFunction()" > {% csrf_token %} {% comment %} <input type="hidden" name="csrfmiddlewaretoken" value="UabxqpD8HGPOu1ZSFnIHAPbMtRgWBAnVHEs8bLDx0HnxN6uhG3LyYvZShvcx1ekn"> {% endcomment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="full_name">Full Name :</label> <input type="text" class="form-control" value ={{ i.full_name}} name="full_name" id="id_full_name" placeholder="Enter First Name"> </div> </div> <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="recruiter_name">Recruiter Name :</label> <input type="text" class="form-control" value ={{ i.recruiter_name }} name="recruiter_name" id="id_recruiter_name" placeholder="Enter Recruiter Name"> </div> </div> {% comment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="id_last_name">Last Name :</label> <input type="text" class="form-control" name="last_name" id="id_last_name" placeholder="Enter Last Name"> </div> </div> {% endcomment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="email">Email :</label> <input type="email" class="form-control" value ={{i.email }} name="email" id="id_email" placeholder="Enter Email"> </div> </div> <div class="row form-group"> <div class="col-md-12 … -
Add new parameters at Django rest framework pagination
I want to add 'isSuccess' at the pagination returns. For example, { "count": 1234, "next": "http://mydomain/?page=2", "previous": null, "isSuccess" : 'Success' # <---- this one "results": [ { 'id':123, 'name':'abc' }, { 'id':234, 'name':'efg' }, ... ] } I found this way but It didn't work. How can I add new parameters at Django pagination return? this is my try: class Testing(generics.GenericAPIView): queryset = Problem.objects.all() serializer_class = userSerializer pagination_class = userPagination def get(self, request): queryset = self.get_queryset() page = self.request.query_params.get('page') if page is not None: paginate_queryset = self.paginate_queryset(queryset) serializer = self.serializer_class(paginate_queryset, many=True) tmp = serializer.data tmp['isSuccess'] = 'Success' return self.get_paginated_response(tmp) -
Overwriting save method not working in Django Rest Framework
I have a model (Points) which saves the points based on the purchase made by a user. I have made in such a way that when order is made (orderapi is called), a signal is passed with order instance and points are calculated based on the amount and it is saved using the save method. Alothugh Order object is created, I dont see the points being saved in the database. I am not sure what is the issue. My models: class Order(models.Model): ORDER_STATUS = ( ('To_Ship', 'To Ship',), ('Shipped', 'Shipped',), ('Delivered', 'Delivered',), ('Cancelled', 'Cancelled',), ) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) @property def total_price(self): # abc = sum([_.price for _ in self.order_items.all()]) # print(abc) return sum([_.price for _ in self.order_items.all()]) def __str__(self): return self.user.email class Meta: verbose_name_plural = "Orders" ordering = ('-id',) class OrderItem(models.Model): orderItem_ID = models.CharField(max_length=12, editable=False, default=id_generator) order = models.ForeignKey(Order,on_delete=models.CASCADE, blank=True,null=True,related_name='order_items') item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True) order_variants = models.ForeignKey(Variants, on_delete=models.CASCADE,blank=True,null=True) quantity = models.IntegerField(default=1) @property def price(self): total_item_price = self.quantity * self.order_variants.price # print(total_item_price) return total_item_price class Points(models.Model): order = models.OneToOneField(Order,on_delete=models.CASCADE,blank=True,null=True) points_gained = models.IntegerField(default=0) def collect_points(sender,instance,created,**kwargs): total_price = instance.total_price if created: if total_price <= 10000: abc = 0.01 * total_price else: … -
form are not display
models.py from django.db import models Create your models here. class dhiraj(models.Model): title=models.CharField(max_length=200, default="" ) completed=models.BooleanField(default=False) created_at=models.DateTimeField(auto_now=True) def __str__(self): return self.title form.py from django import forms from django.forms import ModelForm from . models import dhiraj class dhirajForm(forms.ModelForm): class meta: model=dhiraj fiels='__all__' index.html <h1>this is</h1> <form> {{form}} </form> {% for taskk in dhiraj %} <div> <p>{{taskk}}</p> </div> {% endfor %} error says ValueError at / ModelForm has no model class specified. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.2 Exception Type: ValueError Exception Value: ModelForm has no model class specified. Exception Location: C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages\django\forms\models.py, line 295, in init Python Executable: C:\Users\Dhiraj Subedi\dhiraj\virenv\Scripts\python.exe Python Version: 3.9.4 Python Path: ['C:\Users\Dhiraj Subedi\dhiraj\first', 'C:\Users\Dhiraj ' 'Subedi\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\Dhiraj Subedi\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\Dhiraj Subedi\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\Dhiraj Subedi\AppData\Local\Programs\Python\Python39', 'C:\Users\Dhiraj Subedi\dhiraj\virenv', 'C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages'] Server time: Sat, 08 May 2021 06:29:28 +0000 -
Django Question 'ModelChoiceField' object has no attribute 'use_required_attribute'
Dears, I met a problem in Django. There is an error about 'ModelChoiceField' object has no attribute 'use_required_attribute' and I don't know where I made mistake. My goal is to make my submit customizing form but I couldn't understand how CBV in Django can reach this goal, so I went back to use forms.py and FBV in Django. But my fields in form model have foreign keys to refer other models. I used forms.ModelChoiceField and expected to solve foreign key problem but it doesn't work and show this error. Thank you for reading and hope someone can help me to solve it. Here are my code: forms.py from django import forms from .models import Case from school_app.models import School from student_app.models import Student class CaseModelForm(forms.ModelForm): class Meta: model = Case fields='__all__' widgets = { 'name' : forms.ModelChoiceField(queryset=Student.objects.all()), 'phone' : forms.TextInput(), 'school' :forms.ModelChoiceField(queryset=School.objects.all()) } models.py from django.db import models from django.urls import reverse import datetime,time from school_app.models import School from student_app.models import Student # Create your models here. class Case(models.Model): name=models.ForeignKey(Student,related_name='case_student_name',on_delete=models.CASCADE,verbose_name="姓名") phone=models.CharField(verbose_name="電話",blank=False,max_length=256) school=school=models.ForeignKey(School,related_name='case_school',on_delete=models.CASCADE,verbose_name="學校") views.py def CaseFormView(request): print("CaseForm") form_cus = CaseModelForm() if request.method == "POST": form = CaseModelForm(request.POST) if form.is_valid(): form.save() return redirect("/") context={ 'form_cus': form_cus } return render(request, 'case_app/case_form.html',context) urls.py from … -
Database storing weeks and days of week (Efficient method)
I couldn't decide which is the most effective way of storing the week and the days of the week. if x person is available on day d First Option; class Week(models.Model): user availability = models.BooleanField() # if **x** is available at least one day in week **w** start = models.DateField() end = models.DateField() days = models.ManyToManyField('self', through='DaysOfWeek', symmetrical=False) class DaysOfWeek(models.Model): week = models.ForeignKey(Week, on_delete=models.CASCADE) date = models.DateField() availability = models.BooleanField(default=True) Second Option; class Week(models.Model): user availability = models.BooleanField() # if **x** is available at least one day in week **w** start = models.DateField() end = models.DateField() day1 = models.BooleanField(default=True) day2 = models.BooleanField(default=True) day3 = models.BooleanField(default=True) day4 = models.BooleanField(default=True) day5 = models.BooleanField(default=True) day6 = models.BooleanField(default=True) day7 = models.BooleanField(default=True) -
Python - Django persisting storage through gunicorn processes
I am having very specific use case of persisting storage inside Django production app, I cannot pickle instance of a class and save it to db, simple setup is needed of where instances of class can be saved to an array and accessed and removed. I want to look into pymemcache or would it be possible to persist memory inside file outside Django app? I know this is more technical than programming, but any help is great. Thank you. -
RelatedObjectDoesNotExist at /login/ User has no profile
Profile creation for every new user was working properly. But when I resize the image quality of the user profile from my 'models.py' file, then whenever I create a new user it doesn't create profile for that new user. How do I solve this problem? My codes are given below: Views.py: from django.shortcuts import render, redirect from .forms import UserSignupForm, UserUpdateForm, ProfileUpdateForm from django.contrib import messages from django.contrib.auth.decorators import login_required def signup(request): if request.method == 'POST': form = UserSignupForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') form.save() messages.success(request, f'Signup for {username} is successful') return redirect('login') else: form = UserSignupForm() return render(request, 'users/signup.html', {'title': 'signup', 'form': form}) @login_required def profile(request): context = { 'title' : 'Profile' } return render(request, 'users/profile.html', context) @login_required def update_profile(request): if request.method == 'POST': user_update = UserUpdateForm(request.POST, instance=request.user) profile_update = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if user_update.is_valid() and profile_update.is_valid(): user_update.save() profile_update.save() messages.success(request, 'Profile has been updated!') return redirect('profile') else: user_update = UserUpdateForm(instance=request.user) profile_update = ProfileUpdateForm(instance=request.user.profile) context = { 'title' : 'Update Information', 'u_form' : user_update, 'p_form' : profile_update } return render(request, 'users/profile_update.html', context) signals.py: from django.db.models.signals import post_save from django.contrib.auth.models import User from .models import Profile from django.dispatch import receiver @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, … -
Django best practice to display data to template
I have a Django template that I would like to display a users transactions and I would like to know the best practice for displaying data from my database to the template. Should I implement a form that sends a users 'Order by' value and make an SQL query and then return those results back to the user or should I just handle all the processing via JavaScript? What is the best practice? Note: I don't want the page refreshing so I think I'll be implementing AJAX Banking user transactions example: Date: 5/6/21, type: deposit, description: Venmo inc, amount: 200.00 Date: 5/7/21, type: card, description: Starbucks, amount: 6.75 Date: 5/7/21, type: withdrawal, description: Deja Vu club, amount: 250.00 Below is HTML Template: {% extends "home/base.html"%} {% load static %} {% block title %} <title>Account Transactions</title> {% endblock %} {% block body %} <div id="account-transactions-header">Account Activity</div> <div id="account-transactions-main"> <div id="account-transactions-container"> #User should be able to filter by date, type etc. <div id="account-transactions-order-by">Order by: </div> <div id="account-transactions"> #User transactions would appear here loading about 10 results and upon end of scroll request another 10 from database </div> </div> </div> {% endblock %} -
Creating Virtual Environment
I have completed a project in Django on my Windows PC without creating a virtual env. Now, I feel I should have a virtual env. How do I create it and put my project in the virtual env? Please, do explain to me in steps... Thank you in advance. -
python 2.7: ERROR:root:code for hash md5 was not found
I have installed python via homebrew on my macbook (macOS Big Sur 11.2.3). Yes, I know, it's outdated, but I need it for some old projects. I use virtualenv to seperate stuff. When I try to run ./manage.py runserver I got this error: ERROR:root:code for hash md5 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python@2/2.7.15_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python@2/2.7.15_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type md5 ERROR:root:code for hash sha1 was not found. Traceback (most recent call last): . . . File "/Users/Roland/PythonEnvs/django-wko/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python@2/2.7.15_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/Roland/PythonEnvs/django-wko/lib/python2.7/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/Roland/PythonEnvs/django-wko/lib/python2.7/site-packages/django/contrib/auth/base_user.py", line 8, in <module> from django.contrib.auth.hashers import ( File "/Users/Roland/PythonEnvs/django-wko/lib/python2.7/site-packages/django/contrib/auth/hashers.py", line 241, in <module> class PBKDF2PasswordHasher(BasePasswordHasher): File "/Users/Roland/PythonEnvs/django-wko/lib/python2.7/site-packages/django/contrib/auth/hashers.py", line 251, in PBKDF2PasswordHasher digest = hashlib.sha256 AttributeError: 'module' object has no attribute 'sha256' Maybe it is a problem with hashlib or openssl? Thanks.