Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python & Docker not clean threads
I have docker on my server and premium_daemon.py as daemon which clears the database and cancels orders. premium_daemon.py import time from django.core.management import BaseCommand from django.utils import timezone from adminPanel.models import MyUser, Message, User_purchase, Bot_user, Item from apiV1.bot_services import send_order_canceled class Command(BaseCommand): def handle(self, *args, **options): while True: users = MyUser.objects.filter(is_premium=True) for user in users: if user.premium_expiration_date < timezone.now(): user.is_premium = False user.save() messages = Message.objects.all() for message in messages: if timezone.now() > message.created_at + timezone.timedelta(days=7): message.delete() orders = User_purchase.objects.filter(is_paid=False) for order in orders: admin_user_obj = MyUser.objects.get(id=order.belongs) if order.time_created + timezone.timedelta(minutes=admin_user_obj.booking_time) < timezone.now(): send_order_canceled(order) bot_user = Bot_user.objects.get(belongs=order.belongs, chat_id=order.chat_id) if order.balance_to_return: bot_user.balance += order.balance_to_return bot_user.active_orders -= 1 bot_user.save() try: item = Item.objects.get(id=order.item) if item.strings == '': item.strings = '\r\n'.join(order.strings.split('\n')) else: item.strings = '\r\n'.join((order.strings.replace('\n', '\r\n') + '\r\n' + item.strings).split('\r\n')) item.quantity = len(item.strings.split('\r\n')) item.save() order.delete() except: pass time.sleep(10) docker-compose.prod premium_daemon: build: ./app command: python manage.py premium_daemon volumes: - ./app/:/usr/src/app/ env_file: - ./.env.prod depends_on: - db My htop after 20 mins runing docker: htop As you can see, I have 2400 threads premium_daemon.py How did it works? Why python not cleaning threads? How they create, I don't using threads. How can I clean threads? -
How can I get the full url of the image in DRF?
I am not good at English. I hope you understand. There can be multiple images in the diary. Diary and DiaryImage are in a 1:N relationship. this is my model from django.db import models from userSystem.models import User class Diary(models.Model): id = models.BigAutoField(primary_key=True) user = models.ForeignKey(User, related_name="diary_user", on_delete=models.CASCADE, null=True) title = models.CharField(max_length=30) content = models.CharField(max_length=800) date_created = models.DateField(auto_now_add=True) class DiaryImage(models.Model): diary = models.ForeignKey(Diary, on_delete=models.CASCADE) image = models.ImageField(default='/media/diary/default_image.jpeg', upload_to='diary', blank=True, null=True) this is my serializer from rest_framework import serializers from diary.models import DiaryImage, Diary class DiaryImageSerializer(serializers.ModelSerializer): image = serializers.ImageField(use_url=True) class Meta: model = DiaryImage fields = ['image'] class DiarySerializer(serializers.ModelSerializer): images = serializers.SerializerMethodField() def get_images(self, obj): image = obj.diaryimage_set.all() return DiaryImageSerializer(instance=image, many=True).data class Meta: model = Diary fields = ['id', 'title', 'content', 'date_created', 'images'] def create(self, validated_data): instance = Diary.objects.create(**validated_data) image_set = self.context['request'].FILES for image_data in image_set.getlist('image'): DiaryImage.objects.create(diary=instance, image=image_data) return instance this is my view from diary.serializers import DiarySerializer class DiaryViewSet(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated, ] serializer_class = DiarySerializer def get_queryset(self): return self.request.user.diary_user.all() settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py diary_list = DiaryViewSet.as_view({"get": "list", "post": "create"}) urlpatterns = [ path('admin/', admin.site.urls), path('diary/', diary_list, name="diary-list"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) When I ran this code, the image was saved successfully. However, when loading … -
How to add the source IP in Django Logger in settings.py?
I have the following logger configuration in my settings.py file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '[{asctime}] {message}', 'datefmt' : '%Y-%m-%d %H:%M:%S', 'style': '{', }, }, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': '/home/user/server.log', 'formatter':'simple', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, } It is giving me the logs in the following format. [2021-03-31 13:01:48] Watching for file changes with StatReloader [2021-03-31 13:01:50] "GET / HTTP/1.1" 200 20 However, I also want to get the source IP for HTTP requests like this: [2021-03-31 13:01:48] Watching for file changes with StatReloader [2021-03-31 13:01:50] Source IP : 112.73.20.208 | "GET / HTTP/1.1" 200 20 How can I achieve this? NOTE : I did come across a post regarding something similar but it's not clear, too old and seems abandoned as the comments don't have any response. -
How can i load images in django template with asynchronous system?
I was trying to make asynchronous system in django. I've used Channels for this purpose, and i was trying to send the image url to my template and display the image on the template page. But it didn't work. Here is my settings.py file STATIC_URL = '/static/' import os STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Here is how i send the data from the database. class WSConsumer(WebsocketConsumer): def connect(self): self.accept() x = Student.objects.filter(id=1) self.send(json.dumps({ 'name':x[0].name, "img":x[0].image.url, })) index.html file {% load static %} <!DOCTYPE html> <html> <head> <title>Index</title> </head> <body> <div id='img'></div> <script> var socket = new WebSocket('ws://localhost:8000/ws/some_url/'); socket.onmessage = function(event) { var data = JSON.parse(event.data); console.log(data); var url = data.img var el = document.getElementById("img"); el.innerHTML=`<img src= ${url}>`; } </script> </body> All the asynchronous system works perfectly.The js is already getting the image but it's not displaying the image but the other data. -
How to convert currency in Django?
I have to make conversions between currencies in my Django project. This app has multiple customers and every customer has credit_limit field. Every customer's credit limit amount can be in a different currency and I have to convert all of them to the USD. Because I have a dashboard page and I display some charts with doing operations with these currencies like adding etc... I used django-money and works fine, but it returns Money field and I cannot display it in charts because it is not a float or int field. How can I convert my currencies and return integer of float values? Thanks for any helping. Here are my codes: views.py def customer(request): form_class = NewCustomerForm current_user = request.user userP = UserProfile.objects.get_or_create(username=current_user) company = userP[0].company if request.method == 'POST': form = NewCustomerForm(request.POST) if form.is_valid(): newCustomer = form.save() newCustomer.company = company selected_currency = newCustomer.currency_choice selected_limit = newCustomer.credit_limit newCustomer.usd_credit_limit = convert_money(Money(selected_limit, selected_currency), 'USD') newCustomer.save() return redirect('user:customer_list') else: form = form_class() return render(request, 'customer.html', {'form': form}) models.py class Customer(models.Model): ... CURRENCIES = [ ('USD', 'USD'), ('EUR', 'EUR'), ('GBP', 'GBP'), ] currency_choice = models.TextField(max_length=50, default='Select', choices=CURRENCIES) credit_limit = models.FloatField(default=0, null=True) usd_credit_limit = MoneyField(max_digits=14, decimal_places=2, default_currency='USD', null=True, default=0) risk_rating = models.CharField(max_length=50, default='Select', choices=RISK_RATING, null=True) -
django uuid or hashid field for primary keys? and how to prefix the generated ids with say "cust_"
I am currently using django-shortuuidfield to generate a unique UUID primary key on the Customer model as shown below class Customer(models.Model): customer_id = ShortUUIDField() user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255, blank=False) This guarantees that the customer_id field is unique with space and time. However, this generates an id similar to B9fcKdMDHbwKCBoADjbNyA and I want to prefix this with cust_ to make it like this cust_B9fcKdMDHbwKCBoADjbNyA. How do I achieve this without making multiple db calls? I also looked into django-hashid-field which supports prefixes out of the box but this does not guarantee UUID, and on a larger scale, we may run into unique contain failed issues that are not desirable. Any thoughts on this? Let me know... -
How to fix "Key (username)=() already exists." error
I want to create a user with type 'learner'using mobile nummber,when i am trying to do this there is an error, django.db.utils.IntegrityError: duplicate key value violates unique constraint "user_user_username_key" DETAIL: Key (username)=() already exists. views.py class Register(APIView): def get_permissions(self): return (AllowAny(),) def post(self, request, *args, **kwargs): mobile = request.data.get('mobile') if mobile: data = {'mobile': mobile} serializer = RegisterSerializer(data=data) if serializer.is_valid(raise_exception = True): serializer.save() return Response('sucess') else: return Response('error') serializers.py class RegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('mobile',) def create(self, validated_data): user_data = validated_data.pop('user') user_data['user_type'] = 'learner' user_serializer = UserSerializer(data=user_data) user_serializer.is_valid(raise_exception=True) user = user_serializer.save() user.groups.add(validated_data['group']) user.save() return user instance = self.Meta.model(**validated_data) instance.user = user instance.save() return instance -
How to display a pickled set in Django admin interface?
I have a model, which has a BinaryField, which I use to store a short set of strings. It might not look like the most elegant solution, but it's what I have to work with for now: class Player(models.Model): player_id = models.CharField(max_length=32, primary_key=True) _awards = models.BinaryField(null=True) def set_awards(self, data): self._awards = pickle.dumps(data) def get_awards(self): return pickle.loads(self._awards) The field works fine, I just want to display that _awards set in the admin interface. I tried this, but it didn't work: class PlayerAdmin(admin.ModelAdmin): list_display = ('player_id') readonly_fields = ('_awards') def _awards(self): return self.get_awards() Instead of a list, I get this in the admin interface: <memory at 0x105a81040> -
Is there a way to display a html page both in another page and with its own URL?
I am working on a web app to display details on electronics boards based on a database. I have two ways of displaying results to a search : The first way is to click on a board and it makes you go on the detail page (so this page has its own URL an I can pass it to somebody else) The second way is to compare multiple boards and the details are shown on the same page (just under the boards I selected to compare) Both ways display the same html page called "details.html" Here is my problem : To make the first way work, I used {% extends "base.html" %} and I created a block in the latter so I still have all the menus (that are in "base.html" file) the available in the details page. first way However, to make the second way work, I would like to put the html of "details.html" in a div so that it is displayed on the same page. But, because of the {% extends ...%}, all the menus from "base.html" are also displayed... (which seems logical because I made it so it is displayed for the first way to work.) … -
How to perform inner Join To get customer from Common City In Django ORM?
I have following table. Salesman salesman_id | name | city | commission -------------+------------+----------+------------ 5001 | James Hoog | New York | 0.15 5002 | Nail Knite | Paris | 0.13 5005 | Pit Alex | London | 0.11 5006 | Mc Lyon | Paris | 0.14 5007 | Paul Adam | Rome | 0.13 5003 | Lauson Hen | San Jose | 0.12 And another table named Customer. customer_id | cust_name | city | grade | salesman_id -------------+----------------+------------+-------+------------- 3002 | Nick Rimando | New York | 100 | 5001 3007 | Brad Davis | New York | 200 | 5001 3005 | Graham Zusi | California | 200 | 5002 3008 | Julian Green | London | 300 | 5002 3004 | Fabian Johnson | Paris | 300 | 5006 3009 | Geoff Cameron | Berlin | 100 | 5003 3003 | Jozy Altidor | Moscow | 200 | 5007 3001 | Brad Guzan | London | | 5005 I want to get salesman name, customer name and their cities for the salesmen and customer who belongs to the same city. I can write this query in SQL but I am not been able to hook up with ORM. SELECT … -
how to implement two user types (seller and customer or buyer) using django allauth like fiverr?
I am working on a web e-commerce project where there will be two types of user (seller, customer).I have been wondering how to implement the logic like fiverr seller and buyer. I have created a user account with two flags yet (is_seller, is_customer). class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=254, blank=True) customer = models.ForeignKey('Customer', on_delete=models.CASCADE) is_seller = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() I don't know if it is the good approach. what will be the best approach to this kind of scenario? kindly Someone guide me. Any help will be appreciated. -
heroku ps:scale web=1 on django gives errors
An am new to python and django trying to assign a dyno to my app on heruko using Django and i keep getting this "error: Missing required flag: -a, --app APP to run command". That's any time i type "heroku ps:scale web =1. I will really appreciate some help. Thanks -
Not able to return a query inside a get function in DRF. Please have a look and reply
I have to insert distance as an input parameter and work on this code. But I'm not able to return the query. When I run, the program is asking for distance. { "distance": [ "This field is required." ] } My code is as follows: from django.contrib.gis.geos import Point from django.contrib.gis.measure import D from Admin_Section.models import Distance class ServiceProviderList(generics.ListAPIView): serializer_class=ProfilecompletioneSerializer filterset_class=SnippetFilter filter_backends = [DjangoFilterBackend,SearchFilter,OrderingFilter] filterset_fields = ['fullname', 'category','departments','services'] search_fields = ['fullname', 'category__name','departments__dept_name','services__service_name'] def get_queryset(self,*args, **kwargs): pk=self.kwargs.get('pk') qs = CustomerProfile.objects.filter(user=pk) if qs.exists(): customer = qs.first() else: return qs.none() def get(self,request,*args, **kwargs): pk=self.kwargs.get('pk') customer = CustomerProfile.objects.get(user=pk) serializer = DistanceSerializer(data=request.data) serializer.is_valid(raise_exception=True) Dist = serializer.validated_data['distance'] print(Dist) rad=float(Dist) radius=rad/111 print(radius) query = ProfileCompletion.objects.filter(location__distance_lte=(customer.location,radius)) return query -
How to calculate mean value with respect to the month in DRF
I am trying to get the average with respect to the months of data in DRF. I have two problems here my values in the string so I need to convert first into double and then calculate it. I am not able to think any solution that's why posting the question without my solution what I have tried. My modal class is: class FeedDataValues(models.Model): sensor = models.ForeignKey( 'core.SensorDevice', on_delete=models.SET_NULL, null=True ) hardware_id = models.CharField(max_length=255) field1 = models.CharField(max_length=255, null=True) field2 = models.CharField(max_length=255, null=True) field3 = models.CharField(max_length=255, null=True) received_at = models.DateTimeField(null=True) My serializer class is: class MQTTFeedDataSerializer(serializers.ModelSerializer): class Meta: model = models.FeedDataValues fields = ('id','sensor','hardware_id','field1','field2','received_at',) And views is: class MQTTFeedDataListView(generics.ListAPIView): authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated, permissions.IsAdminUser,) serializer_class = serializers.MQTTFeedDataSerializer queryset = models.FeedDataValues.objects.all() filter_backends = (DjangoFilterBackend, OrderingFilter,) filter_class = filters.MQTTFeedValuesFilter Any suggestion will be of great help. -
When to call gettoken, refresh token and verify token by user in jwt in DRF?
I have been using built in token authentication for my projects in Django rest framework. But now I am shifting to simple jwt. But I am confused on one thing. In Token Authentication user if logged in from front end returns a token, but in jwt documentation I have seen three requests as follows: urlpatterns = [ url(r'^auth-jwt/', obtain_jwt_token), url(r'^auth-jwt-refresh/', refresh_jwt_token), url(r'^auth-jwt-verify/', verify_jwt_token), ] I dont quite understand these requests. As a norman user, when a user visits a site he doest ask to get token, refresh token and verify token, he simply logs in and uses the features of the site. So, I am asking when these requests are made?? I hope I have explained well. -
How to add today's date to django templates
I researched how I could pass in a datetime object to my templates, but none of them seems to work. Here is the code for my view: class LeadListView(LoginRequiredMixin, generic.ListView): # some other code today_date = datetime.date.today() def get_context_data(self, **kwargs): context = super(LeadListView, self).get_context_data(**kwargs) context['today_date'] = self.today_date return context However, when I try to use the today_date in the template, it doesn't work. I am trying to use the today_date so that I might use it in an if statement to see if today's date is between two other datetime variables. Thanks a lot! -
Deleting the objects from Django table is not working
On a button click i want to delete an object from django database table. when i press delete button the desired object is gone. But when i refresh the page, the data is again loaded. How can i solve that error. I want to delete that object forever. Here is my code: models.py class activities(models.Model): name=models.TextField(max_length=60) description=models.TextField() date=models.TextField(max_length=60) list=models.TextField(max_length=60) Dates=models.DateField(max_length=60) root=models.ForeignKey(User ,on_delete=models.CASCADE,default='') def __str__(self): return self.name views.py: def dashboards(request): if request.method =='POST': user_id=request.POST.get('var') a = activities.objects.filter( id=user_id) a.delete() try: response = dashboard(request) except: return render(request,'contact.html') Any help is deeply appreciated. Thanks in advance -
Customized form for registration in django not working : meta tagged model shows no error, but not working
I'm trying to bootstrapify my customized registration page and fix my meta tag Things i've tried: I've altered the form in forms.py and added the extra fields When I remove the meta tag from my form, it has no effect at all, so I'm assuming something's wrong around there but I can't figure out what I'm using the inbuilt Django user model, and I've gone through many questions related to it without finding the solution. Any help would be highly appreciated !!! Note: An important thing is, even though I've mentioned a different order in the meta tag, it doesn't reflect the tag order in the html page Also my code shows me no errors Here's my forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class SignUpForm(UserCreationForm): email = forms.EmailField(widget = forms.EmailInput(attrs={'class' : 'form-control'}) ) first_name = forms.CharField(max_length=100, widget = forms.TextInput(attrs={'class': 'form- control'})) last_name = forms.CharField(max_length=100, widget = forms.TextInput(attrs={'class': 'form- control'})) class Meta: model = User fields = ('username', 'password1', 'password2', 'first_name', 'last_name', 'email') def __init__(self, *args, **kwargs): super(SignUpForm,self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] : 'form-control' self.fields['password1'].widget.attrs['class'] : 'form-control' self.fields['password2'].widget.attrs['class'] : 'form-control' Here's my views.py from django.shortcuts import render from django.views import generic from django.contrib.auth.forms import UserCreationForm from … -
HTTP 403 Forbidden in django-rest-framework
@api_view(['POST', 'GET']) def buyInstituteTutorialAPI(request,id): if request.session['type'] == "Student": user = User.objects.get(username=request.user) student = Student.objects.get(user=user) tutorial = TutorialInstitute.objects.get(id=id) if request.method == "GET": data = [] data['student'] = student.id data['tutorial'] = tutorial.id data['status'] = 1 if int(tutorial.Fees) == 0: buyData = BuyInstituteTutorialSerializer(data=data) if buyData.is_valid(): buyData.save() data['success'] = "Notes Bought Successfully!" else: data['error'] = "something error!" return redirect('view-tutorial-tutor-api') else: return Response(data) is that wrong method to send data in the serializer i'm logged with student but still shows this.... o/p: You do not have permission to perform this action -
Creating an object in django
I have just started learning Django and I am making a database using SQLite I have a python file called models.py and I am currently creating a py file for the objects called object. However I am having trouble creating objects in the database I have made. I think there is an issue with the object.py file because it is claiming that my FruitInfo sections have no objects. models.py from django.db import models from django.core.validators import MinLengthValidator, MaxValueValidator, MinValueValidator class FruitInfo(models.Model): id = models.IntegerField(primary_key=True, max_length=30, validators=[MinLengthValidator("5")]) name= models.CharField(max_length=30) origin = models.CharField(max_length=60) price = models.DecimalField(max_digits=4,null=False,decimal_places=2, validators=[MinValueValidator('200')]) def __str__(self): return self.origin + " " + self.name object.py from stinky.models import FruitInfo FruitInfo.objects.all() FruitInfor.objects.all().values() record = FruitInfo.objects.create(id = "A0001", name = "Pink Lady Apple", origin= "Washington State", price="$2.00/kg" ) record = FruitInfo.objects.create(id = "A0002", name = "Organic Bananana", origin = "Australia", price = "$4.50/kg") record = FruitInfo.objects.create(id = "A0003", name = "Orange", origin = "Indonesia", price = "$4/kg") record.save() -
How to resend a cognito invite
i need to resend cognito invite to users when the previously sent token expires in the documentation it's written like this --message-action (string) Set to "RESEND" to resend the invitation message to a user that already exists and reset the expiration limit on the user's account. Set to "SUPPRESS" to suppress sending the message. Only one value can be specified. Possible values: RESEND SUPPRESS -
Django Query select from where in
i need to write a query in django that creates a table with instructors name, department name, and total number of students taught. the part thats giving me trouble is the student count, i think i have the mysql query: select count (distinct ID) from takes where (course_id, sec_id, semester, year) in (select course_id, sec_id, semester, year from teaches where teaches.ID= Instructor.ID); or select count (distinct t1.ID) from takes as t1 inner join teaches as t2 on t1.course_id=t2.course_id and t1.sec_id=t2.sec_id and t1.semester=t2.semester and t1.year=t2.year where t2.ID= Instructor.ID my models are: class Takes(models.Model): id = models.ForeignKey(Student, models.DO_NOTHING, db_column='id', primary_key=True,) course = models.ForeignKey(Section, models.DO_NOTHING, related_name='+') sec = models.ForeignKey(Section, models.DO_NOTHING, related_name='+') semester = models.ForeignKey(Section, models.DO_NOTHING, db_column='semester', related_name='+') year = models.ForeignKey(Section, models.DO_NOTHING, db_column='year') grade = models.CharField(max_length=3, blank=True, null=True) class Meta: managed = False db_table = 'takes' unique_together = (('id', 'course', 'sec', 'semester', 'year'),) def __str__(self): return self.id class Teaches(models.Model): course = models.ForeignKey(Section, models.DO_NOTHING) sec = models.ForeignKey(Section, models.DO_NOTHING, related_name='+') semester = models.ForeignKey(Section, models.DO_NOTHING, db_column='semester', related_name='+') year = models.ForeignKey(Section, models.DO_NOTHING, db_column='year', related_name='+') id = models.ForeignKey(Instructor, models.DO_NOTHING, db_column='id', primary_key=True,) class Meta: managed = False db_table = 'teaches' unique_together = (('id', 'course', 'sec', 'semester', 'year'),) class Section(models.Model): course = models.ForeignKey(Course, models.DO_NOTHING) sec_id = models.CharField(max_length=8) semester = models.CharField(max_length=6) year … -
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS. HTTPS Websocket wss://
I am writing a website with 2 Django apps. A chat room and a Quiz website. used docker for the webSocket server: docker run -p 6379:6379 -d redis:5 I was using Channels and the app worked fine at https with (ws://) webSocket. But the client cant connect to the webSocket when i changed the link to wss://. Now i am trying to start the server using Daphne. But this has this error: daphne -p 8000 flippingClassroom.asgi:application django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. File tree: my-project chat templates index.html room.html admin.py consumers.py models.py routing.py urls.py views.py flippingClassroom asgi.py settings.py urls.py wsgi.py main ...another app chat/routing.py from django.urls import re_path from .consumers import ChatConsumer websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>[^/]+)/$', ChatConsumer.as_asgi()), ] chat/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<str:room_name>/', views.room, name='room'), ] chat/views.py from django.shortcuts import render # Create your views here. def index(request): return render(request, 'chat/index.html') def room(request, room_name): return render(request, 'chat/room.html', { 'room_name': room_name, 'username': request.user.username }) flippingClassroom/asgi.py import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import chat.routing os.environ.setdefault("DJANGO_SETTINGS_MODULE", … -
AttributeError: 'function' object has no attribute 'get_extra_actions' in function view
views.py @api_view(['GET', 'POST']) def poll(request): if request.method == "GET": question = Question.objects.all() serializer = QuestionSerializer(question, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == "POST": data = JsonParser.parse(request.POST) serializer = QuestionSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) api_urls.py from django.contrib import admin from django.urls import path, include from . import views from rest_framework import routers router = routers.DefaultRouter() router.register(r'poll', views.poll, basename='poll') urlpatterns = [ path('poll/', include(router.urls)), ] error File "C:\Users\azhar\.virtualenvs\Django_and_Rest-YRrszWnq\lib\site-packages\rest_framework\routers.py", line 152, in get_routes extra_actions = viewset.get_extra_actions() AttributeError: 'function' object has no attribute 'get_extra_actions' many solution available for how to use get_extra_actions in class View but I want to use it in poll function please help me out -
What is the best way to generate a primary key for a table from two strings?
Basically I'm trying to make my Django + PostgreSQL database perform better. Say I have a table with first_name, last_name, state, address. For whatever reason I want first_name and last_name together to make my primary key. Doesn't have to make sense, it's just an example. At first I used zlib.adler32() to generate a hash from the two strings and put it into a BigIntegerField and use that as my primary key, but I quickly discovered that the purpose of this function is totally different and I was getting collisions pretty quickly. Currently I'm using hashlib.md5() to generate a hash into a 32 character CharField and use it as my primary key: hashlib.md5(bytes(f'{first_name}{last_name}', encoding='utf-8')).digest().hex() However things slowed down a lot. I don't know if it's because of the md5 algorithm, or because of the table having a string for primary key instead of an integer. I know there is another option - unique_together value of the Meta class, but I've been trying to avoid any Django conveniences for performance reasons. How would you recommend to make a primary key? I'm looking for performance, doesn't need to be human readable. If BigInteger is much faster as a primary key, how do I …