Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make Django pagination with ajax without re-querying the DB
I've checked many related questions on building up pagination with ajax and implemented it in my app. The problem I still have is querying DB each time user сlicks next or prev because ajax call goes to the view function. My code: my_template.html <ul class="list-articles" id="dd"> </ul> <div class="buttons"> {% if page_obj.has_previous %} <a href="#" onclick="ajax_function('{{page_obj.previous_page_number}}','{{title}}')" id="prev">&#10094; prev</a> {% endif %} {% if page_obj.has_next %} <a href="#" onclick="ajax_function({{page_obj.next_page_number}},'{{title}}')" id="next"> next &#10095;</a> {% endif %} </div> views.py def my_view_function(request): if is_ajax(request=request): if 'page' in request.GET: return paginate(request) def paginate(request): parameter_a = request.GET['parameterA'] parameter_b = request.GET['parameterB'] li = MyModel.objects.filter(par_a=parameter_a, par_b=parameter_b) paginator = Paginator(li, 1) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'page_obj': page_obj, ... } return render(request, f'my_app/my_template.html', context) main.js function ajax_function(page, title) { $.ajax({ url: '', type: "get", data: { 'page': page, 'title':title, }, success: function(response, status) { $('#dd').empty(); $('#dd').html(response); } }); } So this code is working but in real app I have more complex db queries to get my Model's objects, so every next/prev iteration will recall the objects again and again which look dump. Ideally I'd like to collect the list of objects once and then use them without any additional queries. I'm not a JS … -
how do you pass a parameter from post method to decorator?
I'm working a python django and django rest framework + swagger (drf-yasg) project. I need a dynamic decorator. how do you pass a parameter(named in this case "essource") of post method to decorator? def xxx(esSource): source = {} if esSource == 1: source = { 'field_1': openapi.Schema(type=openapi.TYPE_INTEGER) } else: source = { 'field_44': openapi.Schema(type=openapi.TYPE_INTEGER) } properties = { 'type_operator': openapi.Schema(type=openapi.TYPE_INTEGER,description="L'operatore di insieme AND(0) OR(1)"), 'column_to_hide': openapi.Schema(type=openapi.TYPE_STRING,description="L'elenco di colonne da nascondere separato da virgola") } return properties.update(source) class ShowResultsView(views.APIView): @swagger_auto_schema( operation_description="La prima pagina di risultati della ricerca", request_body=openapi.Schema( type=openapi.TYPE_OBJECT, required=['type_operator','column_to_hide'], properties=xxx(essource) ), ) def post(self,request,essource,page): resp = {} resp["status"] = 0 resp["data"] = {} resp["message"] = "I risultati della ricerca" return Response(resp,status=status.HTTP_200_OK) I get an error in this line code: properties=xxx(essource) -
Heroku app won't restart after error 14 (Memory quota exceeded)
We have a Django app deployed on Heroku with the following Procfile: release: python manage.py migrate web: gunicorn RDHQ.wsgi:application --log-file - --log-level debug celery: celery -A RDHQ worker -l info Yesterday the app was down and accessing the site returned ERR_CONNECTION_TIMED_OUT. When I looked at the logs, I saw that the celery process was showing an R14 (Memory usage exceeded) error: 2022-12-24T07:14:46.771299+00:00 heroku[celery.1]: Process running mem=526M(102.7%) 2022-12-24T07:14:46.772983+00:00 heroku[celery.1]: Error R14 (Memory quota exceeded) I restarted the dynos a couple of times, but the celery dyno immediately throws the same error after restart. I then removed the celery process entirely from my Procfile: release: python manage.py migrate web: gunicorn RDHQ.wsgi:application --log-file - --log-level debug After I pushed the new Procfile to Heroku, the app is still down! I tried manually scaling down the web dyno and then scaling it up again - nothing. This is what the logs show: 2022-12-24T07:57:26.757537+00:00 app[web.1]: [2022-12-24 07:57:26 +0000] [12] [DEBUG] Closing connection. 2022-12-24T07:57:53.000000+00:00 app[heroku-postgres]: source=HEROKU_POSTGRESQL_SILVER addon=postgresql-reticulated-80597 sample#current_transaction=796789 sample#db_size=359318383bytes sample#tables=173 sample#active-connections=12 sample#waiting-connections=0 sample#index-cache-hit-rate=0.99972 sample#table-cache-hit-rate=0.99943 sample#load-avg-1m=0.01 sample#load-avg-5m=0.005 sample#load-avg-15m=0 sample#read-iops=0 sample#write-iops=0.076923 sample#tmp-disk-used=543600640 sample#tmp-disk-available=72435191808 sample#memory-total=8038324kB sample#memory-free=3006824kB sample#memory-cached=4357424kB sample#memory-postgres=25916kB sample#wal-percentage-used=0.06576949341778418 2022-12-24T07:59:26.615551+00:00 app[web.1]: [2022-12-24 07:59:26 +0000] [12] [DEBUG] GET /us/first-aid-cover/california/ 2022-12-24T07:59:28.421560+00:00 app[web.1]: 10.1.23.217 - - [24/Dec/2022:07:59:28 +0000] "GET /us/first-aid-cover/california/?order_by=title HTTP/1.1" 200 … -
Display related foreign keys in the parent model in Django admin
I'm using PostgreSQL for the DB. I have two models: Project: can contain N Assets. Asset: has a Foreign Key field that points to a Project. An Asset is related to 1 Project. I want the user to be able to set the order of the Assets of a Project in the Django Admin in a handy way like ordering a list in the edit Project screen. The order of the Assets is important in my bussiness logic, but I dont want the user to set the order in each individual Asset (just to improve UX). Is there a way to show a field in the Project admin screen that lists all the Assets that are related to the project and allow the user to order it as he wishes? I did not found any solution to this more than adding a new field in the Asset modal to specify the order and handling the logic by myself (which is expected), however, I don't want it to be a field that have to be changed manually in each individual Asset. -
How to convert my django web app to a portable .exe software?
I have developed a django project and currently deployed on localhost. Currently I am running it through a .bat file giving it the path of project directory and opening its IP address in chrome browser. MY BAT FILE - start chrome http://127.0.0.1:500 cd Desktop cd SFM python manage.py runserver 500 I want my project to make executable and portable after someone downloads it, it downloads all packages and libraries and runs the command to run it automaitcally. Help me.... -
What is the right redirection?
I'm a beginner in Django and I want to display the username from the nav bar. I did not use User athentication. I only created custom database table called JobseekerJobseeker database table. Because the criteria is the user should be able to login using username or email then password. I was able to achieve that using this code,code for username/email login. Now my problem is using {{request.user}} in the nav bar it display the superuser's username, instead on the jobseeker username. Superuser's username. Code for the HTML I want to display the username that i inputed in the login form. It should be one of these username that needs to be displayed sorry for the bad english but hopefully it makes sense. -
How to get rid of not existing errors?
Here is my code from rest_framework.decorators import api_view from rest_framework.permissions import IsAuthenticated, AllowAny from rest_framework.response import Response from rest_framework import viewsets, status from .models import Actor from .serializers import ActorSerializer # Create your views here. class ActorView(viewsets.ModelViewSet): model = Actor queryset = model.objects.all() permission_classes = (AllowAny,) serializer_class = ActorSerializer http_method_names = ['get', 'post', 'put', 'delete'] def list(self, request): serializer = ActorSerializer(self.queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def create(self, request): serializer = ActorSerializer(data=request.data) if serializer.is_valid(raise_exception=True): print(serializer.validated_data['name']) return Response("OK", status=status.HTTP_200_OK) else: return Response("nie ok") Pylance thinks that this line: print(serializer.validated_data['name']) is incorrect, but it is correct. Code works fine and it doesn't displaying any errors while server is running and request is sent. But it is underlined in red, so something must be wrong. How can i get rid of those "errors"? "__getitem__" method not defined on type "empty" Object of type "None" is not subscriptable I am using VSC python 3.10. I have alredy tried uninstalling Pylance and changing its' version but all for nothing. -
Django include template show no data
I am trying to include a html file, into my course page , but when i add the code it show just first tag that is h3 and don't show other data why ? the code : {% include 'android/side_bar_good_posts.html' %} note : i have added this code in other pages in my website and it work and show all data but in this page course it don't show anything else ( most read articles ) word -
pass a list to js to display a chart
Hi I am new to Js and I have some issues to display my chart property. I am trying to pass a list to the template, then grab by my js scrpit, and last pass that list to display chart. I have this tag en my template: <div style="display: none" id="listData" listmonth="{{ month_profit_list }}"></div> Then pass to js file like this: var ctx1 = $("#worldwide-sales").get(0).getContext("2d"); const div1 = document.getElementById('listData'); var listMonth = div1.getAttribute('listmonth'); console.log(listMonth) var myChart1 = new Chart(ctx1, { type: "bar", data: { labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul","Ago","Sep","Oct","Nov","Dec"], datasets: [{ label: "USA", data: listMonth, backgroundColor: "rgba(0, 156, 255, .7)" }, ] }, options: { responsive: true } }); In fact my list displays in console fine but y got this chart: when my list output in cosole is this = [129, -69, 226, 25, 151, 114, -79, 4, 49, 61, -76, 65] Any idea why is showing in chart wrong data? -
ImportError: cannot import name 'Users' from partially initialized module tasks file
ImportError: cannot import name 'Users' from partially initialized module 'users.models from .models import Users from celery import shared_task from django.core.mail import send_mail from server import settings @shared_task() def send_mail_task(user_id): user = Users.objects.get(id=user_id) send_mail( subject='Congratulations!', message=f'Congratulations {user.username}', from_email=settings.EMAIL_HOST_USER, recipient_list=["waelelsafty07@gmail.com", ], fail_silently=False, ) print('Email sent successfully') return f'Email sent successfully' checking installing celery -
Django: make a copy of model admin page into website so normal users can do all the things that staff could
i am looking for make a replica of models admin page (like posts,comments, etc..) into a part of my website. so for example non staff users with given permission could make new posts or filter the posts or even delete them. basically a complete copy of post admin page with all its features -
How to handle IntegrityError exception of conditional unique constraint in Django/Postgres?
let's assume we have the below model class code: from django.db import models class SupplierAddress(models.Model): """Model to create supplier's address instances""" class Meta: """Customize django default way to plural the class name""" verbose_name = 'Supplier Address' verbose_name_plural = 'Supplier Addresses' constraints = [ models.UniqueConstraint( fields=['supplier', 'address'], name='supplier_address_unique_appversion' ), models.UniqueConstraint( fields=['supplier'], condition=models.Q(is_default=True), name='one_default_address_per_supplier' ) ] # Define model fields. supplier = models.ForeignKey( 'Supplier', on_delete=models.CASCADE, related_name='supplier_addresses_supplier' ) address = models.ForeignKey( 'Address', on_delete=models.CASCADE, related_name='supplier_addresses_address' ) is_default = models.BooleanField(default=False) def __str__(self): """String representation of model objects""" return '{}, {}'.format(self.supplier, self.address) This model constraints will make sure there is unique constraint between supplier and address foreign keys AND a conditional unique constraint between supplier and is_default when it's True. The conditional unique constraint in Django and Postgres as database engine, will raise an exception: IntegrityError: duplicate key value violates unique constraint... In case the input by user go against the constraint condition. Ideas to handle such case: 1- handle such case on user side, like using forms But not a good idea for testing. 2- using clean() method and raise an error message, like: def clean(self, *args, **kwargs): """Restrict the add/change to model fields""" if self.is_default is True: if SupplierAddress.objects.filter( supplier=self.supplier, is_default=True ).exclude(id=self.id).count() >= 1: … -
taggit django error, access posts through the links of the tags, error Cannot query "jazz": Must be "Post" instance
I'm new to Django and I'm studying through the book Django 3 by example, when implementing the tags, at the end of chapter 2, I can't access them. The assigned error is as follows: "Cannot query "jazz": Must be "Post" instance" my views.py def post_list(request, tag_slug=None): object_list = Post.published.all() tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) object_list = object_list.filter(tags__in=[tag]) paginator = Paginator(object_list, 2) # 2 posts in each page page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request,'blog/post/list.html',{'page': page,'posts': posts, 'tag': tag}) my urls.py urlpatterns = [ # post views path('', views.post_list, name='post_list'), path('tag/<slug:tag_slug>/', views.post_list, name='post_list_by_tag'), # path('', views.PostListView.as_view(), name='post_list'), path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'), path('<int:post_id>/share/', views.post_share, name='post_share'), my list.html % block content %} <h1>My Blog</h1> {% if tag %} <h2>Posts tagged with "{{ tag.name }}"</h2> {% endif %} {% for post in posts %} <h2> <a href="{{ post.get_absolute_url }}"> {{ post.title }} </a> </h2> <p class="tags"> Tags: {% for tag in post.tags.all %} <a href="{% url "blog:post_list_by_tag" tag.slug %}"> {{ tag.name }} </a> {% if not forloop.last %}, {% endif %} {% endfor %} </p> <p class="date"> Published … -
how to connect correctly fastapi and aiogram
I have a api on fastapi with db, how correctly get data from server? Just connect to fastapi db or use http requests? I saw how used Django Rest Framework and aiogram -
I can't get VScode to activate a virtual environment called ll_env
I'm trying to create a virtual environment for Django Project ,(Chapter 18-20) of Python Crash Course, and it won't work I'm on python version 3.10.7 Here is a link to the book: https://www.google.com/books/edition/Python_Crash_Course_2nd_Edition/w1v6DwAAQBAJ?hl=en&gbpv=1 you can find the chapter in question at page 379 here is the file that generates when you run the first command: https://github.com/Hunty405/ll_env C:\Python\Projects\Learning Log> python -m venv ll_env **<- Create virtual Environment** C:\Python\Projects\Learning Log> source ll_env/bin/activate **<- Activate virtual Environment** source : The term 'source' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + source ll_env/bin/activate + ~~~~~~ + CategoryInfo : ObjectNotFound: (source:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\Users\hlehm\Onedrive Transfer\Python\Projects\Learning Log> I tried running the given codes in the book but i can't get it to activate the environment please help -
The 'poster' attribute does not have a file associated with it"
the following error occurs "The 'poster' attribute does not have a file associated with it" I don't quite understand what it may be related to and how to fix it I tried to change the url value, but nothing worked. I'm new to django. Please help html <div class="container" style="grid-template-columns: repeat(auto-fill, 300px);"> for serial in serials %} <div class="item"> <img src="{{ serial.poster.url }}" class="img-fluid" alt=""> <p> <a href="{% url 'detail_serial' serial.url %}">{{ serial.title }}</a> </p> </div> endfor %} </div> views.py class SerialDetailView(View): def get(self, request): serials = Serials.objects.all() genres = Genre.objects.all() return render(request, "serials/single_serial.html", {"serials": serials, "genres": genres}) urls.py urlpatterns = [ path('register/', views.Register.as_view(), name='register'), path('reg/', views.Reg.as_view(), name='reg'), path("serials_list/", views.SerialsView.as_view(), name='serials_list'), path("add/", views.AddView.as_view(), name='add'), path("single_serial/", views.SerialDetailView.as_view(), name='single_serial'), path("<slug:slug>/", views.SingleSerial.as_view(), name='detail_serial'), path("actor/<int:id>/", views.ActorView.as_view(), name='actor_detail'), ] -
multiple instances of django using 1 celery
I'm using Django as webserver, and redis as broker. I have 3 virtual machines running the same Django app and load balance among them and 1 redis server shared between them. Problem we are facing now is that if we run workers and scheduler on each machine then if we run task_1 on machine 1 then all machines run it 1 time.(total of 3 times.) if we turn off the worker and scheduler on 2 of the machines ( let's say 2 , 3). and then run task_1 on machine 1 everything is okay. but if we run it on machine 2 or 3 nothing happens. my plan is to change celery broker url on each machine and change database so instead of redis://host:port on all of them it would be redis://host:port/1 redis://host:port/2 redis://host:port/3 I wanted to know if this is the right way to go or is there another general solution which only requires 1 machine with celery running on it? -
Updating templates in django app without re-rendering the pages
I'm making a Django web application in python, similar to language learning quiz. It consists of three different parts. One is showing the set of sentences to a user (one element per page) and the second is asking questions about sentences that was just shown. The third one is showing results and asking for redo the wrong q/a. Each part has next/prev buttons for iteration and the content of the sentence. I also need to store info to DB when the user answers the question right to not to show it again. The set of questions is provided by a view function through filtering the models objects. I need to have these 3 stages without page rendering. I face the following problem: The list of questions is passed to the template to iterate over it once to present sentences, then I need to start the loop again with the only difference of adding a field of textarea for answer and a few buttons. What is the best way to do it? I was thinking about some ajax function that'll be triggered after the first loop is finished. This js function can refill the certain tags with textarea and buttons. But … -
i have issues in my schedule school when trying to accommodate with days and hours in my schedule school (django)
This is my modle to create a school class. class Semestre(models.Model): WEEK_DAY = ( ('Lunes', 'Lunes'), ('Martes', 'Martes'), ('Miercoles', 'Miercoles'), ('Jueves', 'Jueves'), ('Viernes', 'Viernes'), ('Sabado', 'Sabado') ) semestre = models.CharField(max_length=1) licenciatura = models.ForeignKey(Licenciatura,null=False,on_delete=models.CASCADE) ciclo = models.CharField(max_length=5,null=False) week_day = MultiSelectField(max_length=2000,choices=WEEK_DAY,max_choices=6) start_time = models.PositiveBigIntegerField(null=True) end_time = models.PositiveBigIntegerField(null=True) history = HistoricalRecords() class Meta: db_table = 'institucion_semestre' def __str__(self): template = 'Semestre {0.semestre} de {0.licenciatura} ciclo {0.ciclo}' return template.format(self) This is a techer model when choose a course class DocenteMateria(models.Model): materia = models.ForeignKey(Page,null=False,on_delete=models.CASCADE,related_name='matdoce') docente = models.ForeignKey(Docente,null=False,on_delete=models.CASCADE,related_name='docedoce') clase = models.ForeignKey(Semestre,null=False,on_delete=models.CASCADE) start_time = models.PositiveBigIntegerField(null=False) end_time = models.PositiveBigIntegerField(null=False) dia = models.CharField(max_length=10,null=False) history = HistoricalRecords() class Meta: db_table = 'pages_docenteMateria' def __str__(self): template = '{0.materia} {0.docente}' return template.format(self) And this is my view to create a schedule class def TimeTableView(request,id): try: section = Semestre.objects.get(id=id) docema = DocenteMateria.objects.select_related('materia','docente','clase').filter(clase_id=section.id) results = DocenteMateria.objects.raw('SELECT * from pages_docenteMateria GROUP BY dia') admin = Admin.objects.all() coordina = Coordina.objects.all() docente = Docente.objects.all() pages = Page.objects.all() disponi = Disponibilidad.objects.all() matedo = DocenteMateria.objects.all() print(docema.query) print(results.query) time = [0] * (section.end_time - section.start_time) time_slot = [''] * (section.end_time - section.start_time) for x in range(0, len(time)): time_slot[x] = str(section.start_time + x) + ':00 - ' + str(section.start_time + x + 1) + ':00' time[x] = section.start_time + x context_1 … -
django super user premissions
i want to add if user is super user show companies and add company anyone can help with what should add in class to do it this is class code just showing in tepmalte page all comapany and add new company not working views.py class Companies(LoginRequiredMixin, FormView, ListView): """ Company add edit delete view """ model = Company template_name = 'company/index.html' form_class = AddCompanyForm success_url = reverse_lazy('companies:index') object_list = Company.objects.all() def form_valid(self, form): user, created = User.objects.get_or_create(username=form.cleaned_data['username'], email=form.cleaned_data['email']) user.set_password(form.cleaned_data['password']) user.save() if created: address = Address(label=form.cleaned_data['label'], city=form.cleaned_data['city'], area=form.cleaned_data['area'], long=form.cleaned_data['longitude'], lat=form.cleaned_data['latitude'], country=form.cleaned_data['country']) address.save() company = Company(owner=user, name=form.cleaned_data['name'], phone_number=form.cleaned_data['phone_number'], logo=form.cleaned_data['logo'], address=address, water_source=form.cleaned_data['water_source']) company.save() return super().form_valid(form) form.py ` class AddCompanyForm(forms.ModelForm): """ Add company model form """ name = forms.CharField(required=True) password = forms.CharField(widget=forms.PasswordInput()) logo = forms.ImageField(required=False) phone_number = forms.CharField(widget=forms.NumberInput()) label = forms.CharField(max_length=20) country = forms.ModelChoiceField(queryset=Country.objects.all()) city = forms.ModelChoiceField(queryset=City.objects.all()) area = forms.ModelChoiceField(queryset=Area.objects.all()) latitude = forms.CharField(max_length=50, required=False) longitude = forms.CharField(max_length=50, required=False) water_source = forms.ModelChoiceField(queryset=WaterSource.objects.all()) class Meta: model = User fields = ['name', 'username', 'email', 'password'] def __init__(self, *args, **kwargs): super(AddCompanyForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.layout = Layout(Row(Column('name', css_class='form-group col-md-6 mb-0'), Column('username', css_class='form-group col-md-6 mb-0'), css_class='form-row'), Row(Column('email', css_class='form-group col-md-6 mb-0'), Column('password', css_class='form-group col-md-6 mb-0'), css_class='form-row'), Row(Column('phone_number', css_class='form-group col-md-6 mb-0'), Column('logo', css_class='form-group col-md-6 mb-0'), css_class='form-row'), … -
Using Django Rest Framework, how can I capture values from an URL to a viewset using routers, not with URLconf?
I have two models: the first is named Card and has a foreign key (named owner) to the second model (User). I'm trying to write a view that lists all the Cards owned by a User, the client selects the User by changing the URL (not query parameters). For example, if I make a GET request to /cards/by-user-id/42/, I should get all the Cards owned by the User whose id is 42. From what I understood, it is possible to achieve this by using an URL pattern like this : path('cards/by-user-id/<int:user_id>', my_view.as_view()) and then in the viewset I can use self.kwargs['user_id'] to get the id and then filter the data. However, I can't find how to do it using routers (more appropriated for djangorestframework). I tried with <int:user_id> in the prefix but it does not pick it up, it just considers it as a normal string, so not only the URL is incorrect (I have to type literally /cards/by-user-id/<int:user_id>/) but also kwargs doesn't contain 'user_id'. Here is what I tried: models.py: from django.contrib.auth.models import User from django.db import models class Card(models.Model): owner = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) serializers.py: from rest_framework import serializers from . import models class CardSerializer(serializers.ModelSerializer): owner = serializers.StringRelatedField() … -
I want to enable or disable fields for some users from admin panel
This is template <div class="container mt-3"> <h5 class="card-title">Kindly enter the details. All details are required</h5> <form class="row g-3" method="post" action="{% url 'home' %}" enctype="multipart/form-data"> {% csrf_token %} <div class="col-md-4"> <label for="name" class="form-label">Full Name</label> <input type="text" class="form-control" id="name" name="name" required> </div> <div class="col-md-4"> <label for="parentage" class="form-label">Father's Name</label> <input type="text" class="form-control" id="parentage" name="father" required > </div> <div class="col-md-4"> <label for="mothername" class="form-label">Mother's Name</label> <input type="text" class="form-control" id="mothername" name="mother" required> </div> <div class="col-md-4"> <label for="phonenumber" class="form-label">Phone number</label> <input type="tel" class="form-control" id="phonenumber" name="pnumber" required> </div> <div class="col-md-4"> <label for="ephonenumber" class="form-label">Emergency contact number</label> <input type="tel" class="form-control" id="ephonenumber" name="enumber" required> </div> <div class="col-md-4"> <label for="dob" class="form-label">Date of Birth</label> <input type="date" class="form-control" id="dob" name="dob" required> </div> <div class="col-12"> <label for="inputAddress" class="form-label">Address</label> <input type="text" class="form-control" id="inputAddress" placeholder="" name="address" required> </div> <div class="col-md-6"> <label for="photo" class="form-label">Upload a photo</label> <input type="file" class="form-control" id="photo" name="photo" accept="image/*,.pdf" required> </div> <div class="col-md-4"> <label for="schoolname" class="form-label">School Name</label> <input type="text" class="form-control" id="schoolname" name="sname" required > </div> <div class="col-md-4"> <label for="inputState" class="form-label">Role</label> <select id="select" class="form-select" name="role" required> <option selected>Choose...</option> <option value="student">Student</option> <option value="teacher">Teacher</option> </select> </div> <div id="show"> </div> <div class="col-12"> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> </div> This is models.py class Student(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,null=True) fullname= models.CharField(max_length=50) father = models.CharField(max_length=30) mother = models.CharField(max_length=30) phno=models.IntegerField() ephno = models.IntegerField() … -
ModuleNotFoundError when importing into database in django python
I have a file that is trying to populate the database. However it shows modulenotfounderror error message directory The error is pointing to the below code. error area settings.py have included the app config settings.py I am not sure what else is the problem. Help please. -
Django Login/Logout Logger
I have a django project where I need to know how much time each user spends on the site. The first thing that came to my mind was that since I have a CustomUser I can create my own login/logout view and populate a table with login and logout and the user's identifier. However, I wanted to know if there is a callback function for django.contrib.auth.urls. So I can use the default login form? -
GeocoderUnavailable at /
from django.shortcuts import render, get_object_or_404 from .models import Measurement from .forms import MeasurementModelForm from geopy.geocoders import Nominatim from geopy.distance import geodesic from .utils import get_geo, get_center_coordinates, get_zoom import folium Create your views here. def calculate_distance_view(request): # initial values distance = None destination = None obj = get_object_or_404(Measurement, id=1) form = MeasurementModelForm(request.POST or None) geolocator = Nominatim(user_agent='measurements') ip = '72.14.207.99' country, city, lat, lon = get_geo(ip) location = geolocator.geocode(city) # location coordinates l_lat = lat l_lon = lon pointA = (l_lat, l_lon) # initial folium map m = folium.Map(width=800, height=500, location=get_center_coordinates(l_lat, l_lon), zoom_start=8) # location marker folium.Marker(\[l_lat, l_lon\], tooltip='click here for more', popup=city\['city'\], icon=folium.Icon(color='purple')).add_to(m) if form.is_valid(): instance = form.save(commit=False) destination\_ = form.cleaned_data.get('destination') destination = geolocator.geocode(destination\_) # destination coordinates d_lat = destination.latitude d_lon = destination.longitude pointB = (d_lat, d_lon) # distance calculation distance = round(geodesic(pointA, pointB).km, 2) # folium map modification m = folium.Map(width=800, height=500, location=get_center_coordinates(l_lat, l_lon, d_lat, d_lon), zoom_start=get_zoom(distance)) # location marker folium.Marker(\[l_lat, l_lon\], tooltip='click here for more', popup=city\['city'\], icon=folium.Icon(color='purple')).add_to(m) # destination marker folium.Marker(\[d_lat, d_lon\], tooltip='click here for more', popup=destination, icon=folium.Icon(color='red', icon='cloud')).add_to(m) # draw the line between location and destination line = folium.PolyLine(locations=\[pointA, pointB\], weight=5, color='blue') m.add_child(line) instance.location = location instance.distance = distance instance.save() m = m.\_repr_html\_() context = { 'distance' …