Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2.0 CreateView AttributeError
Why I got AttributeError: 'function' object has no attribute 'day'? I want to create simple generict view for Editing blog post. views.py: class CreatePostView(LoginRequiredMixin, CreateView): login_url = '/login/' redirect_field_name = 'blog/post_detail.html' model = Post form_class = PostForm Post model in models.py looks like this: class Post(models.Model): title = models.CharField(max_length=200) short_description = models.CharField(max_length=350) slug = models.SlugField(unique_for_date='publish') author = models.ForeignKey('auth.User', on_delete=models.CASCADE) text = models.TextField() created_date = models.DateTimeField(auto_now_add=True) published_date = models.DateTimeField(default=None, blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def get_absolute_url(self): ret_url_context = {'pk':self.pk} if self.published_date: ret_url_context['slug'] = self.slug ret_url_context['year'] = self.published_date.year ret_url_context['month'] = self.published_date.month ret_url_context['day'] = self.published_date.day return reverse("post_detail",kwargs=ret_url_context) def __str__(self): return self.title urls.py: urlpatterns = [ path('', views.PostListView.as_view(), name='post_list'), path('about/', views.AboutView.as_view(), name='about'), path('drafts/', views.DraftListView.as_view(), name='post_draft_list'), path('post/new/', views.CreatePostView.as_view(), name='post_new'), path('post/<int:pk>/edit/', views.PostUpdateView.as_view(), name='post_edit'), path('post/<int:pk>/remove/', views.PostDeleteView.as_view(), name='post_remove'), path('post/<int:pk>/publish/', views.post_publish, name='post_publish'), path('<int:year>/<int:month>/<int:day>/<slug:slug>/', views.PostDetailView.as_view(), name="post_detail_date"), path('post/<str:slug>/', views.PostDetailView.as_view(), name='post_detail'), ] And finally my html form is siple post_form.html: {% extends 'blog/base.html' %} {% block content %} <h1>New post</h1> <form method="POST" class="post-form"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> {% endblock %} I dont know where I should start to find a solution. But I think the problem is in inserting date and time. I'm inserting into editor this text: 12.12.2018 13:45 or … -
How to get a model object with the lowest ID?
I want to get the model object with the lowest ID, in other words the oldest object in that field. oldest = Model.objects.filter(id=lowest_number) How can I achieve this? -
OwlCarousel2 to Wagtail Compatible as Bootstrap Carousel
I have a bootstrap carousel and i want to use OwlCarousel2 on my homepage but converting is giving me trouble any help will be appreciated. The bootstrap carousel i am using is as below and its working fine but would like to use OwlCarousel2 {% if carousel_items %} <div id="carousel" class="carousel slide" data-ride="carousel"> {% if carousel_items|length > 1 %} <ol class="carousel-indicators"> {% for carousel_item in carousel_items %} <li data-target="#carousel" data-slide-to="{{ forloop.counter0 }}"{% if forloop.first %} class="active"{% endif %}></li> {% endfor %} </ol> {% endif %} <div class="carousel-inner" role="listbox"> {% for carousel_item in carousel_items %} <div class="item{% if forloop.first %} active{% endif %}"> {% if carousel_item.embed_url %} {# Embedded video - requires an embedly key to be stored in wagtaildemo/settings/local.py #} <div class="text-center"> {% embed carousel_item.embed_url 1000 %} </div> {% else %} {# Carousel image - first store image as a variable in order to construct an image tag with a title applied (title is used by bxslider js to construct the caption) #} {% image carousel_item.image width-1000 as carouselimagedata %} <img src="{{ carouselimagedata.url }}" style="width: 100%; min-height: {{ carouselimagedata.height }}px;" alt="{{ carouselimagedata.alt }}" /> {% endif %} {% if carousel_item.caption or carousel_item.link %} <div class="carousel-caption"> <h3>{{ carousel_item.caption }}</h3> {% if … -
Test raise exceptions django
How corect test expection. I have next model vatidate func. @classmethod def validate_kind(cls, kind): if kind == 'test': raise ValidationError("Invalid question kind") try to test the self.assertRaises(ValidationError, w.validate_kind('2'),msg='Invalid question kind') also try next: self.assertRaisesRegex(w.validate_kind('2'),'Invalid question kind') Not working corectly. Thex for help. -
How to create human-readable URLs in Django
I'm writing a simple app blog. Django==2.0.4 I want to create human-readable URLs. models.py class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) To this model, I will add slug = models.SlugField('id_url', max_length=255, unique=True) , right? Next, I will add to urls urlpatterns = [ path(r'', views.post_list, name='post_list'), path(r'post/<str:slug>/', views.post_detail, name='post_detail'), ] Right? But I do not understand what I need to add to views.py and need or not me def get_absolute_url(self) in models.py, I hope you help me. Thanks. -
Gitlab CI fails with Error : 2002 Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock
I am running a gitlab CI for my django project with Mysql DB. And I am getting following error : django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)" My requirement.txt file is as follows : Django==2.0.4 django-extensions==2.0.6 mysqlclient==1.3.12 Here is My CI Config file: # This file is a template, and might need editing before it works on your project. # Official framework image. Look for the different tagged releases at: # https://hub.docker.com/r/library/python image: python:latest # Pick zero or more services to be used on all builds. # Only needed when using a docker container to run your tests in. # Check out: http://docs.gitlab.com/ce/ci/docker/using_docker_images.html#what-is-a-service services: # - mysql:latest - postgres:latest variables: # POSTGRES_DB: database_name MYSQL_DB: database_name MYSQL_ALLOW_EMPTY_PASSWORD: "1" # This folder is cached between builds # http://docs.gitlab.com/ce/ci/yaml/README.html#cache cache: paths: - ~/.cache/pip/ # This is a basic example for a gem or script which doesn't use # services such as redis or postgres before_script: - python -V # Print out python version for debugging # Uncomment next line if your Django app needs a JS runtime: # - apt-get update -q && apt-get install nodejs -yqq - pip install -r requirements.txt # To get Django tests to … -
Using HstoreField in Django/ElasticSearch
I'm new to elastic search and I really want to implement it in my django project. My problem: I want to store a python dict object ({'key_1': 'value_1', 'key_2': 'value_2', [...]}) and be sure that my search will look each key. In Django I use Hstore field and I can access my datas doing Model.objects.get(hstorefield__key='value'). Does anyone has an idea to do it using elastic search and be sure that all my keys for my Hstorefield are tracked ? Thanks for help ! Here is my django model: class Product(models.Model): code = models.BigIntegerField() url_off = models.URLField() creator = models.CharField(max_length=200) product_name = models.CharField(max_length=200) last_modified_t = models.DateTimeField() created_t = models.DateTimeField() metadatas = HStoreField() -
Django: Stop model instance creation on ValidationError
I have defined a model and customized the clean() Method for better validation. If I use the model in frontend, it works and I can not save a model that does not fulfil my validation criteria. But when I save via the shell or write my tests a wrong model will still be saved. models.py class FooModel(models.Model): weight_min = models.DecimalField(default=40.0, max_digits=4, decimal_places=1) weight_max = models.DecimalField(default=40.0, max_digits=4, decimal_places=1) def clean(self): if self.weight_min > self.weight_max: raise ValidationError("'Weight min' must be smaller than 'Weight max'.") tests.py def test_create_model_with_wrong_weight(self): foo = FooModel(weight_min=40.0, weight_max=30.0) self.assertRaises(ValidationError, match.save()) # Works, but still saves the model self.assertIs(0, Match.objects.all()) # Fails, QuerySet has objects. I read the docs and tried to call full_clean() in save() but then I dont know how to write the test. What do I have to do to: Raise the ValidationError Prevent Saving the wrong Model Instance -
Recommended way of serializing Django RawQuerySet with non-model fields
Having query like SELECT *, 'hello' AS world FROM myApp_myModel I'd like to serialize it to json. Doesn't seem like a big deal, and there are plenty of similar questions on SO but none seems to give straight answer. So far I've tried: data = myModel.objects.raw(query) # gives: ModelState is not serializable json.dumps([dict(r.__dict__) for r in data]) # doesn't serialize 'world' column, only model fields: serializers.serialize('json', data) #dear God: for r in result: for k in dict(r.__dict__): print(getattr(r,k)) -
Djando-haystack indexes lists instead of raw data with Solr
I am facing a strange issue with django-haystack + Solr: each field receives a list instead of the actual raw value. After indexing, here is an extract of my Solr index (pasted from Solr admin): { "id":"forum.category.4", "django_ct":["forum.category"], "django_id":[4], "text":["Divers"], "name":["Divers"], "url":["/forum/#divers"], "url_str":["/forum/#divers"], "name_str":["Divers"], "django_ct_str":["forum.category"], "text_str":["Divers"]}, As you can see, each relevant data is indexed in a 1-element list, which makes further querying impossible. Here is my index definition: class CategoryIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, model_attr='name') name = indexes.CharField(model_attr='name') url = indexes.CharField(indexed=False) def get_model(self): return Category def prepare_url(self, obj): return obj.get_absolute_url() Any suggestion? Thanks by advance. -
Problems with passing data from view to template?
I am new to Django Python and I am learning how to use Django and passing data from view to template. Now, here is my situation and I really need some help in understanding where i can be doing wrong. I am trying to pass data from view to template and then parse the object in the view but for some reason nothing is happening in the template. I have printed the registration object in my views.py and it works fine and displays the information that is correct. But when I send the registration object from views to template nothing happens. models.py from django.db import models from datetime import datetime from django.shortcuts import redirect # Create your models here. # Create your models here. class Registration(models.Model): first_name = models.CharField(max_length=255, null=True, blank=True) last_name = models.CharField(max_length=255, null=True, blank=True) email = models.CharField(max_length=255, null=True, blank=True) password = models.CharField(max_length=255, null=True, blank=True) mobilenumber = models.CharField(max_length=255, null=True, blank=True) created_on = models.DateTimeField(auto_now_add=True, blank=True) class Meta: ordering = ('first_name',) views.py class Loginview(CreateView): model = Registration form_class = LoginForm template_name = "loginvalentis/valentis_login.html" def get(self, request): form = LoginForm() # returning form return render(request, 'loginvalentis/valentis_login.html', {'form': form}); def form_valid(self,form): user_email = form.cleaned_data.get('email') user_password = form.cleaned_data.get('password') try: registration = Registration.objects.get(email=user_email) print ("registration",registration.mobilenumber) … -
Django, Graphene, Relay, Permissions - How to handle permissions for queries and mutations?
I am new to GraphQL and graphene and I can't really find any documentation on how to handle permissions with Relay. I would also like to know how to handle limiting the number of results from queries with Relay. (Just because nobody wants to get his backend overloaded by too large queries) Just the ability to set a maximum number of results per query would be great. Both of these problems are pretty easy to solve without Relay, but since I want to use django_filters package and some benefits of Relay it becomes a problem. -
Eleasticsearch and Django for Alert Filtering
I have an Elasticsearch index on which records get populated every time we received an email. I want each email to be filtered based on some specific key words (also based on specific time frames) and stored them in another index in the same database. I thought Django is the bast way to do that, as I will be able create GUI for users later on to let them to filter emails based on their preference. Unfortunately, I don't know how to connect Elastisearch and Django to do what I want. -
Django rest api issue: hasattr(): attribute name must be string
I'm creating a simple blog application and I am trying to convert django rest api. But, I got this error TypeError at /user/api/ hasattr(): attribute name must be string Exception Type: TypeError at /user/api/ Exception Value: hasattr(): attribute name must be string this is my models.py file from django.conf import settings from django.db import models from django.urls import reverse class BlogPost(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) blog_title=models.CharField(max_length=200) blog_description=models.TextField() blog_pub=models.DateTimeField(auto_now_add=True) blog_update=models.DateTimeField(auto_now=True) def __str__(self): return self.blog_title def get_absolute_url(self): return reverse('blog:blog_post', kwargs={'pk': self.pk}) this is my serializers.py file from rest_framework import serializers from blog.models import BlogPost class BlogPostSerializer(serializers.ModelSerializer): class Meta: fields=( 'author', 'blog_title', 'blog_description', ), model=BlogPost This is views.py file from blog.models import BlogPost from .serializers import BlogPostSerializer from rest_framework import generics from . import serializers from . import serializers class BlogPostListAPI(generics.ListCreateAPIView): queryset=BlogPost.objects.all() serializer_class=BlogPostSerializer class BlogPostListAPIDetail(generics.RetrieveUpdateDestroyAPIView): queryset = BlogPost.objects.all() serializer_class = serializers.BlogPostSerializer this is urls.py file from django.urls import path,include from .views import SignUpForm, UserProfiles from .api.views import * urlpatterns = [ path('signup/', SignUpForm.as_view(), name='signup'), path('profile/', UserProfiles.as_view(), name='profile'), path('api/', BlogPostListAPI.as_view(), name='asad'), path('api/<int:pk>', BlogPostListAPIDetail.as_view()), ] this is screenshot -
NoneType object is not iterable when trying to save model instance
I am creating a website that allows users to follow stocks and see articles based on those stocks. When I try to save the stocks they follow to the database I get the following error: Error: "request.user.profile.followed_coins = list(form.cleaned_data.get('coins_selected')) TypeError: 'NoneType' object is not iterable" models.py: class Stock(models.Model): name = models.CharField(max_length = 50) ticker = models.CharField(max_length = 50) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) followed_stocks = models.ManyToManyField(Stock, blank=True) def __str__(self): return self.user.username @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: def test(request): if request.method == "POST": form = StockFollowForm(request.POST) if form.is_valid(): request.user.profile.followed_stocks = form.cleaned_data.get('stocks_selected') request.user.profile.save() return redirect('index') else: form = StockFollowForm() return render(request, 'core/test.html',{'form': form}) template: <div class = "container"> <h2 class = "text-center">Register</h2> <form method = 'post'> {% csrf_token %} {{ form }} <div class = "text-center"> <br/> <button class="btn btn-primary" type = 'submit'>Login</button> </div> </form> </div> Thanks in advance! -
Joining and iterating through tables with Django
I have the following 2 Django models: from django.db import models class Stock(models.Model): symbol = models.CharField(db_index=True, max_length=5, null=False, editable=False, unique=True) class PriceHistory(models.Model): stock = models.ForeignKey(Stock, related_name='StockHistory_stock', editable=False) trading_date = models.DateField(db_index=True, null=False, editable=False) price = models.DecimalField(max_digits=12, db_index=True, decimal_places=5, null=False, editable=False) class Meta: unique_together = ('stock', 'date') Obviously this leads to two DB tables being created: myapp_stock and myapp_pricehistory. These tables have 2 and 4 columns respectively. The first table contains thousands of rows. The second table contains millions of rows. I want to join the tables, sort the resultant rows and iterate through these rows one-by-one print them. This is how I plan to do it: for i in PriceHistory.object.all().order_by('stock__symbol', 'trading_date'): print '{} {}: {}'.format(i.stock.symbol, i.trading_date, i.price) Is this the most efficient way to do it to minimize calls to the database? I want it to run only one SQL query. I'm concerned that the above code will run a separate query of the myapp_stock table each time it goes through the for loop. Is this concern valid? If so, how to avoid that? Basically, I know the ideal SQL would look something like this. How can I get Django to execute something similar?: select s.symbol, ph.trading_date, ph.price from myapp_stock as … -
TypeError at /login/ __init__() missing 1 required positional argument: 'request'
when i click on login or register link of my page it show init() missing 1 required positional argument: 'request' and i m confuse on which page it is showing error so i attached my all related pages please verify them same error is showing both login and registration page only.when i click on login or register link of my page it show init() missing 1 required positional argument: 'request' and i m confuse on which page it is showing error so i attached my all related pages please verify them same error is showing both login and registration page only. views.py def guest_register_view(request): form=GuestForm(request.POST or None) context = { "form": form } next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path=next_ or next_post or None if form.is_valid(): email=form.cleaned_data.get("email") new_guest_email=GuestEmail.objects.create(email=email) request.session['guest_email_id']=new_guest_email.id if is_safe_url(redirect_path,request.get_host()): return redirect(redirect_path) else: return redirect("/register/") return redirect("/register/") class LoginView(FormView): form_class = LoginForm success_url = '/' template_name = 'accounts/login.html' def form_valid(self,form): request=self.request next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = authenticate(request, username=email, password=password) if user is not None: login(request, user) user_logged_in.send(user.__class__,instance=user,request=request) try: del request.session['guest_email_id'] except: pass if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path) return super(LoginView, self).form_invalid(form) class RegisterView(CreateView): form_class … -
Django: create a comment form when user is authenticated
I'm creating a simple blog application. A user is logged in this application while He/She can comment any post on my blog application. But cant impletement that idea. This is my models.py file from django.db import models # Create your models here. from user.models import CustomUser from django.conf import settings from django.db import models from django.urls import reverse class BlogPost(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) blog_title=models.CharField(max_length=200) blog_description=models.TextField() blog_pub=models.DateTimeField(auto_now_add=True) blog_update=models.DateTimeField(auto_now=True) def __str__(self): return self.blog_title def get_absolute_url(self): return reverse('blog:blog_post', kwargs={'pk': self.pk}) class Comment(models.Model): blogpost=models.ForeignKey(BlogPost, on_delete=models.CASCADE) comment=models.CharField(max_length=300) author=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,blank=True, null=True) author_name = models.CharField(max_length=50, default='anonymous', verbose_name=("user name")) comment_pub = models.DateTimeField(auto_now_add=True) comment_update = models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse('blog:home', kwargs={'pk':self.pk}) def __str__(self): return self.comment This is views.py file class BlogPostSingle(DetailView, FormView): model=BlogPost template_name='blog/blog_post_single.html' #fields = ['blog_title'] form_class = CreateCommentForm success_url = '/blog/' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) this is my forms.py file class CreateCommentForm(ModelForm): class Meta: model=Comment fields = ('comment', 'blogpost') and this is my html file and forms section {% if user.is_authenticated %} <h5>Hi, {{user.name}} leave your comment now</h5> <form action="" method="post"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit comment"> </form> {% else %} <p>You're not logged in this site, please <a href="{% url 'login' %}">log</a> in for comment </p> {% endif %} My … -
ERROR: CANT_REREAD: The directory named as part of the path /home/app/logs/celery.log does not exist
I'm following a tutorial on how to use Celery on my Django production server. When I get to the bit where it says: Now reread the configuration and add the new process: sudo supervisorctl reread sudo supervisorctl update When I perform sudo supervisorctl reread in my server (Ubuntu 16.04) terminal, it returns this: ERROR: CANT_REREAD: The directory named as part of the path /home/app/logs/celery.log does not exist. in section 'app-celery' (file: '/etc/supervisor/conf.d/app-celery.conf') I've done all of the instructions prior to this including installing supervisor as well as creating a file named mysite-celery.conf (app-celery.conf) in the folder: /etc/supervisor/conf.d If you're curious my app-celery.conf file looks like this: [program:app-celery] command=/home/app/bin/celery worker -A draft1 --loglevel=INFO directory=/home/app/draft1 user=zorgan numprocs=1 stdout_logfile=/home/app/logs/celery.log stderr_logfile=/home/app/logs/celery.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 600 stopasgroup=true ; Set Celery priority higher than default (999) ; so, if rabbitmq is supervised, it will start first. priority=1000 Any idea what the problem is? -
How to solve OperationalError without deleting the db - django 2.0
I have run done these: delete all files under migrations (except init) 2. python manage.py makemigrations python manage.py migrate and even python manage.py migrate --run-syncdb delete db.sqlite3 Thankfully, it solved the problem. However, I had to do step 3 to solve this. How do you solve this problem without deleting the database since I can't afford to do such later on when I already have too much data? Or what causes this problem? Thanks -
django url cache works when only page reload by f5
Maybe It's duplicate of this page. My urls.py: from django.views.decorators.cache import cache_page app_name = 'alphabet' urlpatterns = [ re_path(r'^(?P<alp>a|b|c|d|e)/$', cache_page(60 * 15)(views.alp), name='alp'), ] my_template.html: <div class="non_seen" id="url_custom" data-custom="{% url 'alphabet:alp' %}"></div> And my template file(from my_template.html) there's some js(jquery) code to go that url: $('#btn_custom').click(function (e) { e.preventDefault(); location.href = $('#url_custom').attr('data-custom'); } While I monitor my redis-cli, there's redis monitor logs cache get or set event if I reload(refresh, click F5) page 127.0.0.1:8000/a but when I click #btn_custom, there's no event like that. Question: Why this happened and How to make it cache to every request(including click #btn_custom not only when click F5? -
How to implement SEO in Django
I have django website where there are dyanamically generated web pages. One template and many pages by detailview. I want to add SEO tags in there. How can I? Is it good idea to use DjangoSEO framework? Or I can add context to each page and then render them. Which is best way? -
Django compatability for Python 3.4 on windows
Can any one suggest me if Django is fully supported for python version 3.4 on windows. I have another application developed on PySide framework which is not supported on Python 3.6 . ( Pyside is supported only upto python 3.4). My intention is to retain Python 3.4 on my windows machine and use it for both PySide and Django , is this better approach for both desktop and web application development ? Please suggest...! -
carousel slide not working for static images in django
I am new to Django, I am trying to use bootstrap carousel in django, all images are getting loaded, but slider is not working. <link rel="stylesheet" href="{% static 'Monitoring/css/bootstrap/bootstrap.min.css' %}" /> <script src="{% static 'Monitoring/js/jquery/jquery-1.12.4.min.js' %}" ></script> <script src="{% static 'Monitoring/js/bootstrap/bootstrap.min.js' %}"> </script> <style> .carousel-inner{ height:600px !important; } </style> Below is the body : <div id="myCarousel" class="carousel slide" data-ride="carousel" style="width:100%;"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#myCarousel" data-slide-to="0" class="active"></li> <li data-target="#myCarousel" data-slide-to="1"></li> <li data-target="#myCarousel" data-slide-to="2"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner"> <div class="item active"> <img src="{% static 'Monitoring/media/login/image1.png' %}" alt="Chania" height="600" width="100%"> </div> <div class="item"> <img src="{% static 'Monitoring/media/login/image2.png' %}" alt="Chania" height="600" width="100%"> </div> <div class="item"> <img src="{% static 'Monitoring/media/login/image3.png' %}" alt="Chania" height="600" width="100%"> </div> </div> <!-- Left and right controls --> <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> Also, is there any better way to read all images from a particular folder and use them for carousel slider. In the above code, I am doing same thing for all three images, is it possible to do the same with loop all images in folder. -
paypal sequence django python need explanation
I am trying to refer to paypalrestsdk on my django app but not sure the sequence between authorize and execute https://github.com/paypal/PayPal-Python-SDK I have created the payment and after that I redirect to the payment link using Authorize Payment. This will bring to paypal page. Authorize Payment: for link in payment.links: if link.rel == "approval_url": # Convert to str to avoid Google App Engine Unicode issue # https://github.com/paypal/rest-api-sdk-python/pull/58 approval_url = str(link.href) print("Redirect for approval: %s" % (approval_url)) Execute Payment payment = paypalrestsdk.Payment.find("PAY-57363176S1057143SKE2HO3A") if payment.execute({"payer_id": "DUFRQ8GWYMJXC"}): print("Payment execute successfully") else: print(payment.error) # Error Hash Do we still need to execute payment after authorize payment ? the payment made in authorize should execute already (ok i guess so since return_url seems to go to execute) then how should i process the return_url to obtain (payment id and payer_id)?