Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connect Google Cloud Platform SQL to Visual Studio
I am trying to connect VS to my GCP SQL Server but I'm running into a bunch of issues. I tried following a youtube tutorial (https://youtu.be/l4nPaSXE3QE) and it has an option for Google Cloud SQL in there Photo of Option, but when I download it, mine doesn't show that option. My Visual 2019 version is 16.11.2 Thanks in advance -
Move a data from one department to another using django
I have a webpage where it will show all the data, how do I move this data from this department to another department with just a click of a button. Lets say this data is currently at the customer service page and when I click on the view button the data will go to another department, for example logistic. So after clicking on the button view, it should appear here as shown from the picture below, how to do that Below are my codes for the customer service page and logistic page, they are both the same code. views.py (customer service) @login_required() def ViewMCO(request): search_post = request.GET.get('q') if (search_post is not None) and search_post: allusername = Photo.objects.filter(Q(reception__icontains=search_post) | Q(partno__icontains=search_post) | Q( Customername__icontains=search_post) | Q(mcoNum__icontains=search_post) | Q(status__icontains=search_post) | Q(serialno__icontains=search_post)) if not allusername: allusername = Photo.objects.all().order_by("-Datetime") else: allusername = Photo.objects.all().order_by("-Datetime") # new important part part = request.GET.get('sortType') valid_sort = ["partno", "serialno", "Customername", "mcoNum"] if (part is not None) and part in valid_sort: allusername = allusername.order_by(part) page = request.GET.get('page') paginator = Paginator(allusername, 6) try: allusername = paginator.page(page) except PageNotAnInteger: allusername = paginator.page(1) except EmptyPage: allusername = paginator.page(paginator.num_pages) context = {'allusername': allusername, 'query': search_post, 'order_by': part} return render(request, 'ViewMCO.html', context) views.py (logistic) @login_required(login_url='login') def … -
updating user with same email address, gives email already exists error
I am trying to update user fields but it returns email already exists error when I try to update it with the same email address. @login_required def user_profile(request, id): if request.user.id == int(id): if request.method == "POST": user = Account.objects.get(pk=request.user.pk) form = UserProfileUpdateForm(request.POST, user=user) if form.is_valid(): form.save() messages.success(request, mark_safe("UPDATE: <br> your profile is updated")) context = { "form": form } return render(request, "accounts/user_profile.html", context) else: #... else: #... else: return redirect("not_found") and forms.py class UserProfileUpdateForm(forms.ModelForm): class Meta: model = Account fields = ["first_name", "last_name", "first_name_kana", "last_name_kana", "post_code", "city", "address", "building", "tel", "sex", "occupation", "year", "month", "day", "parent_name", "parent_name_kana", "year", "month", "day", "school_type", "school_name", "student_id", "email"] def __init__(self, *args, **kwargs): now = datetime.datetime.now() user = kwargs.pop("user") super(UserProfileUpdateForm, self).__init__(*args, **kwargs) # widget settings What is the right way to update user fields with the same email address. -
Dictionary output with Django
I need to create a dictionary with the ID's of my users, and also with the coordinates of geocoding API from Google! (The ID is not relevant for the API, but it is for me so i can connect each location with it's own data) This is a template of the dictionary i need to pass to my js script: var markersOnMap = [ { id: { id: 1 }, LatLng: [{ lat: 19.392856, lng: -99.162641 }] }, { id: { id: 2 }, LatLng: [{ lat: 19.393686, lng: -99.170752 }] }, ] This is the views.py script: I'm getting all the addresses and ID's from my users. The API processes the address and returns 2 coordinates: lat and lng, is there a way or a better way to return to the js script each block of data containing the id with it's coordinates and so on per user as i mentioned above? def test(request): # ADDRESSES AND ID'S FROM ALL USERS data = list(UserProfile.objects.values('address', 'id')) # GOOGLE API API_KEY = 'MyApiKey' params = { 'key': API_KEY, 'address': data } base_url = "https://maps.googleapis.com/maps/api/geocode/json?" response = requests.get(base_url, params=params).json() response.keys() if response['status'] == 'OK': geometry = response['results'][0]['geometry'] lat = geometry['location']['lat'] lng = … -
Django inner join with search terms for tables across many-to-many relationships
I have a dynamic hierarchical advanced search interface I created. Basically, it allows you to search terms, from about 6 or 7 tables that are all linked together, that can be and'ed or or'ed together in any combination. The search entries in the form are all compiled into a Q expression. I discovered a problem today. If I provide terms for sub-tables that are (somewhere along the line of foreign keys) in a many to many relationship, the output table will include results from that table that don't match the term. My problem can by reproduced in the shell with a simple query: qs = PeakGroup.objects.filter(msrun__sample__animal__studies__id__exact=3) sqs = qs[0].msrun.sample.animal.studies.all() sqs.count() #result: 2 The ids in sqs include 1 & 3 even though I only searched on 3. I'm hoping I won't have to completely rewrite my interface to do the type of join that only retrieves a record and links to study id 3. Is there a way to do such an inner join as the result of a single Q expression in a filter on the entire set of linked takes that whose fields are in the resulting html table in the template? I'm betting it's not possible without … -
How to update an user with JavaScript on Django
hope someone can help me with this as I´m starting to go crazy not finding anything. I need to make an update for a certain user using django and oracle, me and my team decided to use javascript for the update but we can´t figure it out. {% extends 'core/base.html' %} {% block titulo %} <title>Registro_coach</title> {% endblock %} {% load static %} {% block css %} <link rel="stylesheet" href="{% static 'core/css/estilo_r_coach.css' %}"> {% endblock %} {% block contenido %} <div class="row"> <div class="col-md-6"> <h3>Coachs registrados</h3> <table id="tablaCoach" class="table table-bordered table-dark"> <thead> <tr> <th scope="col">Run</th> <th scope="col">Nombre</th> <th scope="col">Apellido Paterno</th> <th scope="col">Apellido Materno</th> <th scope="col">Correo</th> <th scope="col">Telefono</th> </tr> </thead> <tbody> {% for i in coachs%} <tr> <td>{{i.0}}</td> <td>{{i.1}}</td> <td>{{i.2}}</td> <td>{{i.3}}</td> <td>{{i.5}}</td> <td>{{i.4}}</td> <th><input type="button" class="btnModificar" value="Modificar"></th> </tr> {% endfor %} </tbody> </table> </div> <div class="col-md-5 ml-auto"> <h3>Registro Coach</h3> <form id="FormCoach" action="" method="POST"> {% csrf_token %} <input class="controls" type="text" name="run" id="run" placeholder="Run" oninput="checkRut(this)" maxlength="10" required> <input class="controls" type="text" name="nombre" id="nombre" placeholder="Ingrese su Nombre" required> <input class="controls" type="text" name="a_paterno" id="a_paterno" placeholder="Apellido paterno" required> <input class="controls" type="text" name="a_materno" id="a_materno" placeholder="Apellido materno" required> <input class="controls" type="email" name="correo" id="correo" placeholder="Ingrese su correo" required> <input class="controls" type="text" name="telefono" id="telefono" placeholder="telefono" required> <input class="botons" type="submit" value="Agregar" onclick="limpiarFormulario()" … -
django.db.utils.IntegrityError: null value in column "genre_id" of relation "shop_book" violates not-null constraint
I am building Microservice, I have 2 project / 1 DB in Warehouse and 1 DB in Shop. When I have a new book in Warehouse I have updated DB in Shop - celery takes this task and does Models in Warehouse and Shop it same. I'm getting a strange error that I can't find information for. Models: from django.db import models from django.urls import reverse class Author(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def __str__(self): return f'{self.first_name} {self.last_name}' class Genre(models.Model): name = models.CharField(max_length=50, db_index=True) slug = models.SlugField(max_length=50, unique=True) class Meta: ordering = ('name',) verbose_name = 'genre' verbose_name_plural = 'genres' def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:book_list_by_genre', args=[self.slug]) class Book(models.Model): author = models.ForeignKey('Author', on_delete=models.CASCADE) genre = models.ForeignKey(Genre, related_name='books', on_delete=models.CASCADE) title = models.CharField(max_length=255) description = models.TextField(blank=True) language = models.CharField("language", max_length=20) pages = models.IntegerField() image = models.ImageField(upload_to='products/%Y/%m/%d') slug = models.SlugField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2) isbn = models.CharField('ISBN', max_length=13, unique=True) created = models.DateTimeField(auto_now_add=True) available = models.BooleanField(default=True) quantity = models.IntegerField() class Meta: ordering = ('title',) index_together = (('id', 'slug'),) def __str__(self): return self.title def get_absolute_url(self): return reverse('shop:book_detail', args=[self.id, self.slug]) Celery: from celery import shared_task from django.core.mail import send_mail import requests from .models import Author, Book, Genre @shared_task def send_mail_task(subject, message, email): send_mail(subject, message, … -
cart problem in django checkout, Problem sorting items in cart
i am using a brokerage to pay but i am having trouble sending the cart This is the draft the brokerage house wants from me. options = { 'api_key': 'api', 'secret_key': 'secretkey', 'base_url': 'sandbox-api.iyzipay.com' } payment_card = { 'cardHolderName': kartisim, 'cardNumber': kartno, 'expireMonth': kartskt, 'expireYear': '2030', 'cvc': karcvc, 'registerCard': '0' } buyer = { 'id': adres.id, 'name': adres.adres_uye.username, 'surname': 'Doe', 'gsmNumber': '+905350000000', 'email': adres.adres_uye.email, 'identityNumber': '74300864791', 'lastLoginDate': '2015-10-05 12:43:35', 'registrationDate': '2013-04-21 15:12:09', 'registrationAddress': adres.adres_detay, 'ip': '85.34.78.112', 'city': 'Istanbul', 'country': 'Turkey', 'zipCode': '34732' } address = { 'contactName': 'Jane Doe', 'city': 'Istanbul', 'country': 'Turkey', 'address': 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', 'zipCode': '34732' } basket_items = [ { 'id': 'id', 'name': 'name', 'category1': 'category1', 'category2': 'category2', 'itemType': 'type', 'price': 'price' }, { 'id': 'id', 'name': 'name', 'category1': 'category1', 'category2': 'category2', 'itemType': 'type', 'price': 'price' }, { 'id': 'id', 'name': 'name', 'category1': 'category1', 'category2': 'category2', 'itemType': 'type', 'price': 'price' } ] request_payload = { 'locale': 'tr', 'conversationId': '123456789', 'price': '1', 'paidPrice': '1.2', 'currency': 'TRY', 'installment': '1', 'basketId': 'B67832', 'paymentChannel': 'WEB', 'paymentGroup': 'PRODUCT', 'paymentCard': payment_card, 'buyer': buyer, 'shippingAddress': address, 'billingAddress': address, 'basketItems': basket_items } payment = iyzipay.Payment().create(request_payload, options) this is my method: basket_items = [] for bas in uye: bas = { … -
I'm having some trouble setting default url for specific page in Django
Right now I have my urls.py set up like this: urlpatterns = [ ... path('dividends/<str:month>/', views.DividendView.as_view(), name='dividendview'), path('dividends/', views.DividendView.as_view(), name='dividendview'), ] What I would like is to have the 'month' parameter optional and default to today's month. Right now I have my views.py set up as class DividendView(ListView): model = Transaction template_name = 'por/dividends.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) divs = Dividends() month = self.kwargs['month'] context['month'] = get_month(month) return context def get_month(month): if month: return month else: return datetime.today().month and my dividends.html file as {% extends 'base.html' %} {% load static %} {% block title %}Dividends{% endblock %} {% block content %} {{ month }} {% endblock %} If I navigate to /dividends/Oct/ (or any other month) it works fine, but if I just go to /dividends/ it gives me KeyError: 'month' Can anyone help me figure out what I'm doing wrong and how I might go about fixing it? Thanks. -
How to display product details from django restframework to angular?
I am trying to navigate into my product details, however not getting any response from my api. May i have you assistance please? django views: class Product(generics.RetrieveAPIView): lookup_field = "slug" queryset = Product.objects.all() serializer_class = ProductSerializer django urls: path("product/<slug>", views.Product.as_view(), name="product_detail"), angular api.service: import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class ApiService { baseurl = "http://127.0.0.1:8000" httpHeaders = new HttpHeaders({'Content-Type': 'application/json'}) constructor(private http: HttpClient) { } getAllProducts(): Observable<any>{ return this.http.get(this.baseurl +'/product/', {headers: this.httpHeaders}) } getProductDetails(slug: string){ return this.http.get(this.baseurl +'/product/'+ slug, {headers: this.httpHeaders}) } } angular product detail components: ts - export class GroceriesDetailsComponent implements OnInit { ProductId:any; ProductData:any = []; constructor( private service:ApiService) { } ngOnInit(): void { this.ProductId = this.actRoute.snapshot.params['id']; this.getProductDetails(this.ProductId); } getProductDetails(ProductId: string){ this.service.getProductDetails(ProductId).subscribe(product=>{ this.ProductData=product; }); } } and the html - <div class="form-froup row"> <p>{{ ProductData.title }}</p> </div> -
Django Annotate Changes Query Values/Order
I am trying to pull the 8 most recent items from my model and attach their minimum price. When I annotate the 8 most recent items, the items change unless I use order_by(). Is this a bug, or does this make my query more efficient somehow? I'm trying to better understand my queries so that I can make them faster. class Item(ClusterableModel): name = models.CharField(max_length=100) class Meta: ordering = ('-pk',) class StoreInventory(ClusterableModel): item = ParentalKey('Item', on_delete=models.CASCADE) price = models.DecimalField(max_digits=4, decimal_places=2) Undesired newest_items = Item.objects.all()[:8] > Queryset [Item: Item object(100), ..., Item: Item object(93)] newest_items = newest_items.annotate(price = Min('storeinventory__price')) > Queryset [Item: Item object(1), ..., Item: Item object(8)] Desired newest_items = Item.objects.all().order_by('-pk')[:8] > Queryset [Item: Item object(100), ..., Item: Item object(93)] newest_items = newest_items.annotate(price = Min('storeinventory__price')) > Queryset [Item: Item object(100), ..., Item: Item object(93)] -
Create and get the id of a model's attribute in Django
Im working in a project where users can register their shops addresses in a Django model and i can display all those addresses in a google map. For that i need the addresses but also a way to access to that specific user's shop info, how can i create an id linked or pointing to the user's "address" attribute in my extended users models, and how do i call all those ids? models.py class UserProfile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE, related_name='user_profile') address = models.CharField(null=True, blank=True, max_length=150) views.py def test(request): addresses = list(UserProfile.objects.values_list('address')) address_id = ???????? context = { 'address_id': address_id, 'addresses': addresses } return render(request, "test.html", context) -
Create a preview screen in Django
I have a Django form that receives a text (that I copy from Google Classroom: a bunch of student comments). I use these comments to make student's attendance. What I want to achieve is: Accessing /insertion/ url via GET user receive the page form as a response, to choose the class (class01, class02, etc) and to past the text When the user clicks on submit in this form (post method), it is redirect to the same /insertion/ url, but now the form is bound to the data submited, and the page shows a preview page (based on a boolean variable I'm passing through context), showing what students are present and what are absent based on the text informed. At that page, a new submit button will be shown below a text like "if everything's ok, hit the ok button". After click this ok button, a pdf will be generated and the user will be redirected to /files/ url, to see the generated pdf and previous generated pdf. views.py def insertion(request): context = {} if request.method == 'GET': form = AttendanceDataForm() context.update({"form": form}) if request.method == 'POST': form = AttendanceDataForm(request.POST) context.update({"form": form}) if form.is_valid(): lesson = form.cleaned_data['lesson'] raw_text = form.cleaned_data['raw_text'] # … -
Trouble creating unit tests for Django admin action
I am having a bit of trouble figuring out where to mock and patch things and it's not making sense to me. I'm creating an admin action that fetches a token from a third-party API, and then instantiates an instance of a local class (that connects to said API) and makes API calls based on the item id. For example, let's assume that I'm storing restaurant ratings in an external location, accessible via API calls, and I'm storing users locally. I want to create an admin action that goes through each selected user and deletes all restaurant ratings in my external location, which is authenticated via a fetched token. I know this is not an optimal way to do things, but this is obviously not a real example, just an analogue of something a bit more complicated. Here is the structure of my project. from external_class_location import ReviewClass # This is the class that hooks into the restaurant review location from external_function_location import get_token # This is the method that fetches the token from that external location class UserAdmin(admin.ModelAdmin) actions = ['delete_reviews', ] def delete_reviews(self, request, queryset): reviews = ReviewClass(get_token()) for user in queryset: reviews.delete_all_reviews(user) delete_reviews.short_description = "Delete all reviews … -
How Do I Incorporate Ajax into a CreateView?
I have a CreateView...and it works fine in the traditional sense. I'm trying to convert it essentially to an AJAX for submit because the user can attach files to the form, and I'm trying to avoid a form submission failure based on the user's mistakes. Here is my CreateView... class CreateProcedureView(LoginRequiredMixin,CreateView): model = NewProcedure form_class = CreateProcedureForm template_name = 'create_procedure.html' def form_valid(self, form): instance = form.save() def post(self, request, *args, **kwargs): if "cancel" in request.POST: return HttpResponseRedirect(reverse('Procedures:procedure_main_menu')) else: self.object = None user = request.user form_class = self.get_form_class() form = self.get_form(form_class) file_form = NewProcedureFilesForm(request.POST, request.FILES) files = request.FILES.getlist('file[]') if form.is_valid() and file_form.is_valid(): procedure_instance = form.save(commit=False) procedure_instance.user = user procedure_instance.save() list=[] for f in files: procedure_file_instance = NewProcedureFiles(attachments=f, new_procedure=procedure_instance) procedure_file_instance.save() return self.form_valid(form) else: form_class = self.get_form_class() form = self.get_form(form_class) file_form = NewProcedureFilesForm(request.POST, request.FILES) return self.form_invalid(form) As stated it works just fine the way it is. What I'm trying to figure out is how can I best convert this to an AJAX type of approach? Here's what I have so far... Here's my AJAX... $(document).ready(function (){ $("#forms").on('submit', function(event) { event.preventDefault(); var newprocedure = '{{ newprocedure }}'; $.ajax({ type: "POST", url: "{% url 'Procedures:ajax_posting' %}", data:{ newprocedure:newprocedure, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() }, datatype:'json', success: function(data) { … -
Serving Django App with Apache 2 on Virtual Host
I am learning the Django framework and can run my first app on the development server using: python3 manage.py runserver However, what I really want to do is serve my app with Apache so it can be access from the web. My Apache Virtual Host is: <VirtualHost *:443> ServerName django.example.com DocumentRoot /var/www/django/hello_world/mysite WSGIScriptAlias / /var/www/django/hello_world/mysite/mysite/wsgi.py Include /etc/letsencrypt/options-ssl-apache.conf SSLEngine On SSLCertificateFile /etc/letsencrypt/live/django.example.com/cert.pem SSLCertificateKeyFile /etc/letsencrypt/live/django.example.com/privkey.pem SSLCertificateChainFile /etc/letsencrypt/live/django.example.com/chain.pem WSGIDaemonProcess django.sample.com processes=2 threads=15 display-name=%{GROUP} python-home=/var/www/django/hello_world/mysite/venv/lib/python3.6 WSGIProcessGroup django.sample.com <directory /var/www/django/hello_world/mysite> AllowOverride all Require all granted Options FollowSymlinks </directory> </VirtualHost> I'm getting: My settings.py file is: from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-3b^iz&pognt=yt5m&(!w@keo&*@a9zb&)$n@32v!yj4w%c!k-4' DEBUG = True ALLOWED_HOSTS = [ 'django.sample.com' ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' I'm running … -
What should be my main direction with django?
Heey django masters. I have some questions becouse I don't know which direction to go further. I mastered django on an average/medium level. I want ask you, what is the most important in django and what should I pay attention to. Maybe have you and good tips or tutorials for me? Last my question, when should i learn ajax? Javascript should be first? -
Dictionary not rendering in page
in my view im trying to pass in a dictionary like so rooms = [ {'id': 1, 'name': 'designign'}, {'id': 2, 'name': 'wow'}, {'id': 3, 'name': 'now'}, ] def home(request): context = {'rooms' : rooms} return render(request, 'home.html', context) Then in my home.html page i have this code {% extends 'main.html' %} {% block content %} <h1>Home Template</h1> <div> <div> {% for room in rooms %} <div> <h1>{{room.name}}</h1> </div> {% endfor %} </div> </div> {% endblock content %} but the items in the dictionary are not displaying. the url and path are fine because <h1>Home Template</h1> displays but nothing else displays main.html <body> {% include 'navbar.html' %} {% block content %} {% endblock %} </body> urlpattern if that matters urlpatterns = [ path('', views.home, name="home") ] -
Django/Scrapy/Apache - Error downloading <GET https://example.com>
I've created a web scrapper which runs from Django view and it works as expected when I run it locally but it gives an error when I run it from my (Apache)server. [scrapy.core.scraper] ERROR: Error downloading <GET https://example.com> FYI. I use valid URL addresses for sure and it works locally without any issues. Also, I've set "TELNETCONSOLE_PORT" :None, . Not sure if this is related to the issues but without this parameter it gave me another error. Unable to listen "127.0.0.1: 6023" -
CI/CD pipeline for Django failure
My gitlab ci pipeline keeps failing. It seems am stuck here. Am actually still new to the CI thing so I don't know what am doing wrong. Any help will be appreciated Below is .gitlab-ci.yml file image: python:latest services: - postgres:latest variables: POSTGRES_DB: projectdb # This folder is cached between builds # http://docs.gitlab.com/ee/ci/yaml/README.html#cache cache: paths: - ~/.cache/pip/ before_script: - python -V build: stage: build script: - pip install -r requirements.txt - python manage.py migrate only: - EC-30 In my settings.py file, I have the following settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'thorprojectdb', } } But when I push to gitlab, the build process keeps failing. The - pip install -r requirements.txt runs perfectly but once it gets to - python manage.py migrate, it fails. Below is the error I do get django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? Cleaning up project directory and file based variables ERROR: Job failed: exit code 1 -
How to loop inside Stripe
I have a problem I would like to loop inside Stripe to create dynamic multiple objects in checkout. I can not do that after stripe.checkout.Session.create() because I get an error. Also I can not create JSON object in for loop out of stripe.checkout.Session.create(). Any ideas? How can I use for loop and create multiple line_items? def create_checkout_session(request): if request.method == "GET": try: cart = Cart.objects.get(order_user=request.user) checkout_session = stripe.checkout.Session.create( payment_method_types=['card', 'p24'], line_items=[{ 'price_data': { 'currency': 'eur', 'product_data': { 'name': 'total' }, 'unit_amount': cart.total, }, 'quantity': 1, }], -
How can I extract URL of the video uploaded using Django Embed video
I am using Django Embed Video to upload videos to my website that works perfectly fine. The code below is how I extract the url of the video that I uploaded. HTML TEMPLATE: {% for course in courses %} <div class="name"> <h3>{{course.video}}</h3> </div> {% endfor %} That gives me the url but what i want is the video id for example the url it gives looks like "https://youtu.be/iHkKTGYc6aA" and I just need the "iHkKTGYc6aA". It can be done with the python using the .replace method but whenever I try to use the if tags of django html template i get this error: Could not parse the remainder: The HTML code that I use {% for course in courses %} <div class="name"> {% if text in course.video %} <h3>{{url=course.video.replace("https://youtu.be/", "")}} </h3> {% endif %} </div> {% endfor %} I know it's not the right way of doing it but I shared it just to show what i want to achieve. My views.py: def Courses(request): courses = Video.objects.all() total_uploaded_videos = courses.count() text = "https://youtu.be/" url = "" context = {'courses':courses, 'total_uploaded_videos':total_uploaded_videos, 'text':text, 'url':url} return render(request, 'accounts/Course.html', context) Models.py: class Video(models.Model): name = models.CharField(blank=False, max_length=100, default="", null=False, primary_key=True) video = EmbedVideoField() def __str__(self): … -
How to print host information from Django model while using ModelViewSet of REST Framework
I'm using Django REST Framework that will allow users to save information and generate QR code image which will be URL of the user profile such as: http://127.0.0.1:8000/user/detail/fahad-md-kamal-fd028af3/ Something Like How can I access host address from Django Model so that I can use it to generate QR code? DRF Model class UserInfo(models.Model): def save(self, *args, **kwargs): if not self.slug: self.slug =f'{slugify(self.name)}' qrcode_image = qrcode.make(f"{host}/{self.slug}/") super(UserInfo, self).save(*args, **kwargs) Serializer Class class UserBaseReadSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.UserBase fields = ( 'url', 'phone', 'name', 'address', 'qr_code', 'slug', ) View Class: class UserInfoViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserBaseSerializer queryset = models.UserInfo.objects.all() While I was doing it with standared Django and Functional View I did it like: Functional View: def add_user_info(request): if request.method == 'POST': form_data = UserInfomationForm(request.POST) if form_data.is_valid(): obj = form_data.save(commit=False) obj.save(host =request.META['HTTP_ORIGIN']) Over ridding Model Class's save method class UserInfo(models.Model): def save(self, host=None, *args, **kwargs): if not self.slug: self.slug =f'{slugify(self.name)}-{str(uuid.uuid4())[:8]}' qrcode_image = qrcode.make(f"{host}/{self.slug}/") super(UserInfo, self).save(*args, **kwargs) -
Django: passing context data between html file in different apps
How can I pass the context data (int his case profile_total variable) create in one of my views to the html template of another app? This is my code: app1.views.py def view_profile(request): profile_total = UserProfile.objects.all().count() return render(request, 'profile/user_profile.html', {'profile_total': profile_total}) app2.stats.html <div class="container"> <h1> Show </h1> Profile submitted: {{ profile_total }} </div> Right now it's only displayed a blank space instead that the count of the profile submitted. Thank you all for your helps! -
Implementing a custom authentication in DRF which can read request.data
I have a foreign key on my models like Patient, and Doctor, which point to a Clinic class. So, the Patient and Doctor are supposed to belong to this Clinic alone. Other Clinics should not be able to see any detail of these Models. From my Vue app, I will post using Axios to the django app which uses DRF, and thus get serialized data of Patients and Doctors. It all works fine if I try to use the following sample code in function view: @api_view(['GET', 'POST']) def register_patient_vue(request): if request.method == 'POST': print("POST details", request.data) data = request.data['registration_data'] serializer = customerSpecialSerializer(data=data) if serializer.is_valid(): a = serializer.save() print(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED) else: print("Serializer is notNot valid.") print(serializer.errors) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Sample output: POST details {'registration_data': {'name': 'wczz', 'ageyrs': 21, 'agemonths': '', 'dob': '', 'gender': 'unspecified', 'mobile': '2', 'email': '', 'alternate': '', 'address': '', 'marital': 'unspecified', 'city': '', 'occupation': '', 'linkedclinic': 10}} data: {'name': 'wczz', 'ageyrs': 21, 'agemonths': '', 'dob': '', 'gender': 'unspecified', 'mobile': '2', 'email': '', 'alternate': '', 'address': '', 'marital': 'unspecified', 'city': '', 'occupation': '', 'linkedclinic': 10} However, I need to authenticate the request by special custom authentication. I have another class called UserGroupMap which has Foreign Keys for …