Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to convert Polygon object in Django GIS to an image
I am running a Django project, I created a Company model with company_activity_area field. My goal is to generate an image from the map. and even better, to generate a map image for each polygon. this is my code. from django.contrib.gis.db import models class Company(models.Model): company_activity_area = models.MultiPolygonField(null=True, blank=True, srid=4326, verbose_name='Area of Operation') def save(self, *args, **kwargs): for polygon in self.company_activity_area: # TODO: generate the map image for each polygon, where the polygon appear at the middle of the map super(Company, self).save(*args, **kwargs) -
How to get "starred mails" from Gmail or other mail services using IMAP_tools in django
I am able to get inbox emails and also able to get emails from specific folder but i am unable to get "starred" emails. I tried below code. and i am expecting emails with "starred flag" in response. from imap_tools import MailBox, A # Create your views here. def temp(request): #Get date, subject and body len of all emails from INBOX folder with MailBox('smtp.gmail.com').login('admin@gmail.com', 'password', 'INBOX') as mailbox: temp="empty" for msg in mailbox.fetch(): temp = (msg.date, msg.subject, msg.html) return HttpResponse(temp) -
How to import external .json file to Django database(sqlite)?
So, what is the basic thing I can do to initialize my Django database with the data I have in external .json file. I tried to upload through admin's page after running py manaeg.py runserver but there is no import options. -
Hide modal after form successful submition
I'm using Bootstrap Modals and HTMX to create an event in Django. I got the form rendering OK inside the modal, but when I submit the form the index page appears inside the modal (the success_url parameter of the CreateView). I'd like to hide the modal after the submission and then show the index full screen. This is the modal in the template: <!-- Start modal --> <button type="button" hx-get="{% url 'events:create' %}" hx-target="#eventdialog" class="btn btn-primary"> Add an event </button> <div id="eventmodal" class="modal fade" tabindex="-1"> <div id="eventdialog" class="modal-dialog" hx-target="this"> </div> </div> <!-- End modal --> And this is the Javascript that makes it show the modal: ;(function(){ const modal = new bootstrap.Modal(document.getElementById('eventmodal')) htmx.on('htmx:afterSwap', (e) => { if (e.detail.target.id == "eventdialog") modal.show() }) I tried adding this to the Javascript code but it doesn't work: htmx.on('htmx:beforeSwap', (e) => { if (e.detail.target.id == 'eventdialog' && !e.detail.xhr.response) modal.hide() }) How can I make the modal hide after submitting the form? This is my view: class CreateEvent(LoginRequiredMixin, CreateView): model = Event form_class = EventForm template_name = 'events/events_form.html' success_url = reverse_lazy('events:index') def form_valid(self, form): form.instance.author = self.request.user event_obj = form.save(commit=True) image = self.request.FILES.get('image') if image: EventImage.objects.create(title=event_obj.title, image=image, event=event_obj) return super(CreateEvent, self).form_valid(form) -
I want different authentication system for user and admin in djagno
I create a website where there is a normal user and admin. They both have different log in system.But the problem is when a user logged in as a user, he also logged in into admin page. Also when a admin logged in, he also logged in into user page. def userlogin(request): error = "" if request.method == 'POST': u = request.POST['emailid'] p = request.POST['pwd'] user = authenticate(username=u, password=p) try: if user: login(request, user) error = "no" return redirect(profile) else: error = "yes" except: error = "yes" return render(request, 'login.html', locals()) def login_admin(request): error = "" if request.method == 'POST': u = request.POST['uname'] p = request.POST['pwd'] user = authenticate(username=u, password=p) try: if user.is_staff: login(request, user) error = "no" else: error ="yes" except: error = "yes" return render(request,'login_admin.html', locals()) I want to achive different authentication system for user and also for admin. -
URL with parameters does not find static files Django
I'm making a URL with parameters but it does not find the static files because it adds the name of the URL to the location of the static files, with normal urls this does not happen (I already have some pages working like this). This is a url without parameters This is a url with parameters Look that add 'validador' to static file urls This is the function URLs file -
Django ORM ignoring globally related_name
I have a project with more than 100 models generated from PostgreSQL, when I use it there are many Reverse accessor clashes with ForiegnKey and ManyToManyFields. How can we ignore this functionality of Django globally, instead of adding related_name="+" for each model? -
Django rest Ecommerce category and product offers
I'm trying to acheive catgeory and product offers in my project and am unable to come up with a solution. Like if i give offer to a category all products price in category should get the offer and for products its individual. class Category(models.Model): category_name = models.CharField(max_length=15, unique=True) slug = models.SlugField(max_length=100, unique=True) class Meta: verbose_name_plural = "Category" class Products(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) product_name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=100, unique=True) description = models.TextField(max_length=500) price = models.IntegerField() images = models.ImageField(upload_to="photos/products") images_two = models.ImageField(upload_to="photos/products") images_three = models.ImageField(upload_to="photos/products") stock = models.IntegerField() is_available = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = "Products" def __str__(self): return self.product_name class CategoryOffer(models.Model): category = models.OneToOneField(Category, on_delete=models.CASCADE, related_name='cat_offer') valid_from = models.DateTimeField() valid_to = models.DateTimeField() discount = models.IntegerField( validators=[MinValueValidator(1), MaxValueValidator(100)] ) is_active = models.BooleanField(default=False) def __str__(self): return self.category.category_name class ProductOffer(models.Model): product = models.OneToOneField(Products, on_delete=models.CASCADE, related_name='pro_offer') valid_from = models.DateTimeField() valid_to = models.DateTimeField() discount = models.IntegerField( validators=[MinValueValidator(1), MaxValueValidator(100)] ) is_active = models.BooleanField(default=False) def __str__(self): return self.product.product_name So above are my models. I don't know how to implement, thought of many ways but it keeps leading to errors. -
Django pressing browser back button causes data to reappear
When a user adds a comment to a post, and they want to go back to the home page, and if they press the browser back button, the form cycles through every time the form had data that they had posted. The user has to press the back button (depending on the amount of comments made) at least 2 or 3 times to get to the home page. For Example: A user adds 1 comment to a form, they press the browser back button and the data that they just submitted appears and has to press the browser back button again A user adds 2 comments to a post, and they press the browser back button and they are on the same page with the last form submission data. They press the browser back button again and they are on the first form submission data. And so on.... I know that we can use a redirect call to the same or different page, but the comments need to update once submitted, and even then the data is still cached. Is there a way to have the user press the browser back button once and it will bring them back to … -
CSRF verification failed when used csrf_token and CSRF_TRUSTED_ORIGINS
I try to change my profile but when i subbmit my form, it shows CSRF verification failed even when i used csrf_token and CSRF_TRUSTED_ORIGINS. Here is my models: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=200) avatar = models.ImageField(default='static/images/default.jpg', upload_to='static/images') @classmethod def create(cls, authenticated_user): profile = cls(user=authenticated_user, name= authenticated_user) # do something with the book return profile def __str__(self): return self.user.username My view: @login_required def profile(request): """Show profile""" # profile = UserProfile.objects.get(id= request.user) profile = UserProfile.objects.get(user=request.user) if request.method != 'POST': # No data submitted; create a blank form. form = UserProfileForm(instance=profile) else: # POST data submitted; process data. form = UserProfileForm(instance=profile, data= request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('base:index')) context = {'profile': profile} return render(request, 'users/profile.html', context) My template: {% if user.is_authenticated %} <p>Thong tin nguoi dung:</p> <a>Ten nguoi dung: {{profile.name}}</a> <p>Anh dai dien: <img src="{{profile.avatar.url}}" alt=""></p> <form action="{% url 'users:profile'%}" method="post"> {% csrf_token %} <input type="hidden" name="csrfmiddlewaretoken"> <p> <label for="id_name">Name:</label> <input type="text" name="name" maxlength="200" required="" id="id_name"> </p> <p> <label for="id_avatar">Avatar:</label> <input type="file" name="avatar" accept="image/*" id="id_avatar"> </p> <button name="submit">save changes</button> </form> {% else %} {% endif %} How can i sumit my form ? -
How can I save the username in the database as an email?
I want a signup page with 3 fields (email, password and repeat password). My goal is that when the user enters the email address, it is also saved in the database as a username. I would be super happy if someone could help me, I've been sitting for x hours trying to solve this problem. Thanks very much! enter code here models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() views.py class ActivateAccount(View): def get(self, request, uidb64, token, *args, **kwargs): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.profile.email_confirmed = True user.save() login(request, user) messages.success(request, ('Your account have been confirmed.')) return redirect('login') else: messages.warning(request, ('The confirmation link was invalid, possibly because it has already been used.')) return redirect('login') token.py from django.contrib.auth.tokens import PasswordResetTokenGenerator import six class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.profile.email_confirmed) ) account_activation_token = AccountActivationTokenGenerator() forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=254, help_text='Enter a valid email address') class Meta: model = User fields = [ 'password1', 'password2', ] -
Django App Engine deployment stops responding after 5 or 6 requests
I have been fighting this for a while now. Setup: I have Django 4 application running on Google App Engine (Standard) connected to Cloud SQL. Issue: I will load a page, and either refresh it 5 (ish) times or load 5 (ish) different pages. Then the application just stops responding. Observations: No errors are thrown. I have looked at the metrics and it doesn't appear anything is off. When I go to the instances page, they say they are "restarting" but they just are frozen there for many many minutes. Things I have tried: Manual, Basic, and Automatic Scaling Warmup requests Larger instance sizes Higher scaling thresholds Non-zero min instance sizes None of these items have changed the number of requests it takes to freeze the server. I have run the same server locally and it does not stop responding. Thanks people you make the world go round! -
Integrity error raised while creating custom id in django model
I tried to create auto incrementing custom id using the below code in models.py ` from django.db import models from phonenumber_field.modelfields import PhoneNumberField from django.contrib.auth.models import User from django.db.models import Max # Create your models here. status_choice = [("Pending","Pending"),("Fixed","Fixed"),("Not Fixed","Not Fixed")] class bug(models.Model): id = models.CharField(primary_key=True, editable=False, max_length=10) name = models.CharField(max_length=200, blank= False, null= False) info = models.TextField() status = models.CharField(max_length=25, choices=status_choice, default="Pending") fixed_by = models.CharField(verbose_name="Fixed by/Assigned to", max_length=30) phn_number = PhoneNumberField() user = models.ForeignKey(User, on_delete= models.CASCADE) created_at = models.DateTimeField(auto_now_add= True) updated_at = models.DateTimeField(auto_now= True) screeenshot = models.ImageField(upload_to='pics') def save(self, **kwargs): if not self.id: max = bug.objects.aggregate(id_max=Max('id'))['id_max'] self.id = "{}{:03d}".format('BUG', int(max[3:]) if int(max[3:]) is not None else 1) super().save(*kwargs) While adding a record the below error is shown. IntegrityError at /upload/ null value in column "created_at" violates not-null constraint DETAIL: Failing row contains (BUG009, test21, Fixed, test21, +919999999999, 1, null, 2022-11-18 13:55:09.68181+00, pics/between_operation_02WVLVz.png, test21). Tried to generate custom for the model such as BUG001, BUG002 etc. Can anyone give a suitable solution? -
Get the last record by id in Django Serializer not working properly
I am trying to get the last recorded ID in ActiveSession class. I have tested the below view and it is showing the normal results in normal page but when I try to implement the same to my API i keep getting 'ActiveSession' object is not iterable Here is the model: class ActiveSession(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) log = models.ManyToManyField(Log, related_name='savedlogs') Here is the serializers.py class ActiveSessionSerializer(serializers.ModelSerializer): class Meta: model= ActiveSession fields = '__all__' Here is the api.views @api_view(['GET']) @permission_classes([AllowAny]) def getActiveSession(request, **kwargs): user = get_object_or_404(User, username=request.user) print(user) last_active_session = ActiveSession.objects.filter(user=user).latest('id') serializer = ActiveSessionSerializer(last_active_session, many=True) print(serializer) return Response(serializer.data) here is the traceback: Traceback (most recent call last): File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\views\generic\base.py", line 103, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\User\Desktop\Project\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\rest_framework\decorators.py", line 50, in handler return func(*args, **kwargs) File "C:\Users\User\Desktop\Project\api\views.py", line 67, in getActiveSession return Response(serializer.data) … -
Django IntegrityError: NOT NULL constraint failed with NULLABLE field
When trying to create a superuser in Django, I'm getting the error: django.db.utils.IntegrityError: NOT NULL constraint failed: b3ack_investoruser.watchlist I have a custom user and, the only custom field IS NULLABLE: class InvestorUser(AbstractUser): id = models.AutoField(primary_key=True) watchlist = models.JSONField(default=None, blank=True, null=True) manage.py has: AUTH_USER_MODEL = 'b3ack.InvestorUser' admin.py has: from django.contrib import admin from .models import InvestorUser # Register your models here. admin.site.register(InvestorUser) I have tried python3 manage.py sqlflush I have redone all my migrations. I have deleted previous migrations. None of that works. -
What side effects will come from overriding a custom model manager's create() method?
I am implementing custom model managers, and it looks like the rest_framework by default calls the create() method of a model manager from within its serializer to create a new object. To avoid creating custom views when using a custom model manager, it seems like I could just override the create() method of my custom model manager, and implement standard ViewSets without any customization, but I don't fully understand what side-effects, if any, this will cause. Do I have to call super().create() within the overridden function to get other pieces of django to behave properly? I cannot find anywhere in the django documentation about overriding a custom model manager's create() method, which leads me to think they did not consider it as a use case, and there may be unintended consequences. Is this the case? Why does the standard recommendation seem to be to create a new create_xxx method inside the custom model manager? (i.e. creating a custom user model manager) -
Django manage.py migrate errors
I've been working on a project for CS50-Web for a while now and I was changing some of my models trying to add a unique attribute to some things. Long story short it wasn't working how I wanted so I went back to how I had it previously and now something is wrong and I can get it to migrate the changes to the model. I don't understand what to do because it was working fine before. Please can someone help I so frustrated and annoyed that I've broken it after so many hours of work. Sorry I know this error code is long but I don't know which part is important. Error code `Operations to perform: Apply all migrations: admin, auth, contenttypes, network, sessions Running migrations: Applying network.0019_alter_follower_user...Traceback (most recent call last): File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\sqlite3\base.py", line 416, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: new__network_follower.user_id The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\caitw\Documents\GitHub\CS50-Web\Project-4-Network\project4\manage.py", line 21, in main() File "C:\Users\caitw\Documents\GitHub\CS50-Web\Project-4-Network\project4\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management_init_.py", line 425, in execute_from_command_line utility.execute() File "C:\Users\caitw\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management_init_.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) … -
"DateTimeField %s received a naive datetime (%s)
'2022-11-11' this is the input value getting from the front end, RuntimeWarning: DateTimeField PaymentChart.date received a naive datetime (2022-11-18 00:00:00) while time zone support is active. this is the error that coming paydate = datetime.datetime.strptime(date,'%Y-%m-%d').isoformat() this is how i tried to convert the date, and not working, i got this error before, and i added 'tz=datetime.timezone.utc' , it was workin fine then offer.expiry=datetime.datetime.now(tz=datetime.timezone.utc)+datetime.timedelta(days=28) but how can i add tz in strptime ?? -
Django admin date time helpers missing
I have a model that includes a datetimefield... # Create your models here. class BroadcastNotification(models.Model): message = models.TextField() broadcast_on = models.DateTimeField() sent = models.BooleanField(default=False) class Meta: ordering = ['-broadcast_on'] In the admin pages the helpers for that field have gone away. I don't know what I did to cause it as I didn't test everything after every change. I did do collectstatic fairly recently if that might be the cause. -
Django - How to compare different models with same foreign key
I'm really stuck in how to do this and appreciate the help. I have three models, two of them shares the same foreign key field: class AccountsPlan (models.Model): code = models.CharField(max_length=7, unique=True,) name = models.CharField(max_length=100, unique=True,) class Planning (models.Model): accountplan = models.ForeignKey(AccountsPlan, on_delete=models.PROTECT) month = models.DateField() amount = models.DecimalField(max_digits=14, decimal_places=2,) class Revenue (models.Model): accountplan = models.ForeignKey(AccountsPlan, on_delete=models.PROTECT) receipt_date = models.DateField() amount = models.DecimalField(max_digits=14, decimal_places=2,) And I have this view that annotates the sum for each model by the foreign key name with a form that filters by date: def proj_planning(request): form = ProjectionFilterForm(request.POST or None) # some definitions for the form planned = Planning.objects.values('accountplan__name').annotate(Sum('amount')).order_by('accountplan__code').filter( month__range=[start_date, planned_end_date]) done = Revenue.objects.values('accountplan__name').annotate(Sum('amount')).filter( receipt_date__range=[start_date, end_date],).order_by('accountplan__code') if request.method == 'POST': planned = Planning.objects.values('accountplan__name').annotate(Sum('amount')).order_by( 'accountplan__code').filter(month__range=[start_date, planned_end_date], accountplan__name__icontains=form['accountplan'].value()) done = Revenue.objects.values('accountplan__name').annotate( Sum('amount')).filter(receipt_date__range=[start_date, end_date], accountplan__name__icontains=form['accountplan'].value()) comp_zippedlist = zip(planned, done) return render(request, 'confi/pages/planning/proj_planning.html', context={ 'form': form, 'list': comp_zippedlist, }) The code kinda works (it doesn't throw any errors), but the thing is, I will never have an exact amount of data for each model. For example: if I have 6 different records in the Planning model, but only 4 records in the Revenues model, the zipped list will only show the 4 records in the Revenues and not the … -
Axios POST method with React shows as Anonymous user and CORS error in Django Backend
I have been succesfully using GET methods with Axios while the logged in user information is succesfully transmitted to backend with the following code : await axios({ method: 'get', url: BASE_BACKEND_URL + `/project/` + project_uuid + `/`, data: {}, headers: { 'Content-Type': 'application/octet-stream' }, withCredentials: true, }) class ProjectView(APIView): def get(self, request, uuid): logging.info("ProjectManifest GET begin") user = request.user print(user) When I use a similar code with the POST API call of the same function, Django backend shows the request has been requested by an anonymous user instead of the logged in user. The code for the POST command is below: await axios({ method: 'post', url: BASE_BACKEND_URL + '/project/' + project_uuid + '/', data: { project_uuid : projectJSON }, headers: { 'Content-Type': 'application/json', }, withCredentials: true, }) class ProjectView(APIView): def post(self, request, uuid): logging.info(f"ProjectManifest POST begin: {request.user}") How can I make the react axios post call to work properly with Django backend ? -
Django-filter pagination only the first search filed failed
I'm using django-filter with pagination, as long as the search filed is in the first place in filter.py -> fields = ['name_procss','typeLevel'] list, the pagination for filter of that filed will not work. fitler.py: import django_filters from MyCore.models import MyRunStats class MyRunStatsFilter(django_filters.FilterSet): def gen_choice(self,filed): return tuple((l, l) for l in list(MyRunStats.objects.exclude(**{filed: None}).values_list(filed, flat=True).distinct())) name_procss = django_filters.ChoiceFilter(label='Process',choices=tuple,null_label='None',null_value='null') typeLevel = django_filters.ChoiceFilter(label='Message Type',choices=tuple,null_label='None',null_value='null') class Meta: model = MyRunStats fields = ['name_procss','typeLevel'] def __init__(self, *args, **kwargs): super(MyRunStatsFilter, self).__init__(*args, **kwargs) self.filters['name_procss'].extra['choices'] = self.gen_choice('name_procss') self.filters['typeLevel'].extra['choices'] = self.gen_choice('typeLevel') Views.py def runstat_hist_view_render(request): all_obj = MyRunStats.objects.all().order_by('-create_dttm') hist_filter = MyRunStatsFilter(request.GET, queryset=all_obj) paginator= Paginator(hist_filter.qs[:57], 20) page = request.GET.get('page') try: response = paginator.page(page) except PageNotAnInteger: response = paginator.page(1) except EmptyPage: response = paginator.page(paginator.num_pages) context = {'response': response,'filter': hist_filter} return render(request, 'My/My_runstat_hist.html',context) html: <form method="get" > {{ filter.form}} <button type="button" onclick="submitFilter()" id="hist-search-button" >Search Message</button> </form> {% for item in response %} <nav> <ul class="pagination"> {% if response.has_previous %} <li><a href="?page=1&{{ request.get_full_path }}">&laquo; First</a></li> <li ><a href="?page={{ response.previous_page_number }}&{{ request.get_full_path }}">Previous</a></li> {% else %} <li><a href="#">Previous</a></li> {% endif %} {% for num in response.paginator.page_range %} {% if response.number == num %} <li><a href="?page={{num}}&{{ request.get_full_path }}">{{num}}</a></li> {% elif num > response.number|add:'-3' and num < response.number|add:'3' %} <li><a href="?page={{num}}&{{ request.get_full_path }}">{{num}}</a></li> {% endif %} {% endfor … -
Connecting html with css using django
This is the html file that i'm trying to add a star rating for book_detail.html {% extends "base.html" %} {% load static %} {% block title %} Block Detail Page {% endblock title %} {% block sidenav %} {% for item in item_list %} <li> <a href="{{ item.link }}"> {{ item.item }} </a> </li> {% endfor %} {% endblock sidenav %} {% block content %} <h1 align="center"> Book Detail </h1> <table align="center" border="2" width="400"> <tr> <td> {{ book.name }} </td> </tr> <tr> <td> <img src="{% static book.pic_path %}" width="100"> </td> </tr> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <tr> <td> {{ book.username }} <div id="full-stars-example"> <div class="rating-group"> <input class="rating__input rating__input--none" name="rating" id="rating-none" value="0" type="radio"> <label aria-label="No rating" class="rating__label" for="rating-none"><i class="rating__icon rating__icon--none fa fa-ban"></i></label> <label aria-label="1 star" class="rating__label" for="rating-1"><i class="rating__icon rating__icon--star fa fa-star"></i></label> <input class="rating__input" name="rating" id="rating-1" value="1" type="radio"> <label aria-label="2 stars" class="rating__label" for="rating-2"><i class="rating__icon rating__icon--star fa fa-star"></i></label> <input class="rating__input" name="rating" id="rating-2" value="2" type="radio"> <label aria-label="3 stars" class="rating__label" for="rating-3"><i class="rating__icon rating__icon--star fa fa-star"></i></label> <input class="rating__input" name="rating" id="rating-3" value="3" type="radio" checked> <label aria-label="4 stars" class="rating__label" for="rating-4"><i class="rating__icon rating__icon--star fa fa-star"></i></label> <input class="rating__input" name="rating" id="rating-4" value="4" type="radio"> <label aria-label="5 stars" class="rating__label" for="rating-5"><i class="rating__icon rating__icon--star fa fa-star"></i></label> <input class="rating__input" name="rating" id="rating-5" value="5" type="radio"> </div> </div> </td> </tr> </table> {% … -
Problems filtering columns that have many rows with a None value(Django database)
I am filtering a certain column in PostgreSQL database. n = Database.objects.values(column).count() for i in range(0, n): name = list(Database.objects.all().values_list(column, flat=True))[i] There are 105 lines. From line 86 onwards the values are None. However, when querying line 43, the returned value is None, although in the database this line is filled with a value. Strangely, when I populate lines 86 onwards, the query on line 43 is correct and does not return a None value. I want to know if there is any problem when filtering columns that have many None values and why this might be happening -
web form where you can upload a pdf file and it gets translated into visible text
I'm trying to figure it out how to do it with python and Django or flask. I want to make a website where you can upload a pdf file and it gets translated into visible text, and I need to use specific keywords from pdf file and assign them with translation of my own words and then display it to the user. Is something like that possible with python?