Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to displaying an HTML table with pandas in another template using Django?
I would like to display a data table HTML in an specific template with Django, but I couldn't archive it successfully, am I missing sth important? views.py def dato(request): item = pd.DataFrame({'Nombre Proyecto': ['Cargador de Film', 'Planta de desarrollo','Envasadora'], 'Responsable Proyecto': ['Francisco Bruce','Daniel Nieto','Patricio Oyarzun'], 'Evaluador Proyecto': ['Equipo Austral Pack','Equipo Austral Pack','Equipo Austral Pack'], 'Descripción Proyecto': ['Carga films platicos para envase','Desarrolla Productos','Envasa Productos'] }) data =item.to_html(index=False) return render(request, 'dato.html', {'data': data}) dato.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> {% block content %} <h1>Dato</h1> {{data | safe}} {% endblock %} </body> </html> urls.py from django.urls import path from . import views urlpatterns = [ path("dato.html",views.dato, name="dato"), ] -
Is there any way to use url without writing anything in views?
I have made a model and have registered it. In the urls i have Path = ( r'^Api/', ) Is there a way to make this work without adding any views reference? -
the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I need to send an email in Django but I'm getting this error. What should I do? views.py def home(request): info = About.objects.first() # send email if request.method == 'POST': email = request.POST['email'] subject = request.POST['subject'] message = request.POST['message'] send_mail( subject, message, email, [settings.EMAIL_HOST_USER], ) print(message) print(subject) print(email) return render(request,'base/index.html', {'info': info}) settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = 'hamadakamal819@gmail.com' EMAIL_HOST_PASSWORD = 'qwtbjecezmvrxjfj' EMAIL_USE_TLS = True -
Rest Framework cant save serializer with foreign key
I have next serializers: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' class PostSerializer(serializers.ModelSerializer): category = CategorySerializer() class Meta: model = Post fields = ['id', 'title', 'text', 'date', 'category'] And here is my view: @api_view(['POST']) def create_post(request): serializer = PostSerializer(data=request.data) if serializer.is_valid(): serializer.save() else: return Response(serializer.errors) return Response(serializer.data) I want to create new Post object, but when I pass an category id at form it does not work, it is not saving my object. I tried to replace create method at my PostSerializer, to this: def create(self, validated_data): category_id = validated_data.pop('category') post = Post.objects.create(**validated_data, category=category_id) return post but this dont work. Using postman formdata it is saying, that category field is required despite I filled it. -
Error while running server in Wagtail CMS
This error happens when I add a banner title. Banner title I believe is the property in the class and it's being referenced as a string. Completely new to DJANGO & Wagtail CMS + only been coding/programming for the last eight months! Any help greatly appreciated (: Here is what my terminal says Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/Users/alessiolivolsi/.local/share/virtualenvs/wagsite-cck0l_Kh/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/alessiolivolsi/.local/share/virtualenvs/wagsite-cck0l_Kh/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/Users/alessiolivolsi/.local/share/virtualenvs/wagsite-cck0l_Kh/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/alessiolivolsi/.local/share/virtualenvs/wagsite-cck0l_Kh/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/Users/alessiolivolsi/.local/share/virtualenvs/wagsite-cck0l_Kh/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/alessiolivolsi/.local/share/virtualenvs/wagsite-cck0l_Kh/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/alessiolivolsi/.local/share/virtualenvs/wagsite-cck0l_Kh/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/alessiolivolsi/.local/share/virtualenvs/wagsite-cck0l_Kh/lib/python3.9/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 855, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/alessiolivolsi/Work/Projects/first_wag/wagsite/home/models.py", line 8, … -
Get User ID from rest-auth social Login
I have been trying extensively to get the User ID from Django rest-auth Google login. The default response is: { "key": "6ee5ff4db218a25113f35580d00aeeaf2fe8a2d1" } which is not enough, I need to have the user ID with it. I looked at using custom model serializers but to no avail. My class-based view is: class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter Would appreciate any guidance in this regard. Thank you -
Detect if a model is the through model of an M2M relationship
I've got a widget which offers choices built from content types so that objects can be referenced by ID & content type. I'd like to exclude from those choices; proxy models, automatically created models and M2M (through) models. While inspecting the model _meta I found many_to_many so have implemented the following; content_types = ContentType.objects.all() cts = {} for ct in content_types: model = ct.model_class() _meta = getattr(model, '_meta') if not _meta.proxy and not _meta.auto_created and not _meta.many_to_many: cts[ct.id] = str(_meta.verbose_name) This dictionary is then fed to javascript and a select box is generated. The problem that I have, is that models are being excluded simply for containing a ManyToManyField. What's the correct way to identify a through model if not many_to_many? -
How can I fix Page loading along with the preloader?
I have created a preloader here but am having a hard time since the page is displaying along with the preloader. I want only the preloader to show then the other elements after the preloader fades.The preloader is fading out perfectly. Here is the element I want to display after the preloader [![<div class="row "> <div class="col-md-10 offset-1"> <div class="card"> <div class="card"> <h5 class="card-header">Featured</h5> <div class="card-body"> <h5 class="card-title">Special title treatment</h5> <p class="card-text">With supporting text below as a natural lead-in to additional content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> </div> </div>][1]][1] Here is the Javascript part <script src="{% static 'user/js/jquery-3.5.1.min.js' %}"></script> <script> $( document ).ready(function(){ $('.row').hide(); $('.pre-loader').fadeIn('slow', function(){ $('.pre-loader').delay(2500).fadeOut(); $('.row').show(); }); }); </script> {% endblock %} -
Saving foreign key from form
I have an Order model and an Address model. Address is a foreign key on an Order. I would like to save an Address object to the Order object when an order goes through checkout. order.complete and order.transaction_id both work, but order.address does not link an address to an order. Printing address returns Address object (16) relevant code: address = Address.objects.create( customer = customer, name = request.POST.get('name'), line_1 = request.POST.get('line_1'), line_2 = request.POST.get('line_2'), state = request.POST.get('state'), postal_code = request.POST.get('postal_code'), country = request.POST.get('country') ) order.transaction_id = charge.id order.address = address # this is the line that doesn't work order.complete = True order.save() models: class Address(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) name = models.CharField(max_length=200) line_1 = models.CharField(max_length=200) line_2 = models.CharField(max_length=200, null=True, blank=True) state = models.CharField(max_length=100, null=True, blank=True) country = CountryField(null=True, blank=True) postal_code = models.CharField(max_length=15, null=True, blank=True) class Meta: verbose_name_plural = "addresses" class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) address = models.ForeignKey(Address, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) class Meta: verbose_name_plural = "orders" -
How to filter a django OR query correctly
I tried to make an OR query with django q. But the number of results is differnt to filter in single queries: //result is 7 len(Project.objects.filter(Q(moderator='A') | Q(participant='B'))) //result is 6 len(Project.objects.filter(Q(moderator='A'))) //result is 0 len(Project.objects.filter(Q(participant='B'))) since the third query responses a empty queryset, I expect the same results with first and second query. What is here the problem? -
How to get a django field value throw a custom models.Field?
I have a custom field: class MyCustomTextField(models.Field): (...) and use that on my model: class MyModel(): encrypted_password = MyCustomTextField(null=True) password_seed = models.TextField(null=True) I need when I use MyModel to grab encrypted_password, I need to grab first password_seed and return a new value using the password_seed value. How can I do that, since custom model is instantiate before the data comes to the model? -
Django bad escape \p at position 0
I copied a simple regex from here to remove accented letters but its giving an error. import re import unicodedata class Profile(models.Model): name = models.CharField(max_length=200, blank=False) def name_breakdown(self): newName = re.sub(r'\p{Mn}', '', unicodedata.normalize('NFKD', self.name.lower())) return newName the error: bad escape \p at position 0 What do I do to resolve this? -
I am new to django and still learning. Stuck here from quite long as the error message here is confusing. Any solutions?
These are the py files (error says unknown field(s) (model) specified for Post) views.py from django.db import models from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView from .models import Post from .forms import Post_form # Create your views here. #def home(request): # return render(request, 'home.html', {}) class HomeView(ListView): model = Post template_name = 'home.html' class ArticleDetailView(DetailView): model = Post template_name = 'article_details.html' class AddPostView(CreateView): model = Post form_class = Post_form template_name = 'add_post.html' #fields = '__all__' forms.py from django import forms from django.forms import widgets, ModelForm from django import forms from .models import Post class Post_form(forms.ModelForm): class Meta: model = Post fields = ('title','title_tag', 'model', 'body') widgets = { 'title' : forms.TextInput(attrs={'class':'form-control'}), 'title_tag' : forms.TextInput(attrs={'class':'form-control'}), 'author' : forms.Select(attrs={'class':'form-control'}), 'title' : forms.Textarea(attrs={'class':'form-control'}) } Error File "/urls.py", line 3, in <module> from .views import AddPostView, ArticleDetailView, HomeView File "/views.py", line 5, in <module> from .forms import Post_form File "/forms.py", line 6, in <module> class Post_form(forms.ModelForm): File "/models.py", line 276, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (model) specified for Post I am new to django and still learning. Stuck here from quite long as the error message here is confusing. Any solutions? -
How to Check box filter In Django?
I'm using Django as backend, Postgres SQL as DB, and HTML, CSS, and Javascript as frontend. I am stuck in the filtering option, where the user selects check one brand and shows the selected brand list in the template. So basically like this: I have multiple specifications for each category. Like Mobiles have: Brand RAM ROM etc. Till now, I have done list filtering but I want check-box filtering. The Codes goes here: views.py def product(request, data=None): product = Product.objects.all() if data == None: proc = Product.objects.filter(category = 1) elif data == 'OnePlus' or data == 'boAt' or data == 'Redmi' or data == 'realme': proc = Product.objects.filter(category = 1).filter(brand = data) return render(request, 'list/processor.html', {'product': product, 'proc':proc,}) product.html <ul class="list-group"> <a style="text-decoration:none" href="{% url 'main:product' %}"> <li class="list-group-item d-flex justify-content-between align-items-center"> All </li> </a> <a style="text-decoration:none" href="{% url 'main:productdata' 'OnePlus'%}"> <li class="list-group-item d-flex justify-content-between align-items-center"> OnePlus </li> ....... </ul> I have searched for Django-Filter but proper implementation of check-box filtering not there. How the Checkbox filtering will be done because this process takes too much time. Is there any easy way where all the particular columns get a filter, for ex. if brand name LG is repeated more than … -
How to pass 2 arguments to def get_queryset?
Good evening, I have a problem while learning Django. The point is that I am doing a training news site, and there is such an item as "public" - whether the news is published or not. And to display only published news, use "def get_queryset" But I need to display news only with public = True and by the date the news was created views.py class news(ListView): model = Post template_name = 'flatpages/new.html' context_object_name = 'news' # paginate_by = 6 ordering = '-data' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['cate'] = Category.objects.all() return context def get_queryset(self): return Post.objects.filter(public=True) models.py class Category(models.Model): category_name = models.CharField(max_length=64, unique=True) subscribers = models.ManyToManyField(User, blank=True, null=True) class Meta: verbose_name = 'Категория' verbose_name_plural = 'Категории' def __str__(self): return self.category_name class Post(models.Model): PostAuthor = models.ForeignKey(Author, on_delete=models.CASCADE, verbose_name='Автор поста') PostNews = 'PN' PostArticle = 'PA' # «статья» или «новость» POSITIONS = [ (PostArticle, 'Статья'), (PostNews, 'Новость'), ] postCategory = models.ManyToManyField(Category, verbose_name='Категория поста', through='PostCategory') title = models.CharField(max_length=50, verbose_name='Название') positions = models.CharField(max_length=2, choices=POSITIONS, default=PostArticle, verbose_name='Тип поста') category_id = models.ForeignKey(Category, verbose_name='Категория', null=True, on_delete=models.CASCADE, related_name='category_id') data = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания') data_update = models.DateTimeField(auto_now=True, verbose_name='Дата редактирования') photo = models.ImageField(upload_to='photos/%Y/%m/%d/', verbose_name='Фото', blank=True, default='/photos/def/1.jpg/') previewName = models.CharField(max_length=128, verbose_name='Превью поста') text = models.TextField(verbose_name='Текст поста') rating = models.SmallIntegerField(default=0, … -
AssertionError: database connection isn't set to UTC
I have done server setup multiple times with the same settings but this time, I am seeing the error message. It is not even allowing to migrate the database. System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/usr/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/core/management/base.py", line 458, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations return {(migration.app, migration.name): migration for migration in self.migration_qs} File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/models/query.py", line 276, in __iter__ self._fetch_all() File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/models/query.py", line 1261, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/models/query.py", line 57, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1170, in execute_sql return list(result) File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1569, in cursor_iter for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1569, in <lambda> for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/utils.py", line 97, in inner return func(*args, **kwargs) File "/home/datanal/datanal-samply/venv/lib/python3.9/site-packages/django/db/backends/postgresql/utils.py", line 6, in utc_tzinfo_factory raise AssertionError("database connection isn't … -
Optimizing django rest framework API
I have created an API to get all the data from by database. There is a "deployment" table and a related table "sensors" which has a foreign key referencing the deployment, a one-many relationship. The serializer creates a nested JSON. Currently if I request all records it takes roughly 45 seconds to return the data (17,000 JSON lines). How do I profile my Django application to determine what is the bottleneck? Any suggestions on what can be improved to speed this up? Or is this is as good as it's going to get? models.py class deployment(models.Model): ADD_DATE = models.DateTimeField() #creation of record in db #...30 more fields.... class sensor(models.Model): DEPLOYMENT = models.ForeignKey(deployment, related_name='sensors', on_delete=models.CASCADE) ADD_DATE = models.DateTimeField() #creation of record in db SENSOR = models.ForeignKey(sensor_types, to_field="VALUE", max_length=50, on_delete=models.PROTECT) #...5 more foreign key fields... views.py class GetCrtMetadata(generics.ListAPIView): #Read only serializer_class = CurrentDeploymentSerializer queryset=deployment.objects.all().prefetch_related("sensors") filter_backends = [DjangoFilterBackend] filter_fields = [field.name for field in deployment._meta.fields] deployment app serializers.py class CurrentDeploymentSerializer(serializers.ModelSerializer): #Returns deployment with sensors sensors = SensorSerializer(many=True) class Meta: model = deployment fields = [field.name for field in deployment._meta.fields] fields.extend(['sensors']) read_only_fields = fields sensor app serializers.py class SensorSerializer(serializers.ModelSerializer): class Meta: model = sensor fields = [field.name for field in sensor._meta.fields] -
Html / jquery multiple forms submit
I am working on Django File Sharing Project and in file view on click on file preview div it will pop-up modal with description of file . I have problems in IDing multiple forms FileView.html <div class="parent"> <div class="child" onclick="document.getElementsByClass('form').submit();"> <form class="form" method="post" action="django-script.py"> <h5 > File.jpg</h5> <input type="hidden" name="file" value="file.jpg"> <h6 class="title">{{f.filename}}</h6> <img class="image" src="/images/icons/file.png" > </form> </div> <div class="child" onclick="document.getElementsByClass('form').submit();"> <form class="form" method="post" action="django-script.py"> <h5 > File.pdf</h5> <input type="hidden" name="file" value="file.pdf"> <h6 class="title">{{f.filename}}</h6> <img class="image" src="/images/icons/pdf.png" > </form> </div> <div class="child" onclick="document.getElementsByClass('form').submit();"> <form class="form" method="post" action="django-script.py"> <h5 > File.csv</h5> <input type="hidden" name="file" value="File.csv"> <h6 class="title">{{f.filename}}</h6> <img class="image" src="/images/icons/file.png" > </form> </div> If I use ID it works well only for 1 div I dont know how to make it for all div elements Original Django Code ViewFile.html <div class="parent"> {% for f in file %} <div class="child" onclick="document.getElementById('form').submit();"> <form id="form" method="post" action="{% url 'fileview' %}"> {% csrf_token %} <h5 >{{f.title}}</h5> <input type="hidden" name="file" value="{{f.filename}}"> <h6 class="title">{{f.filename}}</h6> <img class="image" src="{% static '/images/icons/file.png' %}" > </form> </div> {% endfor %} Views.py def fileview(request): global loginFlag,loginUser if request.method == 'POST': fil=request.POST['file'] about=Transaction.objects.filter(filename=fil) emp=about[0].userid aname=Employee.objects.filter(emp_id=emp)[0].name print(about) files=Transaction.objects.all() name=loginName context={'files':files,'name':name,'about':about,'aname':aname} return render(request,'detailedview.html',context) else: file=Transaction.objects.all() name=loginName context={'file':file,'name':name} return render(request, 'viewfile.html',context) I think the issue … -
Django Queryset Annotate value with latest related object
i have three models: Brand, Log and Abstract MWModel. class Log(models.Model): app = models.CharField(max_length=20, choices=get_modules()) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') method = models.CharField(max_length=8, choices=HTTP_METHODS) url = models.TextField() body = models.TextField(null=True) code = models.IntegerField() message = models.TextField(null=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.created_at.isoformat() class MWModel(models.Model): log = GenericRelation(Log) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class Brand(MWModel): name = models.CharField(max_length=50) status = models.BooleanField(default=True) def __str__(self): return self.name How can get code field of last Log record created for each Brand? I have this Brand.objects.filter( merchant=account.merchant, identity__app=F('merchant__erp') ).annotate( log__last__created_at=Max('log__created_at'), log__last__code=Log.objects.filter( content_type__model=Brand._meta.model_name, object_id=OuterRef('pk') ).order_by('-created_at').values('code')[:1] ).values('pk', 'name', 'log__last__created_at', 'log__last__code') And i need something like this Brand.objects.filter( merchant=account.merchant, identity__app=F('merchant__erp') ).annotate( log__last__created_at=Max('log__created_at'), log__last__code=F('log__code', filter=Q('log__created_at'=F('log__last__created_at'))) ).values('pk', 'name', 'log__last__created_at', 'log__last__code') I would greatly appreciate your help. Thanks. -
Print a list in HTML file using Django
I want to print a list called formulario and I want to paste them into a html file using Django template language, although I'm not able to display that information in <li> tag. Is there sth am I missing? views.py from django.template import RequestContext from django.http import HttpResponse from django.shortcuts import render import pandas as pd formulario = ["Hola", "Hi"] def formulario(request): return render (request, "formulario/formulario.html",{ "formulario":formulario }) Html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Formulario !</h1> <ul> {% for formulario in formulario %} <li>{formulario}</li> {% endfor %} </ul> </body> </html> urls.py from django.urls import path from . import views urlpatterns = [ path("index.html",views.index, name="index"), path("financierofinanciamiento.html",views.financiamiento, name="financiamiento"), path("financierobeneficio.html",views.beneficio, name="beneficio"), path("tecnicoinfra.html",views.infra, name="infra"), path("tecnicoequipo.html",views.equipo, name="equipo"), path("tecnicoherramientas.html",views.herramientas, name="herramientas"), path("tecnicomateriaprima.html",views.materiaprima, name="materiaprima"), path("formulario.html",views.formulario, name="formulario"), ] -
want to do authentication using django rest framework, i want to setup the login route for mentors and other users and preserve some end points
Basically i want to authenticate the current user using user_details model and also to check if current user is a mentor and establish authorisation for the endpoints and preserve some endpoints from user But i am not able to understand how to achieve it 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) 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' my serializers.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 = … -
Order queryset using the number of related objects in Django
Let's say I have the following in models.py: class A(models.Model): ... class B(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) What I want to do is sort a queryset for A based on how many B objects they have, in descending order. What is the best approach to this issue? Thanks for any help. -
Get image file and fields in Django rest framework
I am trying to upload image via django restframe work and return a custom response views.py class Imageuploadviewset(viewsets.ModelViewSet): queryset = UploadModel.objects.all() serializer_class = UploadSerializer def retrieve(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance) return Response({'something': 'serializer'}) def list(self, request, *args, **kwargs): return Response({'Model': 'Skin Disease Diagnosis'}) models.py class UploadModel(models.Model): name=models.CharField(max_length=50) image=models.ImageField('images/') urls.py router = DefaultRouter() router.register(r'UploadModel', views.Imageuploadviewset) urlpatterns = [ path('',views.home,name='home'), path('api/', include(router.urls)), ] Serializer.py class UploadSerializer(serializers.HyperlinkedModelSerializer): class Meta: model=UploadModel fields='__all__' Query is that how to play with name and image upload, run some functions on them and return a response. I am not sure how to get those. -
How to combine in one url both url not run on same time?
url(r'^(?P[\w]+)', views.myquestion.questions, name = 'questions'), url(r'^(?P[\w]+)', views.myquestion.mcqs, name = 'mcqs'), -
Django slow loading page due to lots of codes
I am implememting a small recommendation feature on my home page which will suggest jobs to candidates. To accomplish the latter, I have used CountVectorizer and Cosine Similarity. However, to perform this, I had to concatenate lots of fields from the candidate's profile and job description. This code is defined in the views.py. Every time I load the home page, this view gets executed and eventually, it takes time to load. Is there something I can do to improve the loading speed? Thank you guys ;)