Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting a list index out of range and i'm not sure why
I get a index list out of range error and cant figure out why. The error seems to be occurring at the line p2 = 'FLipkart Price: $' + price2[0].text. For some reason the similar code that pertains to the the variable p works fine but not this one. If it helps, I am just trying to make a website that compares prices at amazon and flipkit. I am using python and the Django framework. def search_item(request): item = '' if request.method == 'POST': item = request.POST.get('textfield') wbd = wb.Chrome('/usr/bin/chromedriver') #webdriver_path = '/usr/bin/chromedriver' amazon_url = 'https://www.amazon.com/' flip_url = 'https://www.flipkart.com/' search_url = amazon_url + ("s?k=%s" % (item)) print(search_url) wbd.get(search_url) price = wbd.find_elements_by_class_name('a-price-whole') p = 'Amazon Price: $' + price[0].text l = 'Link: ' + search_url search_url2 = flip_url + ("search?q=%s" % (item)) print(search_url2) wbd.get(search_url2) price2 = wbd.find_elements_by_class_name('_1vC4OE') p2 = 'FLipkart Price: $' + price2[0].text l2 = "Flipkart Link: " + search_url2 return render(request, 'index.html', {'aprice': p, 'alink': l, 'fprice': p2, 'flink': l2}) -
Trying to get access token with django-oauth-toolkit using fetch not working while working using jquery
I'm trying to call endpoint to generate access token using oauth in django it is working when I call the endpoint using jquery but not working when I try to call it with fetch here is the code for fetch fetch(`https://<domain>/o/token/`, { method: 'POST', body:{ grant_type:'password', client_id: "<client-id>", client_secret:"<client-secret>", username:"<username>", password:"<password>" } }) .then(res => res.json()) .then(res => {console.log(res)}); the output is {error: 'unsupported_grant_type'} while when I'm calling it using jquery ajax as below its working $.post({ url:'https://<domain>/o/token/', data:{ grant_type:'password', client_id: "<client-id>", client_secret:"<client-secret>", username:"<username>", password:"<password>" }, success: function(data){ console.log(data); } }) the output is {access_token: '<access-token>', expires_in: 3600, token_type: 'Bearer', scope: 'read write groups', refresh_token: '<refresh-token>'} -
Why is Factory Boy populating Local DB instead of Test DB
I set up ~100 unit test for a django app, and later realized each unit test run was creating test users in my local database, instead of the test database. I found a "solution", but I don't know why it's working. Maybe someone can help. apps/user/tests/factories.py class CompanyFactory(factory.django.DjangoModelFactory): class Meta: model = Company title = fake.name() class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User auth0_id = fake.random_number() email = "unit_test_user@cart.com" company = SubFactory(CompanyFactory) When running a test that uses the factory like this, fake users are being persisted in the DB: When changing the UserFactor inheritance to factory.Factory instead of factory.django.DjangoModelFactory it works fine. Anyone know why this behavior is happening? -
Django Cant query Oracle
I have a Django application, and it works fine. So far, the connection to Oracle seems to be ok. The problems is when I try to query data. I use the objects property and it gives me "ORA-00933: SQL command not properly ended" error. So far I ven looking the query and I think is the problem. Anyway, I try that same query on oracle and sems to be pk print(CONTRIBUYENTES.objects.using('VIALISDB').all().query) SELECT "FGESILDOWN.SILD_DET_CONTRIBUYENTES"."DTCO_FOLIOSOLICITUD" FROM "FGESILDOWN.SILD_DET_CONTRIBUYENTES" Does someone knows the problem? -
How to import a function to a view.py file and launch a server with a basic view in django?
The server works fine when I run python3 manage.py runserver on the VSC terminal But as soon as I try to import a function from a view.py file def hello(request): return HttpResponse("Hello Django - Coder") to the urls.py file the server doesn't work I do the from django.view import hello and I also modify the url by adding the path "hello" of the function urlpatterns = [ path('admin/', admin.site.urls), path('hello/' hello) ] But it doesn't work. Any help would be much appreciated -
Flask in python (jinja2.exceptions.TemplateNotFound)
import smtplib #importing the module from flask import Flask, request from flask import Flask, render_template # importing the render_template function app = Flask(__name__) # home route print(6) @app.route("/") def home(): print(8398383) return render_template('E:/contact.html') print(2) @app.route("/", methods=['POST']) def vals(): print(449483) name = request.form['name'] email = request.form['email'] sub = request.form['subject'] bod=request.form['message'] return render_template('E:/contact.html') if __name__=='__main__': print(4948383) app.run(debug=True) this is my flask code <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>KiddieKingdom - Contact</title> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <meta name="keywords"> <meta name="description"> <!-- Favicon --> <link href="img/Kiddiekingdom.png" rel="icon"> <!-- Google Web Fonts --> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Handlee&family=Nunito&display=swap" rel="stylesheet"> <!-- Font Awesome --> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet"> <!-- Flaticon Font --> <link href="lib/flaticon/font/flaticon.css" rel="stylesheet"> <!-- Libraries Stylesheet --> <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet"> <link href="lib/lightbox/css/lightbox.min.css" rel="stylesheet"> <!-- Customized Bootstrap Stylesheet --> <link href="css/style.css" rel="stylesheet"> </head> <body> <!-- Navbar Start --> <div class="container-fluid bg-light position-relative shadow"> <nav class="navbar navbar-expand-lg bg-light navbar-light py-3 py-lg-0 px-0 px-lg-5"> <!--<img src="" class="logo" style="height: 50px; width: 50px; padding-left: 0%;">--> <a href="" class="navbar-brand font-weight-bold text-secondary" style="font-size: 40px;"> <!--<i class="flaticon-028-kindergarten"></i>--> <span class="text-primary text-center">KiddieKingdom</span> <p class="text-left" style="font-size: xx-small;">Reg. no 532/2021</p> </a> <button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#navbarCollapse"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse justify-content-between" id="navbarCollapse"> <div class="navbar-nav font-weight-bold mx-auto py-0"> <a href="index.html" class="nav-item nav-link">Home</a> <a href="about.html" class="nav-item … -
How do I use UUID from objects in my JS scripts?
Helloo, I'm new here . I don't know if I put the right question but I have a problem In my models.py I have the next field: id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) I'm trying to make a show password and copy to clipboard script in JS for every entry but because I'm using UUID it's not working properly. If I'm using simple ID the scripts are fine. The error: identifier starts immediately after numeric literal template.html {% extends "_base.html" %} {% block content %} {{ entry.id}} {{ entry.password_website }}<br /> {{ decrypted_password }}<br /> {{ entry.name_website }}<br /> {{ entry.url_website }}<br /> {{ entry.login_website}}<br /> <a class="btn btn-dark" href="{% url 'vaults:passwords' %}">Go back<a/> <input id="password-{{ entry.id}}" style="width: auto;" type="password" value="{{ decrypted_password }}" disabled> <button style="font-family: monospace; cursor: pointer;" id="password-button-{{ entry.id}}" onclick="showPassword({{ entry.id }});">show</button> <button style="font-family: monospace; cursor: pointer;" onclick="copyToClipboard({{ entry.id }});">copy</button> <script> function showPassword(id) { var input = document.getElementById("password-" + id); var input_button = document.getElementById("password-button-" + id); console.log(input) console.log(input_button) if (input.type === "password") { input.type = "text"; input_button.text = "hide"; } else { input.type = "password"; input_button.text = "show"; } } function copyToClipboard(id) { var password = document.getElementById("password-" + id).value; var elem = document.createElement("textarea"); elem.value = password; elem.style = … -
filter choices for many to many field in form django
I want "picking_person" to be selectable only from "members" of a Group. I ill trying some init and filters, but i cannot find solution. Profile model does not connected with Group model. Group model have two attributes which are connected to Profile: class Group(models.Model): members = models.ManyToManyField( Profile, blank=True, default=Profile, related_name="members" ) picking_person = models.ManyToManyField( Profile, blank=True, default=Profile, related_name="picking_person" ) forms.py: class ChoosePersonPickingForm(ModelForm): class Meta: model = Group fields = ['picking_person'] views.py: def choose_person_to_pick_players(request, pk): group = Group.objects.get(id=pk) form = ChoosePersonPickingForm(instance=group) group_members = group.members.all() if request.method == "POST": form = ChoosePersonPickingForm(request.POST, instance=group) form.save() return redirect('group', group.id) context = {'form': form} return render(request, "choose-picking-person.html", context) I trying Can you help me to find solution? -
NOT NULL constraint failed: mainsite_customer.user_id
i just wanna get profile with full form or empty form def local_cabinet(request): user_id = request.user.id caruser = Checkout.objects.filter(user=request.user) # form = CheckoutForms() orders = request.user.orderitem_set.all() total_orders = orders.count() ready_order = request.user.order_set.all() customer = Customer.objects.filter(user=request.user) customer_form = CustomerForm() maybe here problem idk if request.method == 'POST': if customer.exists(): form = CustomerForm(request.POST, request.FILES, instance=customer) else: form = CustomerForm(request.POST) if form.is_valid(): form.save() context = { 'caruser': caruser, 'orders': orders, 'total_orders': total_orders, 'ready_order': ready_order, 'cat_selected': 0, 'customer_form': customer_form, 'customer': customer, } return render(request, 'localcabinet.html', context=context) idk why i get this, maybe because not right to sava form i will be thanks you if you can help -
How to replace GeoQuerySet in Django model for Django 2.0+
I am trying to upgrade an old GeoDjango project to user newer versions of software, but I am getting an error when trying to upgrade Django from 1.7.5 to newer than 2.0. Apparently the GeoQuerySet was removed in 2.0. But I am not sure how I should remove it, and what to replace it with. Here is a piece of my models.py with the relevant code. from __future__ import unicode_literals from collections import OrderedDict from django.conf import settings from django.contrib.gis.db import models import clustering class PropertySaleQuerySet(models.query.GeoQuerySet): """ QuerySet with additional clustering methods for the PropertySale objects """ def _single_dot_serialize(self, p): return OrderedDict([ ('id', p.uid), ('type', 'dot'), ('sale_type', p.sale_type), ('latitude', p.geometry.y), ('longitude', p.geometry.x), ]) def _cluster_serialize(self, cluster, num): counts = {} centroid = cluster.centroid if len(cluster.items) < settings.CLUSTER_BREAK: return [self._single_dot_serialize(p) for p in cluster.items] for item in cluster.items: if item.sale_type not in counts: counts[item.sale_type] = 0 counts[item.sale_type] += 1 return [OrderedDict([ ('id', num), ('type', 'cluster'), ('latitude', centroid[1]), ('longitude', centroid[0]), ('extent', cluster.extent), ('chartData', counts) ])] def cluster_saletype(self, bbox_string): x1, y1, x2, y2 = map(float, bbox_string.split(',')) dx = x2 - x1 thresh = dx / settings.CLUSTER_THRESH_DENOM properties = list(self.filter(geometry__isnull=False).only('sale_type', 'geometry')) clusters = clustering.cluster(properties, threshold=thresh, getpoint=lambda p: (p.geometry.x, p.geometry.y)) return sum((self._cluster_serialize(cluster, num) for num, … -
How to run a function every month in Django?
I I Want to Add a certain amount of fees to be added in every individual student account every month. To do that, I need to run a function in the 1st day of month. How do I run a function continuously after every month? -
Wagtail wagtailcore issue "NOT NULL constraint failed: wagtailcore_page.translation_key"
I am getting the error message on any call of Page model save method. django.db.utils.IntegrityError: NOT NULL constraint failed: wagtailcore_page.translation_key One of the Page Models looks like this @register_query_field('home_page') class HomePage(BasePageAbstract): body = StreamField( BasePageAbstract.stream_blocks + [ ], null=True, blank=True ) content_panels = BasePageAbstract.content_panels + [ StreamFieldPanel('body', classname="full") ] parent_page_types = None graphql_fields = [ GraphQLString("body") ] with abstract class class BasePageAbstract(Page): title_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=False, on_delete=models.SET_NULL, related_name='+' ) sub_title_text = models.CharField(max_length=500, blank=True, null=True) stream_blocks = [ ('collection', CollectionBlock()), ("rich_text", blocks.RichtextBlock()), ] content_panels = [MultiFieldPanel([ ImageChooserPanel('title_image'), FieldPanel('sub_title_text', widget=forms.Textarea(attrs={'rows':5})), ])] + Page.content_panels class Meta: abstract = True Django = "==2.2.5" wagtail = "==2.6.1" In my database the table wagtailcore_page and the field translation_key are created. So I think it could be a problem with the uuid creation. I tried deleting and re-migrating the Page models - no success. I also tried updating wagtail - no success. I do not really have a clue on how to get closer to a solution of this problem. I'd appreciate any help. I will supply more info if helpful. Best regards! -
how to read a file from a directory and removing the extension when printing it in django?
I'm building a web app on Django and I've implemented two functions, one to save csv files in a file directory on my PC, and the other is to read these files to view them in the website. My problem is that I want to read csv files from the directory and display them but without the csv extension, I want their names to be the only thing visible, but I keep getting this error FileNotFoundError. this is the function that saves the files to a directory def openDataset(request): if request.method == "GET": return render(request, 'blog/upload_csv_ag.html') if request.FILES.get("file2") is not None: csv_file = request.FILES['file2'] if not csv_file.name.endswith('.csv'): message='The uploaded file has to be CSV. Please try again.' return render(request, 'blog/upload_csv_ag.html',{'message':message}) else: save_path = 'C:/Users/user/Desktop/Fault Detection App/Uploaded_Datasets/' file_name = csv_file.name fs = FileSystemStorage(location=save_path) file = fs.save(file_name, csv_file) else: message='no file is uploaded' return render(request, 'blog/upload_csv_ag.html',{'message':message}) return render(request,'blog/upload_csv_ag.html',{'message':'Dataset Uploaded'}) and the function that reads the files from the directory def read_datasets(request): path = r"C:/Users/user/Desktop/Fault Detection App/Uploaded_Datasets/" test = os.listdir(path) path1, dirs, files = next(os.walk(path)) file_count = len(files) print(file_count) dataframes_list_html = [] file_names = [] index = [] for i in range(file_count): temp_df = pd.read_csv(path+files[i]) print(files[i]) dataframes_list_html.append(temp_df.to_html(index=False)) index.append(i) for item in test: if … -
Page not found (404) mistake after setting media folder django
I am getting Page not found (404) mistake after I set up the media folder as follows in settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' then in urls.py: from django.contrib import admin from django.urls import path from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT). After this when I try to run the server, I am getting the following message: Using the URLconf defined in personal_portfolio.URLs, Django tried these URL patterns, in this order: admin/ ^media/(?P<path>.*)$ The empty path didn’t match any of these. Where is the mistake? -
cant connect django to ORACLE
im using oracle for fech data in an existing database, but the query always gives this error django.db.utils.DatabaseError: ORA-00933: SQL command not properly ended MYMODEL.objects.using("MYDB").all() this is the connections 'MYDB': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'MYHOST:51521/SERVICE_NAME', 'USER': 'MYUSER', 'PASSWORD': 'MYPASS' } -
django blog Summernote prints out html instead of picture
Anyone got any idea why i get this problem when i try to post a blogpost on my django blog? Problem is on the front page before readmore it just displays an html code? the code i used for this is pritty much how to build a django blog and to put in summernote. https://djangocentral.com/building-a-blog-application-with-django/ https://djangocentral.com/integrating-summernote-in-django/ -
Django MultiValueDictKeyError at /accounts/login/
so I got a code error MultiValueDictKeyError at /accounts/login/. MultiValueDictKeyError picture The error appears when I'm trying to send password reset email. Here's my code: views.py: from email.policy import default from django.http import HttpResponse from django.shortcuts import redirect, render from accounts.forms import registrationForm from accounts.models import Account from django.contrib import messages, auth from django.contrib.auth.decorators import login_required #verification stuff from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.utils.encoding import force_bytes from django.contrib.auth.tokens import default_token_generator from django.core.mail import EmailMessage # Create your views here. def register(request): if request.method == 'POST': form = registrationForm(request.POST) if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] phone_number = form.cleaned_data['phone_number'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] username= email.split("@")[0] user = Account.objects.create_user(first_name=first_name, last_name=last_name, email=email, username=username, password=password) user.phone_number = phone_number user.save() #Account activation current_site = get_current_site(request) mail_subject = 'Please activate your account' message = render_to_string('accounts/account_verification.html', { 'user': user, 'domain': current_site, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), }) to_email = email send_email = EmailMessage(mail_subject, message, to=[to_email]) send_email.send() return redirect('/accounts/login/?command=verification&email='+email) else: form = registrationForm() context = { 'form': form, } return render(request, 'accounts/register.html', context) def login(request): if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] user = auth.authenticate(email=email, password=password) if user is not None: auth.login(request, user) messages.success(request, … -
Unable to join static file to root directory in Django
To join the static file in Django, STATIC_URL = "os.path.join(BASE_DIR, '/static/')" print("static file : ", (os.path.join(BASE_DIR, '/static')), ) This is producing : static file : C:/static But in the same document I had joined template folder: print("Path is : ", os.path.join(BASE_DIR, 'myproject/template')) Which produces this: Path is : C:\Users\user\Desktop\django\myproject\myproject/template Is this the reason Django is producing this error: ERRORS: ?: (urls.E006) The STATIC_URL setting must end with a slash. Could you please advise how can i resolve this error? -
Django views receives incomplete POST data
I am sending Axios post data from React app to Django views, However, some of the data is missing when receiving it in the Django view. here is my code : axios .post("http://127.0.0.1:8000/vrp-api/solver/", serverData) .then((response) => { const activeArcs = JSON.parse(response.data).activeArcs; const nodes = createLocations(); const routes = generateVehicleDelivery(activeArcs); let pathIndex = 1; Object.keys(routes).forEach((key) => { let route = routes[key]; route.forEach((arc, i) => { const formattedLocation = `${nodes[arc[0]].lng},${ nodes[arc[0]].lat }:${nodes[arc[1]].lng},${nodes[arc[1]].lat}`; setTimeout(() => { tServices.services .calculateRoute({ key: "I6kBz902v7AXAGvD9J7DNysPz9DkfQMP", locations: formattedLocation, }) .then((routeData) => { pathIndex++; const geoJson = routeData.toGeoJson(); console.log("calculateRoute ===>>", geoJson); drawRoute(geoJson, pathIndex); }); }, i * 3000); }); }); }) .catch((error) => { console.log(error); }); Django code : @api_view(['POST']) @permission_classes([AllowAny]) def solve_vrp(request): data = json.loads(request.body) print(data) an example of what I'm sending is : {"0,1": 5291, "0,2": 5291, "0,3": 5291, "1,0": 4795 ,"1,2": 0, "1,3": 0, "2,0": 4794, "2,1": 0, "2,3": 0, "3,0": 4795, "3,1": 0, "3,2": 0} but actually, I'm receiving only : {"0,1":5291, "0,2":5291, "0,3":5291, "1,0":4794, "1,2":0, "1,3":0, "2,0":4795, "2,1":0, "2,3":0} -
I can't get product vendor id in django
I am working on an e-commerce project. But the product vendor id is not registered in the database. I've tried many ways. I would be glad if you help. seller_id always comes empty What are your suggestions? models.py class Product(models.Model): name = models.CharField(verbose_name="Məhsulun adı", max_length=150) description = models.TextField( verbose_name="Məhsul haqda məlumat", null=True) price = models.FloatField(verbose_name="Məhsulun Qiymət") quantity = models.IntegerField(verbose_name="Məhsulun sayı",) seller = models.ForeignKey( Shop, on_delete=models.CASCADE, verbose_name="Məhsulun satıcısı", null=True ) categories = models.ManyToManyField( Category, verbose_name="Məhsulun kateqoriyaları", related_name='categories') tags = models.ManyToManyField(Tags, verbose_name="Məhsulun etiketləri") discount = models.IntegerField( null=True, blank=True, verbose_name="Endirim", default=0) active = models.BooleanField(default=True, verbose_name="Mağazada göstər",) created_at = models.DateTimeField(auto_now_add=True, null=True) colors = models.ManyToManyField(Colors, verbose_name='Məshulun rəngləri') views.py if request.method == 'POST' and 'addProduct' in request.POST: main_image = request.FILES['main_image'] # form = AddProductForm(request.POST) images = request.FILES.getlist('images') if form.is_valid(): form.seller = request.user.id print(request.user.id) form = form.save(commit=False) form.save() # Product.objects.create(seller=request.user) ProductImages.objects.create(product=form, image=main_image) ProductInfo.objects.create(product=form) for image in images: print(image) ProductImages.objects.create(product=form, image=image) return redirect('shop:shopProducts') else: print(form.errors) forms.py class AddProductForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AddProductForm, self).__init__(*args, **kwargs) self.fields['price'].widget.attrs.update( {'placeholder': 'Qiymət'}) self.fields['name'].widget.attrs.update( {'placeholder': 'Məhsulun Adı'}) for field in self.fields: self.fields[field].widget.attrs.update({'class': 'form-control'}) self.fields['active'].widget.attrs.update( {'class': ''}) class Meta: model = models.Product fields = ['name', 'description', 'price', 'colors', 'discount', 'quantity', 'active', 'categories', ] #'thumbnail','images', widgets = { 'price': forms.TextInput(), 'off': forms.TextInput(), } -
How to test the data with original data taken from user
I really need your help guys. I am working on a project and really confuse. Using Python, Jupyter Notebook Want to give the model inputs from the user to check what the model will predict (by giving them the original values[Text format + Numerical ] ) but for training I changed the test data below: I have trained the model by pre process it with Removing outliers-> Factorize(Converting to numerical) -> Normalize During Factorization I used this code def factorize_fun(df): obj_cols = df.loc[:, df.dtypes == object].columns for col in obj_cols: df[col] = pd.factorize(df[col])[0] +1 return df df6=factorize_fun(df6) In factorization it makes the data like 1,2,3,4 for any different values found in a column. Knn Imputer to complete the missing values import numpy as np from sklearn.impute import KNNImputer def knn_null(df): imputer = KNNImputer(n_neighbors=2) df1 = imputer.fit_transform(df) df2 = pd.DataFrame(df1, columns = df.columns) return df2 df6=knn_null(df6) It changed the date from this this I trained my model on numerical values and got good results. X_train, X_test, y_train, y_test = train_test_split(normalize(df6), y, test_size=0.2, random_state=0) rfc=RandomForestClassifier() rfc1=RandomForestClassifier( random_state=42, max_features='auto', n_estimators= 90, max_depth=8, criterion='gini' ) rfc1.fit(X_train, y_train) y_pred=rfc1.predict(X_test) print("Accuracy for Random Forest on CV data: ",accuracy_score(y_test,y_pred)) print(metrics.classification_report(y_test,y_pred)) df_cm = pd.DataFrame(confusion_matrix(y_test,y_pred), index = [i for … -
I want to write a if condition based in what url my user was before being took for the specific cart view
I'm building an ecommerce site and I built a specific view to handle with adding products in a cart, and after the product is added, my user is redirect to a store. But here is the thing, I want to see if my user was in the store view, where are all the products, of if he was in the product_detail view, where it shows only a specific user. So, if the user was in the store view, I want him to be redirected, after the product was added in the cart, to the store view. But if he was in the product_detail view, I want him to be redirected to this product_detail view. So basically I want to find a way to see in what view, or url, my user was, and then redirect in this way. I also would like to only use Django and no JavaScript, if it's possible. Here is my view that add a product to cart. def add_to_cart(request, slug): product = get_object_or_404(Product, slug=slug) order_item, created = OrderItem.objects.get_or_create( product=product, user=request.user ) order_qs = Order.objects.filter(user=request.user, complete=False) if order_qs.exists(): order = order_qs[0] if order.products.filter(product__slug=product.slug).exists(): order_item.quantity += 1 order_item.save() messages.info(request, 'This item quantity was updated') else: order.products.add(order_item) messages.info(request, … -
How to redirect user to requested url after login? (LoginRequiredMixin Django)
I don't know how to properly redirect user. I've tried so many solutions from the internet that I can't remember them now coz of my frustration. These solutions use def views but I have class views in my app and I don't know how to get this next parameter. I have a class view which requires login: class EditSportFieldView(LoginRequiredMixin, View): login_url = "/sign-in/" (...) I am at the url http://127.0.0.1:8000/sign-in/?next=/sport-field/edit/1/ and after login in I want to go to http://127.0.0.1:8000/sport-field/edit/1/ but instead I go back to the main page http://127.0.0.1:8000/ Here is my sigin in view class: class SignInView(LoginView): template_name = "sign-in.html" redirect_field_name = "sign-in" # def get_success_url(self): # return ("/") def get_redirect_url(self): redirect_to = self.request.POST.get( self.redirect_field_name, self.request.GET.get(self.redirect_field_name, "") ) return redirect_to Why I am such a noob? and how to solve it please? P.S. erros change so fast that I missed that now this redirection takes me to Page not found http://127.0.0.1:8000/accounts/profile/ -
How To Successfully Install Django Using PyCharm Terminal
PS C:\Users\ISAAC EDOKA\Desktop\pilot> pip install django Requirement already satisfied: django in c:\users\isaac edoka\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\p ython310\site-packages (4.0.4) -packages\python310\site-packages (from django) (3.5.2) Requirement already satisfied: sqlparse>=0.2.2 in c:\users\isaac edoka\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-p ackages\python310\site-packages (from django) (0.4.2) Requirement already satisfied: tzdata in c:\users\isaac edoka\appdata\local\packages\pythonsoftwarefoundation.python.3.10_qbz5n2kfra8p0\localcache\local-packages\p ython310\site-packages (from django) (2022.1) WARNING: You are using pip version 22.0.4; however, version 22.1 is available. You should consider upgrading via the 'C:\Users\ISAAC EDOKA\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe -m pi p install --upgrade pip' command. django : The term 'django' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 django --version + CategoryInfo : ObjectNotFound: (django:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException django : The term 'django' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path At line:1 char:1 django --version + CategoryInfo : ObjectNotFound: (django:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException -
How to convert svg to json and return it with JsonResponse in Django framework?
I got a view that takes JSON and converts it to.SVG file Next, I have to display this .svg image in my HTML file Using JsonResponse is mandatory because it returns other data not related to this question P.S. I'm using AJAX on the frontend to get some data from that view Is it possible to do this kind of manipulation with files or do you have other ideas on how to return SVG file to HTML? Thanks in advance