Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Open the Client's Desktop Application using a button Click from Browser - Python/HTML
I want to open the desktop application(For eg: Notepad/Powerpoint/Putty). Attaching an image of how it works on sharepoint. Example image of how Microsoft Teams gets opened on the Click of the button is attached. I need this exact replica. On Clicking Open Microsoft Teams. Teams opens the meeting. Similarly I want to open an already installed desktop app on client's System. Similarly, I also want to open the Desktop Application of my company which is already installed. I used Os.Popen module of Python which works locally but, when hosted does not work. Note: OS and webbrowser module were tried. -
Spatial join in Django
I am trying to do a spatial join (as explaind here) using PostGIS within Django. The Django spatial lookups do not help. My best clue is to use custom SQL but I would really prefer to keep using a QuerySet query. In plain english my query would be: Select all estates which contains at least one building with type "heavy" Here are my two models: class Building(models.Model): type = models.CharField(max_length=255, null=True, db_index=True) footprint = models.IntegerField(null=True, blank=True) perimeter = models.PolygonField(null=True, spatial_index=True) class Estate(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE) area = models.IntegerField(null=True, validators=[MinValueValidator(1)]) perimeter = models.PolygonField(null=True, validators=[estate_val.perimeter], spatial_index=True) Is there any way to do something like: estates = Estate.objects.filter(CUSTOM_JOIN_FILTER) -
Django set User for ForeignKey field in another model
I have a model like this: class File(models.Model): id = models.UUIDField(primary_key = True, default = uuid.uuid4, editable = False, unique=True) name = models.CharField(max_length=500) created_at = models.DateTimeField(auto_now_add=True) size = models.IntegerField(default=0) user = models.ForeignKey(User, on_delete=models.CASCADE) I'm using Django rest framework so, I created a view for this model: class FileCreate(CreateAPIView): def get_queryset(self): return File.objects.all() serializer_class = FileSerializer and I need to set user automatically for File object in view or serializer, but I don't know how... I want, when one user sends a request to create a file, "user" field in the file object automatically add request.user. -
I have this issue when registering user FileNotFoundError at /register/ [Errno 2] No such file or directory: '/media/default.jpg' on ubuntu linux serv
Please any help on how to solve this i know sure this is where the issue comes when i go directly to the url path http://ip:8000/media/default.jpg i can see the image. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' #resize the image after been save() def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.url) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.url) -
What is the difference between objects.create() and instance.save()?
Is there any difference in making new record in database between MyModel.objects.create() and MyModel().save()? -
How can I save created pdf from pdfkit in django model?
Here I render my template to string and use the pdfkit to convert to pdf 'myPdf'. How can I save this created pdf to model? I tried this but it doesn't work. html = render_to_string('somehtmlfile.html',context=context) pdfkit.from_string(html, 'myPdf.pdf') f = open('myPdf.pdf') pdf = File(f) if pdf: data = {'upload': pdf} consent_serializer = CreatePdfSerializer(data=data) if CreatePdfSerializer.is_valid(raise_exception=True): CreatePdfSerializer.save() Here is model class CreatePdf(models.Model): upload = models.FileField('file_path',upload_to='upload_directory' max_length=1023) Serializer class CreatePdfSerializer(ModelSerializer): class Meta: model = models.CreatePdf fields = '__all__' -
Is possible add a subquery with anothers relationships in django orm annotate
I have a View to show my total stock by "point of sale". My problem is a new table added and I have put a more field in my View (counting total of reserved products). My actual scenario: Tables class SalePoint(models.Model): location = models.CharField(max_length=200, verbose_name='Local') [...] class Box(models.Model): sale_point = models.ForeignKey( [...] related_name='boxes', [...] ) product = models.ForeignKey( [...] related_name='boxes', [...] ) amount = models.PositiveSmallIntegerField() capacity = models.PositiveSmallIntegerField() class Product(models.Model): name = models.CharField() sku = models.CharField() View SalePointStockViewSet(viewsets.ModelViewSet): def list(self, request): queryset = ( SalePoint.objects.values( 'location', 'boxes__product__name' ).annotate( total_amount=Sum('boxes__amount'), total_capacity=Sum('boxes__capacity'), ) .order_by('location', 'total_amount') ) return Response(queryset) As I had said, my view works fine. I need to include a new field "reserved" in my queryset. Reserved is a sum of total ordered products with status "waiting" from this table: class Order(models.Model): WAITING = 'WAIT' DELIVERED = 'DELI' STATUS_CHOICES = [ (WAITING, 'Waiting'), (DELIVERED, 'Delivered'), ] sale_point = models.ForeignKey( [...] related_name='orders', [...] ) product_sku = models.CharField() status = models.CharField( [...] choices=STATUS_CHOICES, ) What am I thinking I'm thinking if it's possible to add the "reserved" field and fill it with a "subquery". The problem is that I have to filter the product by "sku". I don't know if this would be … -
Django admin filter is not working toexclude after filtering (Help Needed)
Hi with this code i can not exclue after filtering can any one help me def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "company_names_uuids": kwargs["queryset"] = models.CompanyName.objects.filter(country_code== request._user_country) and models.CompanyName.filter((company_names__exists, country_code__exists) == None).exclue() return super().formfield_for_foreignkey(db_field, request, **kwargs) -
how to take views.py file from app to project/urls.py file
I created a project in django.in that from app/views.py i have to call the functions to mention in the project/urls.py .But its not accepting. mentioning the names from app/views.py to project/urls.py -
What is the difference between POST.get("..") and POST[".."] in django
I am beginner to django and i would like to know the difference between POST.get("..") and POST[".."]. def home(request): username=request.POST.get("username") return render(request,{"username":username}) ############ def home(request): username=request.POST["username"] return render(request,{"username":username}) -
Django - JWT + Brute force protection
Does anyone have boiler plate code for djangorestframework-simplejwt with brute force protection? I see they created 'django-defender' package (same author) but with custom setup path('login/', jwt_views.TokenObtainPairView.as_view(serializer_class=views.CustomTokenObtainSerializer)), it doesnt work, does anyone have minimal setup code with custom token obtainer? thank you -
field app.Vendor.created_by was declared with a lazy reference to 'auth.abstractbaseuser', but app 'auth' doesn't provide model 'abstractbaseuser'
hello i recently changed my user model to abstract base user and now i cant add any kind of OneToOneField models iam getting two different errors the other error : vendor.NewUser.created_by: (fields.E300) Field defines a relation with model 'AbstractBaseUser', which is either not installed, or is abstract. this are my models models.py from os import name from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class CustomAccountManager(BaseUserManager): def create_superuser(self, email, user_name, first_name, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.') return self.create_user(email, user_name, first_name, password, **other_fields) def create_user(self, email, user_name, first_name, password, **other_fields): if not email: raise ValueError(_('لطفا یک ادرس ایمیل بدهید')) email = self.normalize_email(email) user = self.model(email=email, user_name=user_name, first_name=first_name, **other_fields) user.set_password(password) user.save() return user def get_profile_image_filepath(self,filename): return f'uploads/{self.pk}/{"profile.png"}' def get_default_profile_image(): return "uploads/profiled.png" class NewUser(AbstractBaseUser, PermissionsMixin): email = models.CharField(_('ایمیل'),max_length=255 ,unique=True) user_name= models.CharField(_('نام کاربری'),max_length=255,unique=True) first_name = models.CharField(_('نام مسکن'),max_length=255 , blank=True) phone = models.CharField(_('شماره همراه'),max_length=50, blank=True) تاریخ_ثبت_نام = models.DateTimeField(verbose_name='تاریخ_ثبت_نام', auto_now_add=True) اخرین_ورود = models.DateTimeField(verbose_name='اخرین_ورود', auto_now=True) about = models.TextField(_( 'درباره شما'), max_length=500, blank=True) created_by = models.OneToOneField(AbstractBaseUser, blank=True,related_name="vendor",on_delete=models.CASCADE) … -
i am trying to fetch top performing city in django through foreign key - Django
here i am trying to fetch top performing city from sql where they are connected through forienkey. Models class Orders(models.Model): id = models.AutoField(primary_key=True) customer = models.ForeignKey(Customers , on_delete=models.DO_NOTHING , blank = True , null = True) product = models.ForeignKey('Products' , on_delete=models.DO_NOTHING ) class Customers(models.Model): id = models.AutoField(primary_key=True) username = models.CharField(max_length =100 , blank=True) date_created_gmt = models.DateField(blank=True) city = models.CharField(max_length=50 ,blank=True) so basically orders table have multiple orders with product_id and customer_id as foriegnkey. customer table have each customers address with city , pincode etc. so from this i need top performing city. city names which have highest orders in descending order. your help will appriciate. thank you -
Inclusion_tag doesn't display data in other models on template
I was follow to a old courses Udemy and I try create a project had 2 app( group & posts) and just found out that you can use: from django import template register = template.Library() To allow link models app to another app. In the old courses it just add in models.py and create tag in post_list.html to show what group you join and all group but don't create templatetags folder and how it work. Even when I check the sample it don't had any thing. So I was search gg try build it by myself, but it doesn't show anything. Can you check it. Thank App groups models.py: class Group(models.Model): name = models.CharField(max_length=235, unique=True) slug = models.SlugField(allow_unicode=True,unique=True) descripsion = models.TextField(blank=True,default='') descripsion_html = models.TextField(editable=False,default='',blank=True) member = models.ManyToManyField(User,through='GroupMember') def __str__(self): return self.name def save(self,*args, **kwargs): self.slug =slugify(self.name) self.descripsion_html = misaka.html(self.descripsion) super().save(*args, **kwargs) def get_absolute_url(self): return reverse("groups:single", kwargs={"slug": self.slug}) class GroupMember(models.Model): group = models.ForeignKey(Group,related_name='memberships',on_delete=models.CASCADE) user = models.ForeignKey(User, related_name='user_groups',on_delete=models.CASCADE) def __str__(self): return self.user.username In templatetags group_tags.py: from django import template from ..models import Group,GroupMember register = template.Library() @register.inclusion_tag('clonemedia/posts/templates/posts/post_list.html') def get_other_group(): group_members = GroupMember.objects.all() other_groups = Group.objects.all() return {'other_group':other_groups, 'group_member':group_members } In template post_list.html: {% load group_tags %} <h5 class='title'> Your Groups</h5> <ul class='list-unstyled'> … -
django next url parameter
I am using a custom Login View and a custom login page. What I am struggling with is the next parameter that I want to use so if there is the next parameter in the url then the user is being redirected to the previous page. As you can see in the code below I am using django-crispy-forms and django-axes. The problem is that I am able to successfully redirect users to the homepage but I cannot access any data that is visible for logged-in users (all views are restricted for logged-in users) such as user email, and content. Moreover, when I try to click on any hyperlink Django is automatically redirecting to the login page. When I try to access a page manually, for instance, http://127.0.0.1:8000/articles it redirects me to http://127.0.0.1:8000/accounts/login/?next=/articles/ which gives me Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/?next=/articles/ views.py class UpdatedLoginView(LoginView): form_class = LoginForm template_name = 'user/login.html' redirect_field_name='main/homepage.html' def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): if 'next' in request.POST: return redirect(request.POST.get('next')) else: return(redirect('homepage')) else: return render(request, self.redirect_field_name, {'form': form}) class ArticleListView(LoginRequiredMixin, ListView): template_name = 'articles/ArticleListView.html' model = Article paginate_by = 6 queryset = Article.objects.filter(status=1) def get_context_data(self, **kwargs): context = super(ArticleListView, … -
Using template function to each member of array and get it back to array
I have list in django template {{mylist}} each items of mylist has string. What I want to do is like this. {% for i in mylist %} {set i = (i | truncatechars:20)} {% endif%} {{mylist | join:","}} Using truncatechars for each member and then join. It can be in view.py but I want to this in template. Is it possible?? -
DRF endpoint returns weirdly serialized object although it is fetch correctly in the view
So I'm using Django REST authand dj-rest-auth as authentication backend for my React app. In the view it seems that it grabs the correct instance of the logged in user, but it doesn't reflect that in the response. Also if I print fields of that instance it returns the wrong data, the serializer instance however looks like it holds the correct object to serialize...hm # views.py class UserDetail(APIView): """ Retrieve a User instance """ def get(self, request): print('Header Token: ' + str(request.META['HTTP_AUTHORIZATION'])) print('request.user: ' + str(request.user)) try: user_profile = UserProfile(user=request.user) print('user_profile: ' + str(user_profile)) print('user_profile.company: ' + str(user_profile.company)). # Why is this none? serializer = UserProfileSerializer(user_profile) print('serializer: ' + str(serializer)) # looks like the instance is correct though.. print('serializer.data: ' + str(serializer.data)) return Response(serializer.data) except UserProfile.DoesNotExist: raise Http404 Returns and Postman returns But the data should be: # models.py class UserProfile(models.Model): """ Extends Base User via 1-1 for profile information """ # Relations user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True) # Roles is_ta = models.BooleanField(default=False) # indicates if user is part of TA department def __str__(self): return F'{self.user.first_name} {self.user.last_name}' @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) instance.userprofile.save() # serializers.py class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = … -
DRF: convert a list of string into seperate objects and save it into the database(postgres)
My query is that I have a list of string from the post request which were separated by 2 newlines ['hdhsjfhjfsjhj hsjfh skjh jsh shjsfhjs', 'ahfjjfhjdfgdjdkfgajkfgakjgaj', 'jhdsjfhdgjfhdghjdgk'] what i want is that for each of this string a new object is created in the database, so that when i make a get request it shows like ` [{ "id": 11, "para": "Loremdfhskjfsjfjsndjfjksbkvbksbvjsbvkjkbvkbsjbvjsjbvjsjbvjbsfbvbskbvsbhvsbvnlkjbjkvjbvjskbvosdbvnsvisuo sdbvhsvbksubvkusubvukbjvbjkbvkjbjskdbvkjsbdhvbjsdvjkbsdjvbjksbvjkbdjkvbjksbvjkbsjkvbjsbvjkbskj shvjksdhjvbsdbvjkbskdjbvjksjdkbvbskjvbkbkjvbkjsdbjvkbsjkdvbjksdbjvkbsdjkbvjksdbvkjbsjdkbvjkbdskjvbjksdbjvbjskdb." }, { "id": 12, "para": "Loremdfhskjfsjfjsndjfjksbkvbksbvjsbvkjkbvkbsjbvjsjbvjsjbvjbsfbvbskbvsbhvsbvnlkjbjkvjbvjskbvosdbvnsvisuo sdbvhsvbksubvkusubvukbjvbjkbvkjbjskdbvkjsbdhvbjsdvjkbsdjvbjksbvjkbdjkvbjksbvjkbsjkvbjsbvjkbskbhjsdgfgudskfhakfgvkfasgkvfugaskubvksjbj shvjksdhjvbsdbvjkbskdjbvjksjdkbvbskjvbkbkjvbkjsdbjvkbsjkdvbjksdbjvkbsdjkbvjksdbvkjbsjdkbvjkbdskjvbjksdbjvbjskdb." }, { "id": 13, "para": "Loremdfhskjfsjfjsndjfjksbkvbksbvjsbvkjkbvkbsjbvjsjbvjsjbvjbsfbvbskbvsbhvsbvnlkjbjmsknvsjbvjk skvjbvjskbvosdbvnsvisuo sdbvhsvbksubvkusubvukbjvbjkbvkjbjskdbvkjsbdhvbjsdvjkbsdjvbjksbvjkbdjkvbjksbvjkbsjkvbjsbvjkbskbhjsddjjkl sgsdlkfhsdljfjslsl dsfsshlghjshlkg skdjgkldjsk gdsklgj klsdjgk sdkgj ksdj gkjsdk skdj gklsjdkggfgudskfhakfgvkfasgkvfugaskubvksjbj shvjksdhjvbsdbvjkbskdjbvjksjdkbvbskjvbkbkjvbkjsdbjvkbsjkdvbjksdbjvkbsdjkbvjksdbvkjbsjdkbvjkbdskjvbjksdbjvbjskdb." }] my viwes.py @api_view(['GET', 'POST']) def paralist(request): """ List all the paraGraphs added till now to the database or add new paragraphs one by one """ if request.method == 'GET': allpara = para.objects.all() serializer = paraSeriealizer(allpara, many=True) return Response(serializer.data) if request.method == 'POST': todata = request.data['para'].split("\n\n\n") print(todata) serializer = paraSeriealizer(data=todata, many=True) if serializer.is_valid(): print(serializer.data) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) my seriealizer.py class paraSeriealizer(serializers.ModelSerializer): class Meta: model = para fields = '__all__' models.py class para(models.Model): para = models.TextField() -
Django ORM equivalent to left exclusive JOIN
Relatively new to Django and I have the following models in my django (3.2) project: class projectsA(models.Model): projectID_A = models.BigIntegerField(primary_key=True) project_name_A = models.TextField(blank=True, null=True) project_desc_A = models.TextField(blank=True, null=True) projektID_B = models.ForeignKey('projectsB', models.DO_NOTHING, db_column='projektID_B', blank=True, null=True, db_constraint=False) class Meta: managed = False db_table = 'projectsA' class projectsB(models.Model): projectID_B = models.BigIntegerField(primary_key=True) project_name_B = models.TextField(blank=True, null=True) project_desc_A = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'projectsB' I want to get all projects from projectsA which are not in projectsB. The SQL equivalent would be SELECT * FROM projectsA a LEFT JOIN projectsB b on a.projektID_B = b.projectID_B WHERE b.projectID_B is null I have tried with .exclude or .select_related() and several other approaches, but cannot find a solution for this scenario. Thanks in advance. -
Get a result and the filter only has an associated field [Django-filter]
I want to create django-filter where when users search for a book by title or content they get a result and the filter only has an associated field. And also in each field there is a number of containing books with numbers. For example,I'm looking for a book about nature, I write "nature" in the search field in the filter, and then I click "Search". I get a result and a filter with the corresponding fields and results (for example, the filter has the following values - language filter: English (54), German (20) ; Publisher: Oxford (100), Seven House(21) etc.) I want to create a django filter where when users search for a book by title or content they get a result and the filter only has an associated field. And also in each field there is a number of containing books with numbers. For example, I'm looking for a book about nature, I write "nature" in the search field in the filter, and then I click "Search". I get a result and a filter with the corresponding fields and results (for example, the filter has the following values - language filter: English (54), German (20) ; Publisher: Oxford (100), … -
Generate graphene types dynamically
I am sure whether this can be achieved or not. It would be very great if someone suggests any alternative to this or any other supporting packages to achieve this. Below is my code. class DynamicTypeInput(graphene.InputObjectType): object_type = graphene.String() object_value = graphene.String(required=False) # Can we make this required=True if object_type == "requesting_value" class WidgetInput(graphene.InputObjectType): title = graphene.String() dynamic_object_type = graphene.Argument(DynamicTypeInput, required=True) I tried using graphene-pydantic for generating graphene models but no use. Its throwing generalized error like TypeError: Input fields cannot be resolved. The input field type must be a GraphQL input type. Is there any way to achieve this with graphene itself? -
How To Parse form-data / multi-part in HTTP Request
How do I get the multipart section and parse it? b'POST /Hello/MyBrother HTTP/1.1\r\nUser-Agent: PostmanRuntime/7.29.0\r\nAccept: */*\r\nCache-Control: no-cache\r\nPostman-Token: e7051ceb-6859-47b6-bc19-82016a8b6316\r\nHost: 127.0.0.1:8 000\r\nAccept-Encoding: gzip, deflate, br\r\nConnection: keep-alive\r\nContent-Type: multipart/form-data; boundary=--------------------------468552134136252037791868\r\nContent-Length: 29 1\r\n\r\n----------------------------468552134136252037791868\r\nContent-Disposition: form-data; name="username"\r\n\r\nMahanBi\r\n----------------------------468552134136252037791868\r\n Content-Disposition: form-data; name="password"\r\n\r\nYayaya12345678\r\n----------------------------468552134136252037791868--\r\n' -
How to generate Token Authentication for for Already existing users table in my private database in Django REST API?
I have table users in my private database with username, password, email, status, creation_date, updated_date,... etc. with some rows of data. I want to generate Tokens for this users ? So i want to use my private database users table instead of Django db auth_users table for generations of tokens for username's present my private database. **idint(11) NOT NULL AUTO_INCREMENT,usernamevarchar(200) DEFAULT NULL,namevarchar(200) DEFAULT NULL,passwordvarchar(200) DEFAULT NULL,emailvarchar(100) DEFAULT NULL,statustinyint(1) DEFAULT 0 COMMENT '0=>active,1=>inactive,2=>delete',creation_datedatetime DEFAULT NULL,updated_datetimestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),last_logindatetime NOT NULL,created_byint(11) NOT NULL,is_sys_admintinyint(1) DEFAULT 0,is_agency_admintinyint(1) DEFAULT 0,is_adv_admintinyint(1) DEFAULT 0,is_pub_admintinyint(1) DEFAULT 0,is_bidder_admintinyint(1) DEFAULT 0,template_idint(11) DEFAULT -1,camp_list_filterstext DEFAULT NULL COMMENT 'Campaign Listing Page Filters',adv_list_filterstext DEFAULT NULL COMMENT 'Advertiser Listing Page Filters',agency_list_filterstext DEFAULT NULL COMMENT 'Agency Listing Page Filters',account_list_filterstext DEFAULT NULL COMMENT 'Account Listing Page Filters',user_list_filterstext DEFAULT NULL COMMENT 'User Listing Page Filters',template_list_filterstext DEFAULT NULL COMMENT 'Template Listing Page Filters',connection_list_filterstext DEFAULT NULL,adgroup_list_filterstext DEFAULT NULL COMMENT 'Adgroup Listing Page Filters',dashboard_list_filterstext DEFAULT NULL,report_list_filterstext DEFAULT NULL,report_timezonevarchar(200) DEFAULT 'UTC' COMMENT 'User Default Timezone',ad_list_filterstext DEFAULT NULL COMMENT 'Ads Listing Page Filters',segment_list_filters text DEFAULT NULL COMMENT 'Audience Segment Listing Page Filters', PRIMARY KEY (id`) ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1 ** -
How to create new collection datatabase after each scraping execution?
I have created a scrapping tool to crawl data from aliexpress website using python and selenium. This is my script in python : from selenium.webdriver.edge.options import Options from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium import webdriver from pymongo import MongoClient from time import sleep from lxml import html import pandas as pd import cssselect import pymongo import time def scrap(subject): start_time = time.time() options = Options() options.headless = True driver = webdriver.Edge(executable_path=r"C:\Users\aicha\Desktop\mycode\aliexpress_scrap\scrap\codes\msedgedriver",options=options) url = 'https://www.aliexpress.com/wholesale?trafficChannel=main&d=y&CatId=0&SearchText='+subject+'&ltype=wholesale&SortType=default&page={}' # baseurl = 'https://www.aliexpress.com' for page_nb in range(1, 5): print('---', page_nb, '---') driver.get(url.format(page_nb)) sleep(2) current_offset = 0 while True: driver.execute_script("window.scrollBy(0, window.innerHeight);") sleep(.5) # JavaScript has time to add elements new_offset = driver.execute_script("return window.pageYOffset;") if new_offset <= current_offset: break current_offset = new_offset sleep(3) tree = html.fromstring(driver.page_source) results = [] for product in tree.xpath('//div[@class="JIIxO"]//a'): title = product.xpath('.//h1/text()') if title: title = title[0] price = product.cssselect('div.mGXnE._37W_B span') price = [x.text for x in price] currency = price[0] price = ''.join(price[1:]) stars = product.xpath('.//span[@class="eXPaM"]/text()') if stars : stars = stars [0] else: stars = 'None' nb_sold = product.xpath('.//span[@class="_1kNf9"]/text()') if nb_sold: nb_sold = nb_sold[0] else: nb_sold = 'None' supl = product.xpath('.//a[@class="ox0KZ"]/text()') if supl: supl = supl[0] else: supl = 'None' ship_cost … -
Django : CSS file not loading
Css files not working, I am not sure about the reason, I have done everything as done in the tutorial. settings.py STATIC_DIR = BASE_DIR.joinpath('static') STATIC_URL = '/static/'; STATICFILES_DIR = [STATIC_DIR]; base_html <!DOCTYPE html> <html> {% load static %} <head> <title>BASE</title> </head> <link rel="stylesheet" href="{% static 'style.css' %}"> </link> <body> <ul> <li><a href="{% url 'index' %}">Django</a></li> <li><a href="{% url 'admin:index' %}"> Admin</a></li> <li><a href="{% url 'basic_app:register' %}">Register</a></li> {% if user.is_authenticated %} <li><a href="{% url 'logout' %}">Logout</a></li> {% else %} <li><a href ="{% url 'basic_app:user_login' %}" >Log in</a></li> {% endif %} </ul> {% block body_block %} {% endblock %} </body> </html> folder structure