Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Channels - Websocket connection failed
I am currently trying to setup my Django Channels chat app, and I have followed the Docs to the best of my understanding - Obviously when something doesn't go right, there's always a solution, but I am just having difficulties working out where I've gone wrong with getting this to work. So far I have installed Django Channels, correctly configured my channel_layer within settings.py, I have referenced the docs and other online tutorials with creating my consumer.py file, utils.py, views.py and chat.html template file. I have also configured daphne and redis and I can confirm that both of these services are running. I have installed LetsEncrypt and have allowed the SSL port (443 for https connections). I am currently accessing my Django website on a live production server like this: https://:8001 and the direct link to my chat is configured as https://mydomain:8001/messenger Here are the status messages I am getting from the chat page: SUCCESS {response: "Successfully got the chat.", chatroom_id: 1}chatroom_id: 1response: "Successfully got the chat."__proto__: Object (index):303 setupWebSocket: 1 (index):371 ChatSocket connecting.. WebSocket connection to 'wss://www.<mydomain>.com:8001/messenger/1/' failed: setupWebSocket @ (index):317 success @ (index):389 c @ jquery.min.js fireWith @ jquery.min.js l @ jquery.min.js (anonymous) @ jquery.min.js ChatSocket error Event … -
How to filter against subclass's fields with Django InheritanceManager?
I am using InheritanceManager from django-model-utils library. Is there a way to filter against fields of a subclass? Something like this: from model_utils.managers import InheritanceManager class A(models.Model): objects = InheritanceManager() class B(A): flag = models.BooleanField() A.objects.select_subclasses().filter(flag=True) -
context_object_name doesnt work on CreateView (Django 2.2)
how are you? i have an issue. My form doesn't render on the html if i change the context_object_name from 'form' to 'recent_works' (only for my order). here is the code: models.py: class clientes_rfi(models.Model): fondo = models.TextField(null=True,blank=True) nombre_cliente = models.TextField(unique=True,null=True,blank=True) categoria = models.TextField(null=True,blank=True) pais = models.CharField(max_length=3,null=True,blank=True) activo = models.BooleanField(default=True,null=True,blank=True) prospecto = models.BooleanField(default=False,null=True,blank=True) trader_contraparte = models.TextField(null=True,blank=True) final = models.BooleanField(null=True,blank=True,default='t') views.py class CrearClienteCreateView(CreateView): context_object_name = 'recent_works' model = clientes_rfi template_name = "ordenes/ordenes-listar-clientes.html" fields = ['fondo','final','categoria','pais'] ordenes/ordenes-listar-clientes.html {% include 'index.html' %} {% block contenido %} <div class="container"> <div class="h1">Ingreso de trabajos nuevos</div> <form method="post">{% csrf_token %} {{ recent_works }} <input type="submit" value="Guardar"> </form> {% endblock contenido %} the render <form method="post"><input type="hidden" name="csrfmiddlewaretoken" value="lmq7NwolBOSGIy5vnIt8y3fZIUSdSPoC5icnHiNGFOgvWHAo"> <input type="submit" value="Guardar"> </form> Thanks in advance -
Foreign Key IntegrityError at /new_project null value in column "project_id" violates not-null constraint
I know this is probably a duplicate but I've tried every solution on other problems of this nature and I can't seem to solve this, here's my issue. Models class Project(models.Model): project_name = models.CharField(max_length=50) project_url = models.URLField() last_update = models.DateField(default=timezone.now) def __str__(self): return self.project_name class Commit(models.Model): project = models.ForeignKey(Project, on_delete = models.CASCADE, verbose_name="project") commit_id = models.CharField(max_length=40) author = models.CharField(max_length=200) date = models.DateTimeField(default=timezone.now) commit_msg = models.TextField() commit_info = models.TextField() regex_tags = models.TextField(null=True) def __str__(self): return self.commit_id + " - " + self.author + " - " I have these models and I need every commit to be associated with the project they come from. In my view, I do this: class new_project_view(View): def get(self, request): return render(request, 'new_project.html') def post(self,request): if 'create_project' in request.POST: project_name = request.POST['projectname'] project_url = request.POST['projecturl'] print("project url ", project_url) print("project name", project_name) generate_log_file(project_url) logfile = open("logfile.txt", "r") if not logfile.readlines() : print("Estou vazio") logfile.close() return render(request, 'new_project.html') else: print("Add log to DB") logfile.close() #Here I create the project model and send it to a function #that adds to the commits. project = Project.objects.create() project.project_name = project_name project.project_url = project_url project.save() add_log_to_db(project) print("Added") return render(request, 'new_project.html') The add_log_to_db function does a lot but it's working as intended … -
How to embed an HTML table from another domains webpage into my own using Python with Django framework via the backend?
I am trying to embed the HTML table from another domains webpage into my own. Obviously this is not possible using JavaScript via the front-end because of cross-origin policy. I saw a few suggestions to use the back-end, in my case Python on top of Django framework, to fetch the page and render it to the front-end so that it appears to be on the same domain and then use jQuery to extract only the element I am looking for. However, none of these suggestions really provided any working code that I could try and follow. I am a bit confused as to how to render an external domains webpage to my front-end using Django framework ? PS. The table in question does not have an id so I would need to use some sort of CSS selector to extract it. Ideally, I would like to keep the styling of the table the same as it is on the other site. Yes, I have permission to embed the table and I do reference the original site. Yes, I have tried an iFrame but I don't want the entire webpage and prefer not to "hack" the CSS. -
how do i store all loop variables in dictionary of python to use in django
PYTHON import requests import re import os import csv from bs4 import BeautifulSoup headers = { 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36', } searche=['note 8 pro','note 9 pro','boat','realme','poco'] for d in searche: truelink = d.replace(" ","-") truelinkk=('https://www.olx.in/hyderabad_g4058526/q-'+truelink+'?isSearchCall=true') r = requests.get(truelinkk,headers=headers).text soup=BeautifulSoup(r,'lxml') mobile=soup.find_all('li',class_='EIR5N') for note9maxpro in mobile: mobi= note9maxpro.find('span',class_='_2tW1I').text price= note9maxpro.find('span',class_='_89yzn').text date= note9maxpro.find('span',class_='zLvFQ').text link=note9maxpro.a.get('href') orglink='https://www.olx.in'+link price = price.replace("₹ ","") how to store all loop variables in dictionary of python to use in django later i want to use this data in django as. please give me solution to reduce lines of my code as well Thanks in advance for i in data: i.mobi i.price i.date -
is there anyway to use python for frontend development?
I am trying to find a way to develop a frontend using python As I don’t want to use any kind of javascript in my website, I am a Django developer from last 2 years but being a Django developer I feel that after learning python a lot we have to learn javascript too for the frontend, and I think this feels to the whole Django community that at the end of the day, they have to face JavaScript (by their will or forcibly). So, I want the whole community to spend some time to think and please let not down Python Developers to face JavaScript after learning a lot in Python. In my opinion, there should be a full-fledged frontend framework in Python -
How to select a declared variable from a script tag with JavaScript
Could you please help me? I have the four below declared variable inside a script tag ( in a html page. They are radomly generated by folium in python.I would like to select the last one from another js file without success. I tried this window.onload = function() { for (var name in this){ if(Object.keys({name})[0].includes("layer"){ alert (name) } } }; Here are the declared variables inside the script tag in the html page var circle_f3a483b3a7ba46748ac935d3995f4f6b = L.circle( [-16.0, 0.0] ).addTo(feature_group_1c28eff59e394734be54cf676a09eae1); var circle_a01d1791063145b18b439bd7687bc97f = L.circle( [-11.3137, 11.3137], ).addTo(feature_group_1c28eff59e394734be54cf676a09eae1); var layer_control_aec3ac6e0e424b74a19b4c9d1c78ffeb = { base_layers : { }, overlays : { "Roads" : geo_json_cae0ea33c63e4c438678d293e5c32c0d, "Intersections" : feature_group_1c28eff59e394734be54cf676a09eae1, }, }; -
How to replicate django authentication in several services
we have a web app using Django. We have the authentication system setup as described below. Now, we would like to take some part of the application to an independent service, but we would like to have the same valid token/authentication system. The new service will be using Django too, probably, so I would like to know if this is even possible or what options do I have to implement this behavior. In the case that we do not use Django in the new service, there would be a way to still use the same logic to authenticate requests on the two services? Authentication system Right now, we are authenticating the requests using the rest_framework module, more precisely, the TokenAuthentication class. This is the configuration: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', ... 'rest_framework', 'rest_framework.authtoken', ... } REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated' ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'module.authentications.AuthorizedAuthentication', ) } And the code we use to authorize the requests: import logging from rest_framework.authentication import TokenAuthentication from rest_framework.exceptions import AuthenticationFailed class AuthorizedAuthentication(TokenAuthentication): _logger = logging.getLogger(__name__) def authenticate(self, request): response = TokenAuthentication.authenticate(self, request) if response is None: return None return response To authenticate in the views, we do something like this: from rest_framework.permissions import … -
Limit number of objects of a self reference model with Prefetch Django
I have 2 models: Post and Comment. Like this: class Post(models.Model): content = models.TextField() class Comment(models.Model) content = models.TextField() owner = models.ForeignKey(User, null=False, on_delete=models.CASCADE) post_parent = models.ForeignKey( Post, on_delete=models.CASCADE, null=False, db_column='post_parent', related_name='comments', ) comment_ref = models.ForeignKey( 'self', on_delete=models.CASCADE, null=True, related_name='children_comment' ) Suppose that comments can have sub-comments in 1 level. With a post's ID, I want to get 5 newest comments (not sub-comment), each of them is prefetched with their 3 newest sub-comments. My current implementation after searching is: sub_comments = Comment.objects.filter( comment_ref=OuterRef('pk'), post_parent=post_id ).order_by('-timestamp').values_list('id', flat=True)[:3] queryset = Comment.objects.filter( comment_ref=None,post_parent=post_id ).select_related('owner').prefetch_related( Prefetch('children_comment', queryset=Comment.objects.filter( id__in=Subquery(sub_comments) ), to_attr="cmt")) That does not work. It doesn't limit the number of prefetched sub-comments. Please help me :D -
Loading font in django templates
The structure of folders is as follow: --project |--myapp |--static |--fonts |--abs.ttf | |--templates |--report.html I load static files to report.html as follow: <!DOCTYPE html> <html> <head> <title> My Title</title> {% load static %} {% block style_base %} {% block layout_style %} <style type="text/css"> @font-face { font-family: 'abc'; src: url({% static 'fonts/abc.ttf' %}); {# src: url('file:///home/project/myapp/static/fonts/abc.ttf'); #} } ... When import font using url('file:///home/project/myapp/static/fonts/abc.ttf'); it's work fine but using url({% static 'fonts/abc.ttf' %}); doesn't work. settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Also I added urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)' to the urls.py` but no result found. Can anyone tell me where the problem is? -
Can't run compress in django app deployed with heroku
I am trying to deploy a Django 3.2.4 app on heroku, with django-compressor 2.4.1. I wanted heroku to compress the files, so I ignored my local compress directory and added a post-compile file, as specified here. Here is the build log Compressing static files Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: ... other stuff File "/app/.heroku/python/lib/python3.9/site-packages/django/template/backends/django.py", line 123, in get_package_libraries raise InvalidTemplateLibrary( django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'compressor.templatetags.private_static': cannot import name 'PrivateFileSystemFinder' from 'compressor.finders' (/app/.heroku/python/lib/python3.9/site-packages/compressor/finders.py) ! Push rejected, failed to compile Python app. ! Push failed I followed the steps for setting up django-compressor as per the docs. -
Applying filter to queryset only when query is provided in Django
Let's say I have a model called Article with the field title. I have a method that returns a queryset for this model, and the method takes an optional argument called query which if provided, is used to filter out the queryset. So something like this: def get_articles(query=None): if query: return Article.objects.filter(title__icontains=query) else: return Article.objects.all() This works fine, but notice how this method has two return statements, as in, I'm writing out two separate queries. Is there a way to do this in one go? In other words, the ideal scenario would be writing just one query instead of two. Thanks for any help. -
Is it possible to create my own domain email with django and Amazon SES?
I'm creating a site using Django and hosting it with Amazon EC2. My domain is managed by Namecheap, and they charge for email forwarding. I was thinking if there's a way to create a mailbox inside the django project, in order to validate an email that uses my own domain so I can forward it without using Namecheap service. I found projects like Django-mailbox and Django-ses but they seem to only manage emails that already exists. Thank you -
Django slow query with a nullable Foreignkey
Imagine we have this two models class Offer(models.Model): fetch_datetime = models.DateTimeField(db_index=True) tracking = models.ForeignKey(Tracking, models.SET_NULL, blank=True, null=True) class Tracking(models.Model): MANUAL = "Manual" AUTO = "Auto" UNMATCHED = "Unmatched" MATCHING_TYPES = [(MANUAL, "Matched by a human"), (AUTO, "Matched by a computer"), (UNMATCHED, "Not matched")] matching_status = models.CharField(max_length=10, choices=MATCHING_TYPES, default=UNMATCHED) And we want to query like this Offer.objects.filter(fetch_datetime__range=(now_minus_14days, now)) .select_related('tracking') .filter(tracking__matching_status__iexact="manual") .annotate( fetch_day=Cast("fetch_datetime", DateField()) ) When the query is executed with the default index that django creates on the field Offer.tracking the query is so slow. On the other hand, when we get rid of this index, the query is fast. I'm so confused. Anybody can give a solution? Thank's in advance -
How can I use CSS on form.ImageFiled in Django?
I would like to apply CSS to form.ImageFiled in Django same as Charfeild but I got the error. File "/Users/hogehoge/Desktop/hoge/hoge/forms.py", line 42, in PostForm photo = forms.ImageField(label='Image', validators=[file_size],widget=forms.ImageField(attrs={'class': 'fileinput'})) File "/Users/hoge/opt/anaconda3/lib/python3.8/site-packages/django/forms/fields.py", line 545, in __init__ super().__init__(**kwargs) TypeError: __init__() got an unexpected keyword argument 'attrs' How can I apply CSS CSS on form.ImageFiled? forms.py photo = forms.ImageField(label='Image', validators=[file_size],widget=forms.ImageField(attrs={'class': 'fileinput'})) html <div class="col-8 col-lg-4">{{ form.photo }}</div> -
Django Image Processing/Serving to improve page speed
I am building a site that has a piece of functionality that is pulling images from the Instagram API and they are being flagged up as the main issue in pagespeed insights. The site is here: http://demo.emmawedgwoodaesthetics.co.uk/ and the problematic page speed is here  If I hover on one of the images in devtools it shows me this:  Okay so my understanding is that the files size is too big and I need to serve a smaller file. Facebooks/Instagram Documentation is super bad and I cant find a way there to ask for a smaller image. My template has this: <div class="carousel ml-10p" x-ref="carousel"> {% for post in instafeed%} <div class="w-3/5 h-10v pr-5 "><img class="rounded-3xl shadow-xl w-40 h-40 " src="{{ post.media_url}}" alt=""></div> {% endfor %} </div> The w-40 h-40 are what is rendering the 160x160. So how do I solve this problem? I am thinking I need to use an image processing third party package? Do I need to? I am thinking the minimum requirement is take a set of image_urls from instagram(1440 x 1440) convert them to smaller images on the server and then serve those in the view. I have been looking at sorl-thumbnail, django-imagekit and … -
i keep on receiving ('NoneType' object has no attribute 'price') as an error in server
i keep on receiving the error ('NoneType' object has no attribute 'price') on my server and i have no idea how to remove it or what the problem is, i added a product in my admin and then i removed it in my admin but that item was in my cart so when i refreshed my cart i got that error in my server this is my models.py class Shoe(models.Model): brands = models.ForeignKey(Brands, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) price = models.DecimalField(max_digits=7, decimal_places=2) image_1 = models.ImageField(null=True, blank=True) class Cart(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.CASCADE) complete = models.BooleanField(default=False) date_ordered = models.DateTimeField(auto_now_add=True, null=True) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) @property def get_cart_total(self): cartitems = self.cartitem_set.all() total = sum([item.get_total for item in cartitems]) return total @property def get_cart_items(self): cartitems = self.cartitem_set.all() total = sum([item.quantity for item in cartitems]) return total @property def shipping(self): shipping = True cartitems = self.cartitem_set.all() return shipping, cartitems class CartItem(models.Model): shoe = models.ForeignKey(Shoe, on_delete=models.SET_NULL, blank=True, null=True) cart = models.ForeignKey(Cart, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True, null=True) @property def get_total(self): total = self.shoe.price * self.quantity return total -
a generic class for the creation, modification or deletion of objectsz in django
from django.contrib.auth.models import AbstractUser from django.db.models import Model class Repository(object): def init(self, model: Model or AbstractUser): self.model = Model def list(self): return self.model.objects.all() def retreive(self, _id: int): return self.model.objects.get(id=_id) def put(self, _id: int, data: dict): _object = self.model.objects.get(_id) if _object is None: return Exception('object not found') else: for i in data: if hasattr(_object, i) and getattr(_object, i) != data[i]: setattr(_object, i, data[i]) _object.save() return _object def create(self, data: dict): return self.model.objects.create(**data) def delete(self, _id): return self.model.objects.get(_id).delete() -
foreign key in django
I have a model for musics and a model for comment of musics: class music(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) STATUS_CHOICES = (('draft', 'Draft'), ('published', 'Published'),) music = models.FileField() music_image = models.ImageField(upload_to="images/") singer_name = models.CharField(max_length=100) music_name = models.CharField(max_length=100) text_of_music = models.TextField() create = models.DateField(auto_now_add=True, blank=True, null=True) update = models.DateField(auto_now=True, blank=True, null=True) publish = models.DateField(default=timezone.now, blank=True, null=True) slug = models.CharField(max_length=250, unique_for_date='publish') status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published = PublishedManager() class Meta: ordering = ('-publish',) def get_absolute_url(self): return reverse('music:music_detail', kwargs={"id":self.id}) class comment(models.Model): # Foreignkey for each music For = models.ForeignKey(music, on_delete=models.CASCADE, related_name='post') body = models.CharField(max_length=500) created_on = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) commented_by = models.ForeignKey(User, on_delete=models.CASCADE) and this is my view: def music_Detail(request, id=None): user = request.user template_name = 'music/music_detail.html' Music = music.objects.all().filter(id=id) new_comment = None Comment = comment.objects.all().filter(active=True) form = comment_form(data=request.POST) if request.method == 'POST': if form.is_valid(): new_comment = form.save(commit=False) new_comment.For = Music new_comment.save() form = comment_form() return render(request, template_name, {'Music': Music, 'Comment': Comment, 'form': form}) Well, I get this error when I comment: Cannot assign "<QuerySet [<music: m, majid kharatha>]>": "comment.For" must be a "music" instance. How can I solve this problem and how can I display the information of the user who left this comment? -
paypal user login page (page after clicking the paypal button) reloads indefinitely, after adding "&vault=true&intent=subscription"
I am integrating PayPal for subscription related service, I have earlier implemented for single time payment by adding the Paypal button via adding the script <script src="https://www.paypal.com/sdk/js?client-id=SB_CLIENT_ID"></script> but for subscription as per the documentation https://developer.paypal.com/docs/subscriptions/integrate/#subscriptions-with-smart-payment-buttons we are supposed to add &vault=true&intent=subscription also thus making it <script src="https://www.paypal.com/sdk/js?client id=SB_CLIENT_ID&vault=true&intent=subscription"></script> but after adding this I get the following error in the chrome console and the login page reloads indefinitely Failed to load resource: the server responded with a status of 400 (Bad Request) -
Can't updating an object from serializer DRF
I'm trying to update the balance each time that I create a transaction. so far I have tried this but it isn't working. What I'm trying is to check the type of transaction, 1 means is an income and 2 means that is an expense, next I get the object filtering from the user id that in the balance model filed is call user_id, to later add or take away to the amount the incoming data depending on the transaction type. Model class Balance(models.Model): balance = models.FloatField( verbose_name="Balance", blank=False, null=False) user_id = models.ForeignKey( 'expenseApi.Users', verbose_name="Usuario", blank=False, null=False, on_delete=models.PROTECT) def __str__(self): return '{}'.format(self.pk) serializer class TransactionsSerializer(serializers.ModelSerializer): user_id = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Transactions fields = ['type', 'user_id', 'description', 'amount', 'id'] def create(self, request, validated_data): user = self.context['request'].user balanceObj = Balance.objects.get(user_id=user) if self.context["view"].kwargs['type'] == 1: balanceObj.balance = F('balance') + self.context["view"].kwargs['amount'] balanceObj.save() if self.context["view"].kwargs['type'] == 2: balanceObj.balance = F('balance') - self.context["view"].kwargs['amount'] balanceObj.save() return super().create(**validated_data) The balance object is created when a user is created.And it is asing an amount of 0 class RegisterSerializer(serializers.ModelSerializer): tokens = serializers.SerializerMethodField() email = serializers.EmailField(max_length=50) balance = serializers.SerializerMethodField() class Meta: model = Users fields= ['id', 'email', 'password', 'name', 'lastname', 'birthday', 'tokens', 'balance'] extra_kwargs = { 'password': { 'write_only': … -
I am new to django and i am trying to make a get request to a path to list all the fields of a model but getting errors
My models.py from django.db import models # Create your models here. class LiveClass(models.Model): standard = models.IntegerField() no_of_students_registered = models.IntegerField(default=0) class Meta: verbose_name_plural = 'Class' class User_details(models.Model): name = models.CharField(max_length=30) standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE) email = models.EmailField(max_length=30) mobile_number = models.IntegerField() class Meta: verbose_name_plural = 'User_details' class Mentor(models.Model): name = models.CharField(max_length=30) standard = models.ManyToManyField(LiveClass) details = models.TextField() class Meta: verbose_name_plural = 'Mentors' class LiveClass_details(models.Model): standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE) chapter_name = models.CharField(max_length=30) chapter_details = models.TextField() mentor_name = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE) class_time = models.DateTimeField() class Meta: verbose_name_plural = 'LiveClass_details' class LiveClass_registration(models.Model): class_details = models.OneToOneField(LiveClass_details, on_delete=models.CASCADE) name = models.OneToOneField(User_details, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'LiveClass_registration' This is serializer for all my models , please tell a way to reduce the code in it as all of it is a repetition my Serializer.py from rest_framework import serializers from . import models class LiveClass_serializer(serializers.ModelSerializer): class Meta: model = models.LiveClass fields = '__all__' class User_details_serializer(serializers.ModelSerializer): class Meta: model = models.User_details fields = '__all__' class LiveClass_details_serializer(serializers.ModelSerializer): class Meta: model = models.LiveClass_details fields = '__all__' class Mentor_serializer(serializers.ModelSerializer): class Meta: model = models.Mentor fields = '__all__' class LiveClass_registration_serializer(serializers.ModelSerializer): class Meta: model = models.LiveClass_registration fields = '__all__' my urls.py from django.urls import path, include from . import views urlpatterns = [ path('liveclass/', … -
Django Create multiple views
I am new to django.I have to create multiple views and create buttons for them in the main page. I have to create different view for different filter of the table.My main page show 404 error and my app page only shows one view(the first one linked in urls.py). hereis my code: views.py from django_tables2 import SingleTableView from django.db.models import Max from django.db.models import Min from .models import airdata from .tables import AirdataTable class AirdataListView(SingleTableView): model = airdata table_class = AirdataTable template_name = 'dashboard/data.html' q = airdata.objects.aggregate(alpha=Min('pol_max'))['alpha'] queryset = airdata.objects.filter(pol_min= q).order_by('-state') class AirdataListView2(SingleTableView): model = airdata table_class = AirdataTable template_name = 'dashboard/data2.html' q = airdata.objects.aggregate(alpha=Max('pol_max'))['alpha'] queryset = airdata.objects.filter(pol_min= q).order_by('-state') urls.py from django.urls import path from . import views from .views import AirdataListView,AirdataListView2 urlpatterns = [ path('', AirdataListView2.as_view()), path('', AirdataListView.as_view()), ] template {% load render_table from django_tables2 %} <!doctype html> <html> <head> <title>Air Data</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> </head> <body> {% render_table table %} </body> </html> -
django and postgres what is the alternative to uuid
I want all of the ID fields of all model classes(tables) in my Django project to be unique. by unique I mean unique throughout all of the tables, not just one table. I don't wanna use UUID due to the performance and storage issues and actually I don't need my Id fields to be that kind of unique I just want them to be probably a 5 or 6 digit unique number in 30 tables. my database is Postgres. Why I need it: assume that there are 3 tables: news, article, and tag. I want to assign multiple tags to news or articles. so I store tag_id and news_id or article_id in another table called typetag. so news and articles can not have similar ids as the django auto-incrementing primary key generates. how would I tackle this problem?