Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Capturing Data of a User Visiting my website
How can I capture data of someone visiting my website via a shortened link? I want to be able to capture the OS, IP, divide ID etc. Would capturing the user agent string be the best option? What are some other ways? In my case I'm building a website with DJAGNO. -
Django-Ckeditor editor issues
I can't install Django CKEditor in virtual environment, I tried with pip install django-ckeditor. Where did the actual problem occurred? It's shown below error. Note: I used ckeditor before in a project, there worked perfectly. In my prvious project wherse I used ckeditor, I didn't create virtual environment. But in the current project I created virtual environment. error: ERROR: Exception: Traceback (most recent call last): File "D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\pip\_vendor\urllib3\response.py", line 438, in _error_catcher yield File "D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\pip\_vendor\urllib3\response.py", line 519, in read data = self._fp.read(amt) if not fp_closed else b"" File "D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 90, in read data = self.__fp.read(amt) File "c:\users\dcl\appdata\local\programs\python\python39\lib\http\client.py", line 455, in read n = self.readinto(b) File "c:\users\dcl\appdata\local\programs\python\python39\lib\http\client.py", line 499, in readinto n = self.fp.readinto(b) File "c:\users\dcl\appdata\local\programs\python\python39\lib\socket.py", line 704, in readinto return self._sock.recv_into(b) File "c:\users\dcl\appdata\local\programs\python\python39\lib\ssl.py", line 1241, in recv_into return self.read(nbytes, buffer) File "c:\users\dcl\appdata\local\programs\python\python39\lib\ssl.py", line 1099, in read return self._sslobj.read(len, buffer) socket.timeout: The read operation timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\pip\_internal\cli\base_command.py", line 167, in exc_logging_wrapper status = run_func(*args) File "D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\pip\_internal\cli\req_command.py", line 205, in wrapper return func(self, options, args) File "D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\pip\_internal\commands\install.py", line 339, in run requirement_set = resolver.resolve( File … -
ImportError: cannot import name 'url' from 'django.conf.urls' in packages
I have a project of migrating django web app from Django-3.2.14 to Django-4.0. Immediately after migration, when I run the server I get the error as shown in Console output. When I traced the changes, it traced to django-compat package, which was being called by django-background-tasks package. my_env is my virutal environment. We have latest version of django-compat, which is 1.0.15 and django-background-tasks, which is 1.2.5. Could you please look into this? Thank you in advance. Console: (myenv) D:\New_Folder\github\project\project_name>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "D:\New_Folder\github\myenv\lib\site-packages\compt\__init__.py", line 46, in <module> from django.conf.urls import url, include, handler404, handler500 ImportError: cannot import name 'url' from 'django.conf.urls' (D:\New_Folder\github\myenv\lib\site-packages\django\conf\urls\__init__.py) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Program Files\Python39\lib\threading.py", line 980, in _bootstrap_inner self.run() File "C:\Program Files\Python39\lib\threading.py", line 917, in run self._target(*self._args, **self._kwargs) File "D:\New_Folder\github\myenv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\New_Folder\github\myenv\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "D:\New_Folder\github\myenv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "D:\New_Folder\github\myenv\lib\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "D:\New_Folder\github\myenv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\New_Folder\github\myenv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\New_Folder\github\myenv\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() … -
DJ-Stripe metadata not attaching to product
I am following this guide: https://www.saaspegasus.com/guides/django-stripe-integrate/#contents I get to "Adding metadata to your Stripe objects" and am told to create a metadata.py file. It doesn't tell me where to import @dataclass and List from so I had to guess. The issue is that, moving forward from this point in the guide, the metadata does not print to my template but I can retrieve product information. I'm thinking this guide is missing or assuming I know stuff about metadata that is required to make it work. my metadata.py: from dataclasses import dataclass from pip import List from project.subscriptions import features @dataclass class ProductMetadata(object): """ Metadata for a Stripe product. """ stripe_id: str name: str features: List[str] description: str = '' is_default: bool = False PREMIUM = ProductMetadata( stripe_id='<prod id>', name='Premium', description='yerp', is_default=False, features=[ features.UNLIMITED_WIDGETS, features.LUDICROUS_MODE, features.PRIORITY_SUPPORT, ], ) features.py: UNLIMITED_WIDGETS = 'Unlimited Widgets' LUDICROUS_MODE = 'Ludicrous Mode' PRIORITY_SUPPORT = 'Priority Support' views: from django.shortcuts import render from djstripe.models import Product def pricing_page(request): context = { 'products': Product.objects.all() } return render(request,'subscriptions/pricing_page.html', context=context) urls: path('pricing_page/', view=pricing_page, name='pricing_page'), template: {% extends "base.html" %}{% load static socialaccount %} {% block content %} <h1>Plans</h1> <section> <p class="title">Pricing Plans</p> <div class="columns"> {% for product in products %} … -
Django: How to get all objects related to a model by another model?
I have 3 models: User, Course and Homework. Each course has some homework and some users(students). How can I have all homeworks of all courses a user is in? These are the models: class User(AbstractUser): # ... class Course(models.Model): students = models.ManyToManyField(User, blank=True, related_name='student_courses') # ... class Homework(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='course_homeworks') # ... -
Where to add udp socket initialization in django project
I am a newbie to python django framework. Currently i am working on a django project which listens to udp messages and act accordingly. Initially i initialized the socket and starts a thread to receives the messages on that socket in one of the views.py where it handles the request from URL. Now i have to make these initialization and starting the thread when the server is up. Which is the ideal place to put this piece of code ? I tried out so many places, i am facing an issue here. Whereever i put "python manage.py makemigrations" executes this code and gets stuck in receiveing the messages. I even tried in ready() method overridden in apps.py. This method also gets executed with makemigrations. Is there any way i can bypass makemigrations and initialze the sockets only during runserver ? -
Error while deploying application on heroku
I am getting an error while deploying app on heroku Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command heroku logs --tail Everything is working perfectly fine on heroku local here are some of settings that I did ALLOWED_HOSTS = ['0.0.0.0'] Any idea why am I getting this error -
Is this the correct way to get information from forign-key model Django
In the model declaration, I make property: @property def author(self): book_id = getattr(self, 'book_id') book = Book.objects.get(id=book_id) author_id = getattr(book, 'author_id') author = Author.objects.get(id=author_id) author_name = getattr(author, 'first_name') return author_name To get data on the front. It works. But how is this possible and how can it be done better? -
How to send data to a websocket from outside of consumer django channels
I'm trying to send data to a websocket from outside of the consumer so i did following: settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379)], }, }, } routing.py from django.urls import path from .consumers import CoinsListConsumer websocket_urlpatterns = [ path('ws/coins/', CoinsListConsumer.as_asgi()) ] asgi.py import os from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from apps.coins.routing import websocket_urlpatterns os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( websocket_urlpatterns, ) ) ) }) consumers.py class CoinsListConsumer(AsyncWebsocketConsumer): async def connect(self): logger.info('Websocket was connected.') await self.accept() async def disconnect(self, code): logger.warning('Websocket was disconnected.') pass async def receive(self, text_data=None, bytes_data=None): return await super().receive(text_data, bytes_data) well this is ok and when i go to a view... the websocket will connect very well but when i want to send data to the websocket. def send_data_to_websocket_coins_list_view(data: List[Dict]) -> None: """Send data to websocket coins list view """ async_to_sync(channel_layer.send)(json.dumps(data)) This did not work and raised following error TypeError: send() missing 1 required positional argument: 'message' Also in the documentation this is should work by following code async_to_sync(channel_layer.send)("channel_name", {...}) its also not worked and raise the following error AssertionError: message is not a … -
Want to design a promotion model in Django
Brand partner creates a plan a. Creates a plan in the database with planID, planName, amountOptions and tenureOptions, benefitPercentage (for example: 10), benefitType (cashback/extraVoucher) and any other attributes needed. Brand partner creates promotion for an existing plan a. Promotion can be limited in two ways i. By the number of users to get the promotion (for example: 500 users) ii. By a time period (for example: 22th May 2022 to 24th May 2022) b. Assume that promotion can only affect benefitPercentage for a given plan Code I have written for Plan Model class Plan(models.Model): planID = models.BigAutoField(primary_key=True) planName = models.CharField(max_length=255, null=True, blank=True) amountOptions = models.CharField(max_length=15, choices=AMOUNT_CHOICES, default="cash") tenureOptions = models.IntegerField(default=1, choices=TENURE_CHOICES) benefitPercentage = models.FloatField(default=0) benefitType = models.CharField(max_length=10, choices=BENIFIT, default="cashback") def __str__(self): return self.planName -
Filtering data using age group in django
I want to filter my products based on for what age group they are intended to. My plan of doing that is using a boolean field and filter the products by that. I have a dropdown menu which lists the different age groups and when a person clicks on one, a page will be displayed with the products which have boolean true for that age group. Here is my models. class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=150) image = models.ImageField(null=False, upload_to='images/') price = models.DecimalField(max_digits=12, decimal_places=2, default=0) amount = models.IntegerField(default=0) detail = RichTextUploadingField() create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) child = models.BooleanField(default=False) teen = models.BooleanField(default=False) adult = models.BooleanField(default=False) def __str__(self): return self.title Is this the way I should do it? If it is the case should I use 3 different views.py for each boolean or is there any efficient way? Thank you in advance! -
I can't submit multiple images with django
I have tried to submit multiple images to my Django website without using Django forms but I can't seem to get it working. I have watched multiple tutorials doing the exact same thing but it's not working. Can you please simplify the answers please, Thank you. views.py @login_required(login_url='/') def addlisting(request): if request.user.is_realtor == True: if request.method == 'POST': header_image = request.FILES.getlist('header_image') property_images = request.FILES.getlist('property_images') for image in property_images: image.save() description = request.POST['description'] built_on = request.POST['built_on'] video_link = request.POST['video_link'] agent = request.user new_property = Property.objects.create( full_bathrooms=full_bathrooms, half_bathrooms=half_bathrooms, one_quarter_bathrooms=one_quarter_bathrooms, three_quarter_bathrooms=three_quarter_bathrooms, garage=garage, lot_size=lot_size, yard_size=yard_size, header_image=header_image, description=description, built_on=built_on, video_link=video_link, agent=agent, ) new_property.save() return render(request, 'dashboard-add-listing.html') else: return render(request, 'index.html') html <div class="dasboard-widget-box fl-wrap"> <div class="custom-form"> <div class="clearfix"></div> <div class="header-image"> <div class="upload-options upload-options-header"> <label class="file-upload-label"> <input class="upload" type="file" accept="image/*" name="header_image"> <span>Upload Header Image</span> </label> </div> </div> <div class="clearfix"></div> <div class="listsearch-input-item fl-wrap"> <div class="fuzone"> <div class="fu-text"> <span><i class="far fa-cloud-upload-alt"></i> Click here or drop files to upload</span> <div class="photoUpload-files fl-wrap"></div> </div> <input type="file" name="property_images" class="upload" multiple> </div> </div> </div> </div> -
InvalidCursorName at cursor "_django_curs_6134247424_sync_4" does not exist
Whenever I try to add a user from djangos user_auth I get this error. models.py: class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthday = models.DateField(blank=True, null=True) def __str__(self): return self.user admin.py: class AccountInline(admin.StackedInline): model = Account can_delete = False verbose_name_plural = 'Accounts' class CustomUserAdmin(UserAdmin): inlines = (AccountInline,) admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) Being new to django, I don't understand what the error means and how to get rid of it. Any help will be greatly appreciated. -
Django .order_by() related field returns too many items
I'm trying to return a list of users that have recently made a post, but the order_by method makes it return too many items. there is only 2 accounts total, but when I call test = Account.objects.all().order_by('-posts__timestamp') [print(i) for i in test] it will return the author of every post instance, and its duplicates. Not just the two account instances. test@test.gmail.com test@test.gmail.com test@test.gmail.com test@test.gmail.com foo@bar.example Any help? class Account(AbstractBaseUser): ... class Posts(models.Model): author = models.ForeignKey('accounts.Account',on_delete=models.RESTRICT, related_name="posts") timestamp = models.DateTimeField(auto_now_add=True) title = ... content = ... -
How to solve "TypeError: Field.__init__() got an unexpected keyword argument 'choices'"?
I recently decided to update my forms.py file of my Django project to make one of the fields into a drop down menu rather than an empty text box. In my forms.py file, I changed the class for customers from; class CustomerSignUpForm(UserCreationForm): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) email_address = forms.EmailField(required=True) membership_tier = forms.CharField(required=True) class Meta(UserCreationForm.Meta): model = User @transaction.atomic def data_save(self): user = super().save(commit=False) user.first_name = self.cleaned_data.get('first_name') user.last_name = self.cleaned_data.get('last_name') user.is_customer = True user.save() customer = Customer.objects.create(user=user) customer.email_address = self.cleaned_data.get('email_address') customer.membership_tier = self.cleaned_data.get('membership_tier') customer.save() return user to the following class CustomerSignUpForm(UserCreationForm): member_tiers = ( 'Basic', 'Intermediate', 'Beast' ) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) email_address = forms.EmailField(required=True) membership_tier = forms.CharField(choices = member_tiers, default = 'Basic', required=True) class Meta(UserCreationForm.Meta): model = User @transaction.atomic def data_save(self): user = super().save(commit=False) user.first_name = self.cleaned_data.get('first_name') user.last_name = self.cleaned_data.get('last_name') user.is_customer = True user.save() customer = Customer.objects.create(user=user) customer.email_address = self.cleaned_data.get('email_address') customer.membership_tier = self.cleaned_data.get('membership_tier') customer.save() return user And here is my customer class in my models.py as well if that will help, class Customer(models.Model): member_tiers = ( 'Basic', 'Intermediate', 'Beast' ) username = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) email_address = models.EmailField(max_length=30) membership_tier = models.CharField(max_length = 30, choices = member_tiers, default = 'Basic') What my question boils down to is: … -
How to POST requests in Django with JS?
I'm trying to add products in my basket without refreshing the page and i have urls: app_name = 'basket' urlpatterns = [ path('', views.BasketView.as_view(), name='summary'), path('/add', views.BasketView.post, name='basket_add'), ] views: class BasketView(generic.list.ListView): template_name = 'basket/basket.html' model = Category def post(self, request, *args, **kwargs): data = request.POST print(data) return 'something' html (+JS): ... <button onclick="basket_add(this)" id="{{ item.id }}"></button> ... <script> function send_productId(id){ var request = new XMLHttpRequest(); request.open('POST', '{% url 'basket:basket_add' %}', true); request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); const data = { id: id, csrfmiddlewaretoken:'{{ csrf_token }}', action: "POST", }; request.send(data); }; function basket_add(obj){ send_productId(obj.id); }; </script> after pressing the button i get this error Forbidden (CSRF token missing.): /basket/add So how can i at least print data correctly or do i need to do it the other way? -
Does `django-import-export` delete old saved model objects when updating them?
This is just a quick question to better understand how django-import-export works. Say I have a few objects of some model already saved in my database. If I try to import from a file containing the data for an object that is already in the database (so, an object with the pk in the import file already exists in the database), the change list shows that this object is being updated. My question is this: does the update process involve deleting the old instance of that object (the one that is saved in the database) and then adding the one that we are importing as if it was a new instance? or is it actually updated using, for example, the instance.update(attr=new_val) method? -
Login not redirecting to the LOGIN_REDIRECT_URL
I created a simple login form with username and password. My login is not redirecting to the LOGIN_REDIRECT_URL link which should redirect to the home page. I tried several credentials from the admin side(which I got from signing up) Urls.py: from django.contrib import admin from django.urls import path from jobs import views as jobs_views #from the job application it is gonna import views from users import views as users_views from django.contrib.auth import views as auth_views urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name = 'login.html'), name= 'login'),] Login.html(only added relevant code): <section class="site-section"> <div class="container"> <div class="row"> {% csrf_token %} {{ form.non_field_errors }} <!-- DEBUG --> {% for field in form %} {% if field.errors %}{{ field.html_name }}: {{ field.errors }}{% endif %} {% endfor %} <div class="col-lg-6"> <h2 class="mb-4">Log In To JobBoard</h2> <form class="p-4 border rounded", submit= 'POST'> <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="fname">Username</label> {{ form.username }} </div> </div> <div class="row form-group mb-4"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="fname">Password</label> {{ form.password }} </div> </div> <div class="row form-group"> <div class="col-md-12"> <input type="submit" value="Log In" class="btn px-4 btn-primary text-white"> </div> </div> </form> </div> </div> </div> </section> settins.py(only added relevant code): LOGIN_REDIRECT_URL = 'home_page' LOGIN_URL = 'login' I tried putting … -
Django raw queries and Postgres declare variable
I have a file with many raw sql queries, that uses text substitution i.e select * from table1 where date_col between '%%from_date%%' and '%%to_date%%' these %%date_from%% and %%date_to%% are then replaced by values using python string replace function. this works fine and the queries work. however it is not idle as it can be open to sql injection. (and no I can't use models or anything beside the raw sql) to make matters worse I can't use %s and parametrise the queries because the variables change order and %s works by order (as far as I can tell) I thought about using declare in order to have my variables at the start of the select block i.e sql - declare from_date date:= %s declare to_date date:= %s select * from table1 where date_col between to_date and from_date python - with with connection.cursor() as cursor: cursor.execute(query, [from_date, to_date']) but this gives out django.db.utils.ProgrammingError: syntax error at or near "date" LINE 1: DECLARE from_date date := '2022-01-01'::date DECLARE to_date... ^ I don't know what I'm doing wrong and I'll be glad for some help. as far as I can see I got the syntax right, maybe django raw queries only support select? … -
How to create a search field in django MultipleChoiceField?
I have a list of skills and I added them to django MultipleChoiceField. But there are a lot of skills and it's hard to find what you want. So I decided to add a search field to this MultipleChoiceField. Is that possible and how can I do it? -
json.dumps returns the objects as a string instead of a JSON object
In the views.py: data1 = Inventory.objects.values_list('product_number','amount') data = json.dumps(list(data1), cls=DjangoJSONEncoder). I pass data as context to the html file. In the HTML file, Using JS I access the JSON object with this code: {{ data|json_script:"hello-data" }} <script type="text/javascript"> var data = JSON.parse(document.getElementById('hello-data').textContent); document.getElementById('id_line_one').onchange = function(event){ console.log(typeof data) alert(data); document.getElementById('id_line_one_unit_price').value = data[this.value]; }; </script> I expect the var data to be a dictionary but it seems to be a String. Object.fromEntries is not working and I get the error Uncaught TypeError: Iterator value [ is not an entry object at Function.fromEntries (<anonymous>). JSON.parse is removing the double quotation and I get [[1, 56000], [2, 55000]] but I am not able to access it as a dictionary. Whenever I use the index to access it, It returns the single characters as output instead of thinking of it as a dict object. How can I convert it into a dictionary? Thanks -
Having issue in loading files from static folder
I am new on django and having issue while following a tutorial on YouTube I stuck in it and try several things but didn't get rid of it plz help me so my static page which i changed into dynamic will load with changes that i made.Everything is working fine except when i try to run it by using {%static%} and i also told the system about static stuff through {%load static%} but it not showing pictures which i try to show through static folder. List item Not showing pictures on web page. Having issue to upload it from static folder. -
Django Rest API filter keeper query (foreignkey)
Django Rest API has user input in foreignkey format. The User input returns all users. But I only want to fetch users that are in the unit of the requesting user. current keeper select input: queryset = User.objects.all() my wish keeper input: queryset = User.objects.filter(unit=request.user.unit) serializers.py: class InventorySerializer(serializers.ModelSerializer): class Meta: fields = ('keeper','status','name') views.py: class InventoryGet(generics..RetrieveUpdateAPIView): serializer_class = InventorySerializer permission_classes = [permissions.IsAuthenticated] lookup_field = 'id' queryset = Inventory.objects.all() models.py keeper = models.ForeignKey(User,models.SET_NULL,null=true,blank=true) status = models.CharField(max_length=500) name = models.CharField(max_length=500) -
How to destructure message in django formatters?
I am trying to customize the logger in django, and here is my code: import logging.config LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "fmt1": { "format": "{asctime}\t{message}", "datefmt": "%Y-%m-%d", "style": "{", }, }, "handlers": { "console1": { "level": "INFO", "class": "logging.StreamHandler", "formatter": "fmt1", }, }, "root": { "handlers": ["console1"], "level": "DEBUG", "propagate": True, }, "loggers": { "": { "handlers": ["console1"], "level": "DEBUG", "propagate": True, }, }, } logging.config.dictConfig(LOGGING) In so doing, I got the following message in my terminal: 2022-07-10 "GET /api/list/ HTTP/1.1" 200 13 However, when I try to use the string function .format() to format the message in formatters, I end up with the following error: ... File "/Users/retr0327/Desktop/Py/django-restAPI/env/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 187, in log_message Message: '"%s" %s %s' Arguments: ('GET /api/list/ HTTP/1.1', '200', '13') Ideally, I want my terminal to have this: 2022-07-10 GET /api/list/ 200 13 How can I achieve this or is there a better way to customize the logger? Thanks for any help!! -
what is the best way to store photos?
I'm using Django as backend and Flutter as front end. I'm developing my first app/website witch is an album app, just like instagram. As you can understand, there is a lot of photos to store, for each user. today I store photos in an sub folder in the backend, witch is not the best thing to do. what is then best place to store photos ? I learn in internet that I can use Base64 or CDN but I really dont know what to choose and why ? Thank you