Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-allatuh login automatic on "/"
I have a program in DJango. I have a second program called "users". Inside I have implemented login and login with microsoft authentication. I have done this using the "allauth" library. Now I want you when accessing the page, (without having to access the "/login" page) check if you have a microsoft account. That is, when I enter the main page: "/", it takes me to the page to choose a microsoft account in the event that it has one. Without having to press any buttons. That's possible? That it automatically connects if I am connected to a Microsoft account. This is my view: def home(request): if not request.user.is_authenticated: user = authenticate(request, auth_entry='microsoft') if user is not None: login(request, user) return redirect('main_page') else: microsoft_account = SocialAccount.objects.filter(user=request.user, provider='microsoft') if microsoft_account.exists(): return redirect('main_page') return render(request, 'home.html') As you can see, the problem is that I firt see if the user is authenticated. But if it the first time the user enters, it is imposible to be autheticated. I don't know if I explained myself correctly, I want the Microsoft authentication to be automatic -
django.db.migrations.exceptions.InconsistentMigrationHistory:
I am getting this error when trying to make migrations. Migration test_1.0001_initial is applied before its dependency test_2.0016_boolean on database 'default'. I've tried python manage.py makemigrations --merge I have also tried. python manage.py migrate --fake -
Getting this error when tried to install using pip install anymail
ERROR: Could not find a version that satisfies the requirement anymail (from versions: none) ERROR: No matching distribution found for anymail Can anyone help me with this -
Django Python view function for virtual assistant app
I have done the code for a virtual assistant using openai, speech_recognition, PyAudio. Its working fine on terminal. Now I'm trying to add the UI for it using Django. Does anyone have an example of how the view function should look like ? Thanks I want to add a UI for text option as well as speech option on it. -
In Reactjs Getting an error .map() is not a function
when i try to fetch response from api i got map is not a function error .but i declared state as array. Here's the code: function VendorListScreen(){ const [vendorsList,setVendorsList]=useState([]); const getVendors =()=>{ axios.get('http://127.0.0.1:8000/api/vendors/').then((res)=>{ setVendorsList(res.data) }) } <h1>Vendor</h1> <button onClick={getVendors}>get</button> {vendorsList.map(vendor=>{ return <p>{vendor.name}</p> })} -
nameError in django model.py
i made a class named Airport in models.py, but when i am feeding data through shell its giving me nameError: name 'Airport' is not defined from django.db import models # Create your models here. class Airport(models.Model): code = models.CharField(max_length=3) city = models.CharField(max_length=64) def __str__(self): return f"{self.city} ({self.code})" class Flight(models.Model): origin = models.ForeignKey(Airport, on_delete =models.CASCADE, related_name="departures") destination = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="arrivals") duration = models.IntegerField() def __str__(self): return f"{self.id}: {self.origin} to {self.destination}" -
How to make a reference in adminpanel to another entity that is a relationship
How to make it so that when you click on, for example, a payment number it takes you to its page. Order and payment are in Onetoonefield relationship. admin.py @admin.register(Order) class OrderAdmin(admin.ModelAdmin): ordering = ('pk',) list_display = ['pk', 'user', 'order_date', 'deadline', 'status', 'payment', 'total', 'debt', 'shipping'] list_filter = ['status', 'if_extended'] exclude = ['order_date', 'deadline', 'return_date', 'total', 'payment', 'shipping', 'if_extended', 'number_of_extensions'] search_fields = ('pk',) inlines = [ItemInline] -
Maintaining the task creation time in Django
I have a Django web application that has a superuser who can see all the tasks of other users that have been entered since the past days. When I applied this filter to the superuser, it did not display any tasks for the superuser. That filter is It used to be that the super user could only see the tasks of the current month, that is, from the first of the month until now, and if it was the first of the month, he could access the tasks of the previous month. I am editing my code like This but that is not working!!! class Task(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True) posted_time = models.DateTimeField(auto_now_add=True, auto_now=False, blank=False,editable=False) def save(self, *args, **kwargs): if self.pk: kwargs['update_fields'] = [f.name for f in self._meta.fields if f.name not in ['posted_time', 'id']] -
Test Django settings with pytest
I am trying to set some environment variables that drive the configuration of a Django project in some tests so that I can mock some of the values and make assertions easier and explicit. I want to set an environment variable with the name of a file which stores some configuration which is loaded if the variable is set and the file exists. i.e: # proj.settings.py CONFIG = None if _filename := os.environ.get('FILE_PATH', None): with open(_filename) as f: CONFIG = json.load(f) I have tried a fixture that sets an environment variable (see set_env), so my tests look like this: # some_app.tests.test_settings.py import os @fixture def data_raw(): return dict( foo="bar" ) @fixture def data_file(data_raw): with NamedTemporaryFile(mode="w+") as f: json.dump(data_raw, f) yield f.name @fixture def set_env(data_file): os.environ['FILE_PATH'] = data_file def test_it_loads_data(set_env, data_raw, settings): assert settings.CONFIG == data_raw But set_env doesn't execute before Django's configuration, so CONFIG is never set. -
Django pytest APIView: How to create test for an api
I have an api endpoint which is passed client_id, and token Using the client_id and token, it gets an email_id. Using the email_id it creates a user and then creates a jwt token for the user and sends back in response The below is my view from rest_framework.views import APIView from rest_framework.response import Response from rest_framework_simplejwt.tokens import RefreshToken from django.contrib.auth.hashers import make_password from django.contrib.auth.models import BaseUserManager from rest_framework import status from google.oauth2 import id_token from google.auth.transport import requests class GoogleView(APIView): def post(self, request): # (Receive CLIENT_ID and token by HTTPS POST) CLIENT_ID = request.data['client_id'] token = request.data['token'] try: idinfo = id_token.verify_oauth2_token(token, requests.Request(), CLIENT_ID) email_d = idinfo['email'] try: user = User.objects.get(email=idinfo['email']) except User.DoesNotExist: user = User() user.email = idinfo['email'] # provider random default password user.password = make_password(BaseUserManager().make_random_password()) user.save() token = RefreshToken.for_user(user) # generate token without username & password response = {} response['email'] = user.email response['access_token'] = str(token.access_token) response['refresh_token'] = str(token) return Response(response) except ValueError: response = {} response['message'] = "Not a valid google oauth tokens" return Response(response, status=status.HTTP_406_NOT_ACCEPTABLE) the urls: path('google/', views.GoogleView.as_view(), name='google'), I am asked to write test cases for this api using pytest. I am not sure what all to be tested in this case. Can someone help what … -
apache seems to be adding a trailing slash to static files so 404 but python manage.py runserver works fine
I am new to django and apache and am trying to serve a project on Debian 9 with django 1.9 over apache 2.4 server. For some reason when I try to run django project with python manage.py runserver 0.0.0.0:8000 and access it from local web browser using server ip:8000 it works fine but when I try to serve it through apache 2.4 for some reason it seems like apache is adding a trailing slash to static files paths and I get a 404 error django project path: /var/gnats django settings path: /var/gnats/gnats/settings.py DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'compressor', 'taggit', 'modelcluster', 'wagtail.wagtailcore', 'wagtail.wagtailadmin', 'wagtail.wagtaildocs', 'wagtail.wagtailsnippets', 'wagtail.wagtailusers', 'wagtail.wagtailimages', 'wagtail.wagtailembeds', 'wagtail.wagtailsearch', 'wagtail.wagtailsites', 'wagtail.wagtailredirects', 'wagtail.wagtailforms', 'djrill', 'mail_templated', 'password_reset', 'pages', 'account', 'siteconfig', 'api' ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'wagtail.wagtailcore.middleware.SiteMiddleware', 'wagtail.wagtailredirects.middleware.RedirectMiddleware', ) STATIC_ROOT = '/var/gnats/pages/static' STATIC_URL = '/static/' templates format <link href="/static/css/bootstrap.css" rel="stylesheet"> <link href="/static/font/stylesheet.css" rel="stylesheet" > <link href="/static/css/font-awesome.css" rel="stylesheet" > <link href="/static/css/screen.css" rel="stylesheet" > log when using python manage.py runserver 0.0.0.0:8000 (no issues) [30/Mar/2023 04:56:45] "GET / HTTP/1.1" 200 12779 [30/Mar/2023 04:56:45] "GET /static/css/bootstrap.css HTTP/1.1" 304 0 [30/Mar/2023 04:56:45] "GET /static/font/stylesheet.css HTTP/1.1" 304 … -
Why is my django-crontab cronjob not working?
I have a django-project with an app called app that has a file called cron.py with a function called my_job(). I want the my_job() function to be called every minute. In my django-project/django-project/settings.py I have this: INSTALLED_APPS = [ 'django_crontab', ... ] ... CRONJOBS = [ ('*/5 * * * *', 'app.cron.my_job') ] My django-project/app/cron.py looks like this: from .models import TestModel def my_job(): TestModel.objects.create(number=100) return True Of course I ran : python3 manage.py crontab add And the terminal printed: adding cronjob: (62dd7536ac2c985925ee33743a070a4c) -> ('*/5 * * * *', 'app.cron.my_job') To be safe I run: python3 manage.py crontab show And the terminal prints: Project/ccc_nema -> ('*/5 * * * *', 'app.cron.my_job') To check if evrything works I run: python3 manage.py crontab run someHash Traceback (most recent call last): File "/home/anik/Workplace/Office Project/ccc_nema v2/core/manage.py", line 22, in <module> main() File "/home/anik/Workplace/Office Project/ccc_nema v2/core/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/anik/Workplace/Office Project/ccc_nema v2/env_python/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/anik/Workplace/Office Project/ccc_nema v2/env_python/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/anik/Workplace/Office Project/ccc_nema v2/env_python/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/home/anik/Workplace/Office Project/ccc_nema v2/env_python/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/home/anik/Workplace/Office Project/ccc_nema v2/env_python/lib/python3.10/site-packages/django_crontab/management/commands/crontab.py", line 29, in handle Crontab().run_job(options['jobhash']) File "/home/anik/Workplace/Office Project/ccc_nema v2/env_python/lib/python3.10/site-packages/django_crontab/crontab.py", line … -
Combining two models into one in django
Is it possible to combine two models into one in django so that I can show all details of both table in django admin panel in one table. class User(AbstractUser): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(unique=True) phone = models.CharField(max_length=12) username = models.CharField(max_length=150, null=True) company_name = models.CharField(max_length=255, null=True, blank=True) gst_no = models.CharField(max_length=150, blank=True, null=True) class Address(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='address') street_address = models.CharField(max_length=100) apartment_address = models.CharField(max_length=100) country = CountryField(multiple=False) state = models.CharField(max_length=100,) city = models.CharField(max_length=100) zip = models.CharField(max_length=100) address_type = models.CharField(max_length=1, choices=ADDRESS_CHOICES) default = models.BooleanField(default=False) used_in_orders = models.BooleanField(default=False) display = models.BooleanField(default=True) def gst_no(self): return self.user.gst_no if self.user.gst_no else None I know there is Inline method but I don't. want that I want to show all details of both models into one separate table -
How to remove duplicates in a django request
Remove duplicates in a Django query Image SQL duplicate. I used select_related and reduced the number of requests from 90 to 18, but if the database grows, then this will not save me. How can the query be improved? views.py def index(request): snj = ScheduleNotJob.objects.select_related() form = SNJ() return render(request,"index.html",{'snj': snj, 'form':form}) models.py class Office(models.Model): title = models.CharField(max_length=150, db_index=True) def __str__(self): return self.title class Post(models.Model): office = models.ForeignKey(Office, on_delete=models.CASCADE) title = models.CharField(max_length=150, db_index=True) def __str__(self): return self.title class Human(models.Model): office = models.ForeignKey(Office, on_delete=models.CASCADE) post = ChainedForeignKey( Post, chained_field="office", chained_model_field="office", show_all=False, ) initials = models.CharField(max_length=150, db_index=True) def __str__(self): return self.initials class Reason(models.Model): title = models.CharField(max_length=150) def __str__(self): return self.title class Shift(models.Model): title = models.CharField(max_length=150) def __str__(self): return self.title class ScheduleNotJob(models.Model): shift = models.ForeignKey(Shift, on_delete=models.CASCADE) office = models.ForeignKey(Office, on_delete=models.CASCADE) post = GroupedForeignKey(Post, "office") human = GroupedForeignKey(Human, "post") reason = models.ForeignKey(Reason, on_delete=models.CASCADE) comment = models.CharField(max_length=300, blank=True, null=True) length_time = models.IntegerField(blank=True, null=True) date_start = models.DateField(blank=True, null=True) date_end = models.DateField(blank=True, null=True) index.html {% for elem in snj %} <tr class="mySelect"> <td>{{ elem.id }}</td> <td>{{ elem.shift }}</td> <td>{{ elem.office }}</td> <td>{{ elem.post }}</td> <td>{{ elem.human }}</td> <td>{{ elem.reason }}</td> <td>{{ elem.comment }}</td> {% endfor %} I used select_related and reduced the number of requests from 90 … -
Django password reset with mailtrap.io return error for DateTimeField classes
I am trying to create a forget_password function and I am using the following: @api_view(['POST']) def forgot_password(request): data = request.data user = get_object_or_404(User, email=data['email']) token = get_random_string(40) now = datetime.now() expire_date = now + timedelta(minutes=30) user.profile.reset_password_token = token user.profile.reset_password_expire = expire_date user.profile.save() host = get_current_host(request) link = '{host}/api/reset_password/{token}'.format(host=host, token=token) # Here is the message. body = 'Your password reset link is: {link}'.format(link=link) # Sending email send_mail( 'Password reset for DicoAPI', body, 'noreply@dicoapi.com', [data['email']] ) return Response({ 'message': 'Password reset email sent to: {email}'.format(email=data['email']) }) I use the following field in the model I have created: reset_password = models.DateTimeField(null=True, blank=True) Now when trying to use the endpoing everything works fine in the console: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' But when I try: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' I got the following error with the DateTimeField RuntimeWarning: DateTimeField Profile.reset_password_expire received a naive datetime (2023-03-29 22:29:24.744400) while time zone support is active. By the way, I am using mailtrap for email testing Email testing configuration with: https://mailtrap.io/ EMAIL_HOST=config('EMAIL_HOST') EMAIL_HOST_USER=config('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD=config('EMAIL_HOST_PASSWORD') EMAIL_PORT=config('EMAIL_PORT') EMAIL_USE_TLS=config('EMAIL_USE_TLS') -
How do I replace the text in an element?
Hello I'm trying to replace this h2 element with an AJAX response. I think it goes something like this? but it doesn't seem to work. <h2 class="b-0" class="d-inline categoryname">Food</h2> These are the things I've tried $(`.categoryname`).text(`${response['category_name']}`); $(`.categoryname`).replaceWith(`${response['category_name']}`); $(`.categoryname`).text().replace(`${response['category_name']}`); $(`.categoryname`).html(`${response['category_name']}`); None of em seem to work! Does anyone know what to use? -
forms.ValidationError aren't being displayed on form
i'm trying to show an error message bellow the input on my register form, although it isn't being showed. On my tests the form is considered invalid by django on the if respostas_form.is_valid(): condition, but the message that was suposed to be displayed is not apearing. ( the name of variables and funcs of the codes are in portuguese cz i'm brazilian ) html: {% for field in cadastro.visible_fields %} <div class="inputContainer"> <label class="forms__label" for="{{field.id_for_label}}" class="inputText">{{field.label}}</label> {{field}} {% for error in field.errors %} <div class="alert alert-danger"> {{error}} </div> {% endfor %} </div> {% endfor %} forms.py class CadastroForm(forms.Form): email = forms.EmailField( max_length=100, required=True, label='Email', widget=forms.TextInput({ "class": 'forms__input', "placeholder": "exemplo@gmail.com", }) ) nome_de_usuario = forms.CharField( max_length=100, required=True, label="Nome de usuário", widget=forms.TextInput({ "class": 'forms__input', "placeholder": "Ex.: Jóse Dávila", }) ) senha = forms.CharField( max_length=70, required=True, label="Senha", widget=forms.PasswordInput({ "id": "userPasswordInput", "class": 'forms__input', "placeholder": "Exemplo1234+", }) ) senha2 = forms.CharField( max_length=70, required=True, label="Confirme sua senha", widget=forms.PasswordInput({ "id": "userPasswordInput", "class": 'forms__input', "placeholder": "Exemplo1234+", }) ) def clean_senha2(self): senha = self.cleaned_data.get('senha') senha2 = self.cleaned_data.get('senha2') if senha and senha2: if senha != senha2: raise forms.ValidationError('Senhas não são iguais') else: return senha2 views.py def cadastrar(request): if request.user.is_authenticated: return redirect('inicio') cadastro_form = forms.CadastroForm() if request.method == 'POST' and request.POST: … -
Paypal order details won't show on paypal invoice for unauthenticated users
I have successfully integrated a paypal checkout for orders. When a user registers and makes and order the paypal invoice shows all details I have requested. When the use is anonymous no details are shown other than the amount paid. I hope I have given enough code for some one to help me figure this out. JS from checkout page: <script> document.cookie = "cookie_name=value; SameSite=None; Secure"; var total = '{{order.get_cart_total}}'; var order_id = '{{ order.id }}'; var order_items = []; {% for item in order.orderitem_set.all %} order_items.push({ name: '{{ item.product.title }}', quantity: '{{ item.quantity }}', unit_amount: { currency_code: 'GBP', value: '{{ item.product.price }}' }, title: '{{ item.product.title }}' }); {% endfor %} // Render the PayPal button into #paypal-button-container paypal.Buttons({ style: { color: 'blue', shape: 'rect', }, // Set up the transaction createOrder: function(data, actions) { var purchase_units = [{ amount: { value: parseFloat(total).toFixed(2), breakdown: { item_total: { currency_code: "GBP", value: parseFloat(total).toFixed(2) } } }, description: "Order ID: {{order.id}}", items: order_items }]; return actions.order.create({ purchase_units: purchase_units }); }, // Finalize the transaction onApprove: function(data, actions) { return actions.order.capture().then(function(details) { console.log(JSON.stringify(details)); submitFormData() }); } }).render('#paypal-button-container'); </script> <script type="text/javascript"> if (user != 'AnonymousUser'){ document.getElementById('customer-info').innerHTML = '' } if (user != 'AnonymousUser'){ document.getElementById('customer-info').classList.add('hidden'); … -
How can I combine two Django views into one?
I am tring to combine two Django views into one. The goal is to be able to render a Django form and a folium map on the same page. Below is my best attempt at combining the views into a Combined view. Please let me know where I went wrong. import folium from django.shortcuts import render from django.views import View from django.views.generic import FormView from .models import StLouisCityLandTax from .forms import StLouisCityLandTaxForm class formView(FormView): form = StLouisCityLandTaxForm template_name = 'maps/partials/_form.html' def get(self, request): form = StLouisCityLandTaxForm() return render(request, 'maps/partials/_form.html', {"form": form}) def folium_map(request): properties = StLouisCityLandTax.objects.all() # create a Folium map centered on St Louis m = folium.Map(location=[38.627003, -90.199402], zoom_start=11) # add markers to the map for each station for i in properties: coordinates = (i.point_y, i.point_x) folium.Marker(coordinates).add_to(m) context = {'map': m._repr_html_()} return render(request, 'maps/partials/_map.html', context) class CombinedView(View): def get(self, request): context = { 'form': form, 'map': m._repr_html_(), } return render(request, 'maps/StLouisCityLandTaxSale.html', context) I tried the code listed above. -
Django: Fields from Parent class don't include in the child class table
I have three django models. A parent class and a two childs class. What I am missing to get the parent class fields appear in the childs class tables class Parent(models.Model): advertiser = models.CharField('Advertiser', max_length=100) insertion_order = models.ForeignKey(UserInsertionOrder, on_delete=models.CASCADE) strategy = models.CharField('Strategy Name', max_length=300) creative = models.CharField('Creative Name', max_length=400) def __str__(self): return "%s" % self.insertion_order class Meta: db_table = 'InserstionOrders' # abstract = True class Child1(Parent): dsp = models.CharField('DV360', max_length=25) class Child2(Parent): dsp = models.CharField('Xandr', max_length=25) In my pgadmin, I don't see variables comming from Parent class. I even got an error when I add abstract=True in the Parent class -
How to find which code is changing the settings of the Decimal context in a long-running process?
After scratching my head for days over a bizarre and intermittent problem in a Django app I'm responsible for, I eventually determined that the problem was that the configuration of the default Decimal context (the precision setting, in particular) is being altered without being altered back. I've worked around this, but still haven't determined where or why it's happening. It doesn't seem to be occurring in my code, so I suspect that it must be some 3rd-party package or other, and I'd like to determine which one so I can file a report with the vendor. So, what are some techniques I could use to track down the code (or at least the package, but the more granular the better) that's modifying the settings of the Decimal context, without spending a ton of time auditing source code? Python 3.8.5, Django 4.1. -
Giving every submitted form a different I'd in Django
I got a problem when trying to submit the review form. Below are the two issues When l try to send the form without pk=1 it returns an error below MultipleObjectsReturned at /submit _review/7/ get() returned more than are Action Review--it returned 6! When I try to send the form when pk=1, it works and the review form is sent to the Admin. But the following below nor work It only changes the review form with an id=1 My Expectations and Needs I would like to have a form submitted and it gets the new id not being fixed like pk=1, but getting a new id everytime and every form sent or submitted #Action/views.py def submit_review(request,game_id): url = request.META.get('HTTP_REFERER') if request.method == 'POST': try: reviews = ActionReview.objects.get(user__id=request.user.id, game_name__id=game_id, pk=1) form = Game_ReviewForm(request.POST, instance=reviews) form.save() messages.success(request, 'Thank you! , Your review has been Updated Successfully.') return redirect(url) except ActionReview.DoesNotExist: form =Game_ReviewForm(request.POST) if form.is_valid(): data=ActionReview() data.subject = form.cleaned_data['subject'] data.stars = form.cleaned_data['stars'] data.content = form.cleaned_data['content'] data.game_id=game_id data.user__id=request.user.id data.save() messages.success(request, 'Thank you! , Your review has been Added Successfully.') return redirect(url) -
Django paginator does not pass second GET
My goal is to filter objects by buttons and then parse it to pages. It works but when i go to next page the filter i get from GET just disapears. it works on the first page just fine but when i move to 2.page that is where it doesn't filter. My view: def Archive(request): filte = request.GET.get("category") manga = Manga.objects.all() if filte != None: manga = manga.filter(manga_categorys=filte) cats = Categorys.objects.all() paginator = Paginator(manga, 20) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) manlen = len(manga) context = { "Category": cats, "Manga": page_obj, "MangaLen":manlen, } template = loader.get_template("Category.html") return HttpResponse(template.render(context, request)) And my template(filter): <form method="GET"> <div class="grid grid-cols-10 gap-6"> {%for x in Category%} <button class="bgl text-center p-4" type="submit" value="{{x.id}}" name="category"><h2 class="M text-xl ">{{x.category_name}}</h2></button> {%endfor%} </div> </form> Edit : I have also tried: {%for x in Category%} <a class="bgl text-center p-4" href="?category={{x.id}}"><h2 class="M text-xl ">{{x.category_name}}</h2></a> {%endfor%} My paginator(they are in the same template): <div class="pagination mx-auto p-2 flex w-max mt-4 bgl roulnded-lg"> <span class="step-links"> {% if Manga.has_previous %} <a href="?page=1"> <div class="p-3 text-lg M w-max mx-auto inline mx-2 border-r-2">&laquo;</div></a> <a href="?page={{ Manga.previous_page_number }}"><div class="p-3 text-lg M w-max mx-auto inline mx-2 border-r-2">Önceki</div></a> {% endif %} <span class="current text-lg p-3 mx-2"> {{ Manga.number }} … -
Pass order details into invoice via PayPals smart button
I have made a simple website for my father in which he sells photographic prints, They are added to the cart, order is processed and everything goes through perfectly as it should, seeing as it is not a complex ecommerce website. I am not seasoned coder and the only method I can currently get working is the PayPal smart buttons with in my check out page. Currently my orders are going through successfully and all data is been stored in the back end of my Django app/database. What I want to do is be able to pass all of the order details into the paypal invoice, such as item names, quantity etc... I cannot seem to get it working. Here is my code: Checkout.HTML / JS: <script src="https://www.paypal.com/sdk/js?client-id=MY-ID&currency=GBP"></script> <script> document.cookie = "cookie_name=value; SameSite=None; Secure"; var total = '{{order.get_cart_total}}'; var order_id = '{{ order.id }}'; // Render the PayPal button into #paypal-button-container paypal.Buttons({ style: { color: 'blue', shape: 'rect', }, // Set up the transaction createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value:parseFloat(total).toFixed(2), }, description: order_id }] }); }, // Finalize the transaction onApprove: function(data, actions) { return actions.order.capture().then(function(details) { console.log(JSON.stringify(details)); submitFormData() }); } }).render('#paypal-button-container'); </script> <script type="text/javascript"> … -
How to draw a line graph for the django model feild In django template using google chart api
Here is sample data of my model GDP Here i want to display years (like 1961,1962,1963...) on my x-axis and prices on my y-axis Here i am also sharing my reference image to display the graph Here in above picture those point(i.e 283.75, 274.84...] are nothing but my gdp values from GDP Model i am sharing my views.py here def gdp_chart(request): gdp_values = GDP.objects.values_list('date','gdp') return render(request, 'dashboard_graph.html', {'gdp_values':gdp_values}) Please help me out write html code using google chart api to get the line graph as sample image