Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add two url argument to Django template url tag?
my django version is 2.0.5 my os version is ubuntu 20.04 I want to pass two url argument in Django template url tag,my url code is blow path('download/<str:bucket>/<str:object>/',views.Download.as_view(), name='download'),# appname= storage the code below can work <a href="{% url 'storage:download' bucket=bucket object='object.Key' %}">{{ object.Key }}</a> but the the code below doesn't work <a href="{% url 'storage:download' bucket=bucket object= object.Key %}">{{ object.Key }}</a> <a href="{% url 'storage:download' bucket object.Key %}">{{ object.Key }}</a> is there any way to make my code work? -
Django project how to find admin username and password
I found a Django project and failed to get it running in Docker container in the following way: git clone https://github.com/hotdogee/django-blast.git $ cat requirements.txt in this files the below dependencies had to be updated: kombu==3.0.30 psycopg2==2.8.6 I have the following Dockerfile: FROM python:2 ENV PYTHONUNBUFFERED=1 RUN apt-get update && apt-get install -y postgresql-client WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ For docker-compose.yml I use: version: "3" services: dbik: image: postgres volumes: - ./data/dbik:/var/lib/postgresql/data - ./scripts/install-extensions.sql:/docker-entrypoint-initdb.d/install-extensions.sql environment: - POSTGRES_DB=django_i5k - POSTGRES_USER=django - POSTGRES_PASSWORD=postgres ports: - 5432:5432 web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - dbik links: - dbik $ cat scripts/install-extensions.sql CREATE EXTENSION hstore; I had to change: $ vim i5k/settings_prod.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } Please below the logs after I ran docker-compose build docker-compose up Attaching to djangoblast_dbik_1, djangoblast_db_1, djangoblast_web_1 dbik_1 | db_1 | dbik_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization dbik_1 | db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db_1 | dbik_1 | 2021-05-19 10:45:54.221 UTC [1] LOG: starting PostgreSQL … -
TypeError in returned value django
I have this property for my table: @property def commission_percent(self): with connection.cursor() as cursor: # Data retrieval operation - no commit required cursor.execute('SELECT crowdfunding_offering.commission_percent FROM crowdfunding_offering WHERE crowdfunding_offering.id = %s ORDER BY crowdfunding_offering.id DESC LIMIT 1', (int(self.offering.id),)) row = cursor.fetchone() if not row is None: return row return 0 which returns 0.05. It's going exactly how I expected it, but when I try to use the value to compute for another property like so: def commission_due(self): if not self.commission_paid is None: return (self.invested * self.commission_percent) - self.commission_paid return self.invested * self.commission_percent I get this error: Exception Value: can't multiply sequence by non-int of type 'decimal.Decimal' I tried changing self.commission_percent to self.commission_percent() but I get this error: Exception Value: 'tuple' object is not callable I don't know what to do, and this is all very new to me. Any help is appreciated. -
Can't import views from application the the URLS of project in Django 3.1
I'm not able to import my views in the app folder to the URLS of project folder. I've tried every possible methods like 'from . import views' or 'from newapp import views as newapp_views' and 2-3 more alternatives that I searched on the internet. My app name is newapp and project name is newproject. Please help me. This is my models file: from django.db import models class User(models.Model): first_name=models.CharField(max_length=128) last_name=models.CharField(max_length=128) email=models.EmailField(max_length=256, unique=True) This is my URLS of newapp folder: from django.conf.urls import url from django.urls.resolvers import URLPattern from .models import views urlpatterns= [url(r'^$', views.users, name='users'), ] This is my views of newapp folder: from django.shortcuts import render from .models import User def index(request): return render(request, 'newapp/index.html') def users(request): user_list=User.objects.order_by('first_name') user_dict={'users': user_list} return render(request, 'newapp/users.html', context=user_dict) This is my URLS of newproect folder: from django.contrib import admin from django.urls import path,include from newapp import views urlpatterns = [ path('', views.index, name='index'), path('users/',views.users, name="users"), path('admin/', admin.site.urls), ] This is my settings file: from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'newapp' ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR,], 'APP_DIRS': True, … -
Django MPTT get specific child category
I have two models a category and a product model, the category is using django MPTT. I am unable to get or filter on a specific child. class Item(models.Model): title = models.CharField(max_length=150) merchant = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name="Merchants", on_delete=models.CASCADE, related_name="items" ) category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name="category" ) price = models.DecimalField(max_digits=9, decimal_places=2) discount_price = models.DecimalField( max_digits=9, decimal_places=2, blank=True, null=True ) class Category(MPTTModel): title = models.CharField(max_length=100) parent_category = TreeForeignKey( "self", blank=True, null=True, on_delete=models.CASCADE, related_name="sub_categories", ) slug = models.SlugField(max_length=100) vertical = models.ForeignKey(Vertical, on_delete=models.CASCADE, blank=True, null=True) class Meta: indexes = [GinIndex(fields=["title", "parent_category"])] verbose_name_plural = "categories" unique_together = ["slug", "parent_category"] class MPTTMeta: order_insertion_by = ['title'] parent_attr = 'parent_category' the problems I have when I run a queryset against a sub_category it continues to give me all the object in the main category items = Item.objects.filter(category__parent_category__sub_categories__slug='flu') However it is returning all items under the parent category not only the items that belong to the flu category many thanks -
Django view returning POST instead of GET request
So I have these working views for registration and login using POST requests, both of which returning profile.html. The problem is the login and registration views return a POST to the login or register urls when i submit the forms(according to cmd), to run the necessary functions. which means it is simply rendering the profile.html, but not running ITS view function. How do i have the form submissions send a GET to the profile view while still having them send POST for their own respective functions. Views: def log_in(request): if request.method == 'POST': form = log_form(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(request, username=username, password=password) if user is not None: print("user exists") login(request, user) return render(request, 'profile.html') else: print("user does not exist") print(form.errors) return render(request, 'login.html', { 'form2': log_form }) else: return render(request, 'login.html', { 'form2': log_form }) else: return render(request, 'login.html', { 'form2': log_form }) def profile(request, username): if request.method == 'GET': user = Users.objects.get(username=username) interests = [] interest_list = Interests.objects.filter(member=user)#i got 5 objs here for i in interest_list: interests.append(i.item) print('added interest') info = Bios.objects.get(author=user) return render(request, 'profile.html', { 'user': user, "interests": interests, 'info': info }) Urls: urlpatterns = [ path('reg/', views.register, name='register'), path('log/', views.log_in, … -
I can't display a google maps map with django
I am trying to display a map with django: {% block content %} {% load static %} <div id="map"></div> <script src="{% static 'display_map.js'%}"></script> <script src="https://maps.googleapis.com/maps/api/js?key=mykey&libraries=places&callback=initMap"></script> {% endblock %} And the display_map.js file is: let map; function initMap(){ map = new google.maps.Map(document.getElementById('map'), { center: { lat: -34.397, lng: 150.644 }, zoom: 8, }); } It does not show the map. Thank you -
Why Does My Django Project Reject React Tags?
In my project, I am trying to tie together Django and React. index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> {% load static %} <link rel="icon" href="{% static 'logofavicon.ico' %}" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta property="og:image" content="{% static 'Banner.png' %}"> <meta name="description" content="The future of digital content" /> <link rel="apple-touch-icon" href="{% static 'logo192.png' %}" /> <link rel="manifest" href="{% static 'manifest.json' %}" /> <title>Drop Party</title> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <script type="module" src="{% static 'index.js' %}"></script> <div id="root"></div> </body> </html> index.js import React from "react"; import ReactDOM from "react-dom"; import "./index.css"; import App from "./App"; import reportWebVitals from "./reportWebVitals"; import "./styleguide.css"; import "./globals.css"; ReactDOM.render( < React.StrictMode > < App / > < /React.StrictMode>, document.getElementById("root") ); reportWebVitals(); settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/frontend/' STATICFILES_DIRS = ( FRONTEND_DIR / 'build', FRONTEND_DIR / 'src', FRONTEND_DIR / 'public' ) Project Hierarchy Extension of this post. I have added in the script, but I have found that I get an Uncaught SyntaxError: Unexpected token '<' on line 9, which is where the React tag is. -
django inlineformset_factory not saving the froms data
Why the data of inlineformset_factory not saving? here is my code: models.py class HeaderImage(models.Model): header_image = models.ImageField() post = models.ForeignKey(Post, on_delete=models.CASCADE) froms.py BlogImageFormSet = inlineformset_factory(Post, # parent form HeaderImage, # inline-form fields=['header_image'] ,can_delete=False, extra=1) #views.py class BlogUpdateView(PermissionRequiredMixin,UpdateView): raise_exception = True permission_required = "blog.change_post" model = Post template_name = "blog_update_post.html" form_class = BlogPost def get_success_url(self): self.success_url = reverse_lazy('my-account') return self.success_url def get_context_data(self, **kwargs): context = super(BlogUpdateView, self).get_context_data(**kwargs) if self.request.POST: context['form_image'] = BlogImageFormSet(self.request.POST, instance=self.object) else: context['form_image'] = BlogImageFormSet(instance=self.object) return context def form_valid(self, form): context = self.get_context_data() image_form = context['form_image'] if image_form.is_valid(): self.object = form.save() image_form.instance = self.object image_form.save() return HttpResponseRedirect(self.get_success_url()) else: return self.render_to_response(self.get_context_data(form=form)) I am not understanding why data is not saving for inlineformset_factory field. -
Django JSONfield update element in list
I'm using a JSONField to store a list of elements in this format: [{"name": "field1", "value": "100"}, {"name": "field2", "value": "500"}] This is my model: from django.contrib.postgres.fields import JSONField class MyModel(models.Model): json_data = JSONField(default=list, null=True) # Create an empty list always I have a form to update the values stored in json_data, I update the data like this: obj = MyModel.objects.get(pk=1) json = obj.json_data # [{"name": "field1", "value": "100"}, {"name": "field2", "value": "500"}] new_data = {"name": "field2", "value": "99"} # data to update that comes from form fields_not_updated = [field for field in json if new_data['name'] != field['name']] # Create a list of elements that are not updated fields_not_updated.append(new_data) # Add the new data, output: [{"name": "field1", "value": "100"}, {"name": "field2", "value": "99"}] obj.json_data = fields_not_updated # set new json obj.save() # save object I was wondering if there is an easier or more efficient method to update the elements inside the list and save them in the JSONField using django functions or methods or directly using python. -
When I try to run my Django Project on safari I get a safari can't open page
My venv is running, and everything seems to be fine besides that I cant run it on safari. Any help would be greatly appreciated. Thank you -
Can't access ip 0.0.0.0 and ip 127.0.0.1
There's no problem with the code, but it doesn't work. The same applies when i change the port number or turn off the firewall. I'm sorry if there's a problem because this question was written with a translator. I've already tried many ways on the Internet. enter image description here # file name : index.py # pwd : /project_name/app/main/index.py from flask import Blueprint, request, render_template, flash, redirect, url_for from flask import current_app as app main= Blueprint('main', __name__, url_prefix='/') @main.route('/main', methods=['GET']) def index(): return render_template('/main/index.html') # file name : __init__.py # pwd : /project_name/app/__init__.py from flask import Flask app= Flask(__name__) from app.main.index import main as main app.register_blueprint(main) <!--file name : index.html--> <!--pwd : /project_name/app/templates/main/index.html--> <html> <head> This is Main page Head </head> <body> This is Main Page Body </body> </html> # file name : run.py # pwd : /project_name/run.py from app import app app.run(host="0.0.0.0", port=80) Serving Flask app "app" (lazy loading) Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. Debug mode: off Running on http://0.0.0.0:80/ (Press CTRL+C to quit) /error code/ http://0.0.0.0:80/ access > ERR_ADDRESS_INVALID or 127.0.0.1 - - [21/May/2021 06:41:30] "GET /show HTTP/1.1" 404 - -
Django creates two model instances instead of one
I'm trying to learn some django basics and have got strange result when I try to create some model instances using forms. This is my view: from django.shortcuts import render from .forms import ProductModelForm from .models import Product def create(request): form = ProductModelForm(request.POST or None) if form.is_valid(): obj = form.save(commit=False) data = form.cleaned_data Product.objects.create(title_text=data.get("title_text")) obj.save() return render(request, "test_app/create.html", {"form": form}) Form: from django import forms from .models import Product class ProductModelForm(forms.ModelForm): class Meta: model = Product fields = [ "title_text", ] And a template: {% block content %} <form action="." method="post">{% csrf_token %} {{ form }} <button type="submit">Save Model</button> </form> {% endblock %} Thanks in advance. -
submit button is not working in django form using crispy
I have a contact form in django and i use crispy in my template but in both Class base view and Function base view my submit button is not working and i have no errors. here is my fbv code i also tried it with cbv my template is using jquery,bootstrap,moment.js here is my code: models.py class ContactUs(models.Model): fullname = models.CharField(max_length=150, verbose_name="Full Name") email = models.EmailField(max_length=150, verbose_name="Email") message = models.TextField(verbose_name="Message") is_read = models.BooleanField(default=False) class Meta: verbose_name = "contact us" verbose_name_plural = "Messages" forms.py class CreateContactForm(forms.Form): fullname = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "Full Name"}), validators=[ validators.MaxLengthValidator(150, "Your name should be less than 150 character") ], ) email = forms.EmailField(widget=forms.EmailInput(attrs={"placeholder": "Email address"}), validators=[ validators.MaxLengthValidator(150, "Your email should be less than 150 character") ], ) message = forms.CharField(widget=forms.Textarea(attrs={"placeholder": "Your Message"})) views.py def contact_page(request): contact_form = CreateContactForm(request.POST or None) if contact_form.is_valid(): fullname = contact_form.cleaned_data.get('fullname') email = contact_form.cleaned_data.get('email') message = contact_form.cleaned_data.get('message') ContactUs.objects.create(fullname=fullname, email=email, message=message, is_read=False) # todo : show user a success message contact_form = CreateContactForm(request.POST or None) context = {"contact_form": contact_form} return render(request, 'contact_page.html', context) template <form id="contact-form" class="contact-form" data-toggle="validator" novalidate="true" method="post" action=""> {% csrf_token %} <div class="row"> <div class="form-group col-12 col-md-6"> {{ contact_form.fullname|as_crispy_field }} {% for error in contact_form.fullname.errors %} <div class="help-block with-errors">{{ error }}</div> {% … -
Using Django to create Strava Webhook subscription
I am trying to create a Strava webhook subscription to recieve events from users who have authorised my Strava application. I was able to successfully create a subscription using the code in this Strava tutorial. However, I don't understand Javascript, so can't adapt the code to my needs. I am therefore trying to replicate it's functionality within Python using Django. My basic approach has been to follow the setup outlined in the Django section of this webpage, then replace the code in the file views.py with the code below. I have tried to make the code function as similarly as possible to the Javascript function within the tutorial I linked above. However, I'm very new to web applications, so have taken shortcuts / 'gone with what works without understang why' in several places. from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.views.decorators.clickjacking import xframe_options_exempt import json @csrf_exempt @xframe_options_exempt def example(request): if request.method == "GET": verify_token = "STRAVA" str_request = str(request) try: mode = str_request[str_request.find("hub.mode=") + 9 : len(str_request) - 2] token = str_request[str_request.find("hub.verify_token=") + 17 : str_request.find("&hub.challenge")] challenge = str_request[str_request.find("hub.challenge=") + 14 : str_request.find("&hub.mode")] except: return HttpResponse('Could not verify. Mode, token or challenge not valid.') if (mode == 'subscribe' … -
Autocomplete for input with Django, Bootstrap and JQuery
I have a form in Django + Bootstrap/JQuery, and the fields (labels/inputs) are generated from a ModelForm, that is, directly from Django and not in the .html, just like this: <div class = "panel" id = "personal_data"> <div class = "panel-body"> {% bootstrap_form client_form%} </div> </div> This "client_form" is a .py, which contains a ModelForm, which contains the fields automatically generated when the page is loaded My goal is to make an autocomplete on a specific input of this form, for example "Client Name". This autocomplete would show names the same as those typed by the user in real time, and each name would have a link to redirect to another page, it could be, for example, a page to change that customer's data The autocomplete data must come from a function that queries the database! Consider that this function already exists I tried to do this with Typeahead and Bloodhound but I couldn't -
AttributeError: 'NoneType' object has no attribute 'attname'
I am using this django_multitenant library to implement multi tenancy. I tried creating an object in python manage.py shell using the below code >>> from ReportingWebapp.models import * >>> from django_multitenant.utils import * >>> org = Organization.objects.first() >>> set_current_tenant(org) >>> get_current_tenant() <Organization: Organization object (1)> >>> a = ApplicationSetting(username="a",password="b",client_secret="c",client_id="d",tenant_id="e") Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\hp\Desktop\reporting_multitenant\env\lib\site-packages\django_multitenant\mixins.py", line 58, in __init__ super(TenantModelMixin, self).__init__(*args, **kwargs) File "C:\Users\hp\Desktop\reporting_multitenant\env\lib\site-packages\django\db\models\base.py", line 416, in __init__ self._state = ModelState() File "C:\Users\hp\Desktop\reporting_multitenant\env\lib\site-packages\django_multitenant\mixins.py", line 62, in __setattr__ if (attrname in (self.tenant_field, get_tenant_field(self).name) File "C:\Users\hp\Desktop\reporting_multitenant\env\lib\site-packages\django_multitenant\mixins.py", line 115, in tenant_field return self.tenant_id File "C:\Users\hp\Desktop\reporting_multitenant\env\lib\site-packages\django\db\models\query_utils.py", line 149, in __get__ instance.refresh_from_db(fields=[field_name]) File "C:\Users\hp\Desktop\reporting_multitenant\env\lib\site-packages\django\db\models\base.py", line 623, in refresh_from_db db_instance_qs = self.__class__._base_manager.db_manager(using, hints=hints).filter(pk=self.pk) File "C:\Users\hp\Desktop\reporting_multitenant\env\lib\site-packages\django\db\models\base.py", line 573, in _get_pk_val return getattr(self, meta.pk.attname) File "C:\Users\hp\Desktop\reporting_multitenant\env\lib\site-packages\django\db\models\query_utils.py", line 147, in __get__ val = self._check_parent_chain(instance) File "C:\Users\hp\Desktop\reporting_multitenant\env\lib\site-packages\django\db\models\query_utils.py", line 163, in _check_parent_chain return getattr(instance, link_field.attname) AttributeError: 'NoneType' object has no attribute 'attname' Why did i get this error? Tenant is already set in thread local. -
Django - catch migrating process
I am using django-background-tasks, which is unfortunately short of maintainers atm and has an oen issue: click. it results in errors when deploying and can easily be worked around with by just commenting django-background-tasks related functions when migrating. as I do the process fairly often: Can I check for migrating/makemigrations being in process? something like: if migrating() == True: pass else: activate_django_background_tasks_related_stuff() -
Reverse for 'projeto' with no arguments not found. 1 pattern(s) tried: ['delete/(?P<pk>[0-9]+)/projeto/$']
Hail Devs. I have an app that in the index I call some queries with ForeignKey between table fields, using the User as argument. The views work for other tables without ForeignKey. But when I invoke the CRUD (delete, update, create) functions that request the database, it returns an error: Request Method: GET Request URL: http://127.0.0.1:8000/delete/13/ Django Version: 3.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'projeto' with no arguments not found. 1 pattern(s) tried: ['delete/(?P<pk>[0-9]+)/projeto/$'] Exception Location: C:\webcq\venv\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\webcq\venv\Scripts\python.exe Python Version: 3.8.6 Python Path: ['C:\\webcq', 'C:\\webcq\\venv', 'C:\\webcq\\venv\\lib\\site-packages'] Server time: Thu, 20 May 2021 21:03:07 +0000 url.py project from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('', include('imagem.urls', namespace='home')), path('view/<int:pk>/', include('imagem.urls', namespace='view')), path('edit/<int:pk>/', include('imagem.urls', namespace='edit')), path('update/<int:pk>/', include('imagem.urls', namespace='update')), path('delete/<int:pk>/', include('imagem.urls', namespace='delete')), ] urls.py app from django.urls import path from . import views app_name = 'imagem' urlpatterns = [ path('', views.home, name='home'), path('projeto/', views.projeto, name='projeto'), path('form/', views.form, name='form'), path('create/', views.create, name='create'), path('view/<int:pk>/', views.view, name='view'), path('edit/<int:pk>/', views.edit, name='edit'), path('update/<int:pk>/', views.update, name='update'), path('delete/<int:pk>/', views.delete, name='delete'), ] views.py app The views work, but do not redirect to the view name and return the above error. def edit(request, pk): data = {} data['db'] … -
How can I add a relationship in Django to a model that's created before the model I need to reference?
I have two different models: Movies and Characters. I want Characters to have a movies field where I can see the movies in which the characters appear and I want Movies to have the characters that appear in them. However, since one of the models has to be defined first, I am not sure how to make the first one relate to the second one. This is my code so far but this doesn't show 'movies' when I access the Character model: class Character(models.Model): image = models.ImageField() name = models.CharField(max_length=100) age = models.IntegerField() story = models.CharField(max_length=500) def __str__(self): return self.name class Movie(models.Model): image = models.ImageField() title = models.CharField(max_length=100) creation_date = models.DateField(auto_now=True) rating = models.IntegerField() characters = models.ManyToManyField(Character) def __str__(self): return self.title I am not sure how to add the movies to the Character model since it's referenced before the Movie model, how can I accomplish this? Thank you. -
how to implement PUT method in Django views
I am new to Django. I have assigned a task to create a PUT API. I don't know how to proceed. Already POST method is there: if request.method == 'POST': """ add a new rule """ data = JSONParser().parse(request) validated_data=data ruleParam=validated_data.pop('ruleParam') ruleTypeDetail=validated_data.pop('ruleTypeDetail') rule= Rule.objects.create(**validated_data) for rp in ruleParam: RuleParameter.objects.create(rule=rule,**rp) print(validated_data) if validated_data['ruleType']=='Simple': qcData = ruleTypeDetail.pop('qualifyingCaluse') fl=FieldList.objects.get(id=ruleTypeDetail['allFieldList']['id']) ag=AggregateFunction.objects.get(id=ruleTypeDetail['allAggregateFunction']['id']) fldList= ruleTypeDetail.pop('allFieldList') aggFunction = ruleTypeDetail.pop('allAggregateFunction') simpleRule=RuleSimple.objects.create( rule=rule, fieldList = fl, aggregateFunction = ag, **ruleTypeDetail ) for qc in qcData: fl=FieldList.objects.get(id=qc['fieldListDetail']['id']) cl=ConditionList.objects.get(id=qc['conditionListDetail']['id']) QualifyingClause.objects.create( ruleSimple=simpleRule, detailSrl=qc['detailSrl'], fieldList=fl, conditionList=cl, value=qc['value'] ) Please help me or show mee similar to this. -
Django project not rendering React.js
In my project, I am trying to tie together Django and React. index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> {% load static %} <link rel="icon" href="{% static 'logofavicon.ico' %}" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta property="og:image" content="{% static 'Banner.png' %}"> <meta name="description" content="The future of digital content" /> <link rel="apple-touch-icon" href="{% static 'logo192.png' %}" /> <link rel="manifest" href="{% static 'manifest.json' %}" /> <title>Drop Party</title> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> </body> </html> index.js import React from "react"; import ReactDOM from "react-dom"; import "./index.css"; import App from "./App"; import reportWebVitals from "./reportWebVitals"; import "./styleguide.css"; import "./globals.css"; ReactDOM.render( < React.StrictMode > < App / > < /React.StrictMode>, document.getElementById("root") ); reportWebVitals(); settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/frontend/' STATICFILES_DIRS = ( FRONTEND_DIR / 'build', FRONTEND_DIR / 'src', FRONTEND_DIR / 'public' ) Project Hierarchy I have looked at this post, and confirmed that this solution is not applicable for me. The primary issue, I think, is that Django is serving the html, but not running the .js, so I'm unsure of where to go with this. I have also confirmed that the image linking is … -
Two packages with the same import name conflicting
I am interacting with the InfusionSoft API in a Django project that I am working on. I would like to use both infusionsoft-client package and infusionsoft-python. However, they both require import infusionsoft so now I am getting error messages regarding infusionsoft-client attributes that are already working. How can I set these up so that they do not conflict? -
how to make sure if an instance of a model does not exist then create one else return instance all ready exists
i am stuck at a point where i have to make sure if a payment does not exists corresponding to an order then create one else return payment all ready done. Bellow is the code what i have tried: if(transaction_status=='SUCCESS'): try: payment= Payments.objects.get(orders=order,direction=direction) except (Payments.DoesNotExist): payment = Payments( orders=order, amount=amount, is_active='True' ) payment.full_clean() payment.save() return Response({"payment":"All ready exists"}) if there is a better way please do suggest. -
Django Class based views and their cohesion
I'm coming from laravel and trying to do something like laravael model controller where functions are mapped to request methods and no of arguments. I tried to find something similar in Django but the class based views are too scattered. The conventional approach with CBVs(ListView,TemplateView,GenericEditView) won't let me implement all the function in one class. That would make a number of classes and a number of URLs to handle also, so with my low knowledge, I have done the thing below. Please check and guide. class InvoiceView(View): @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): if (args or kwargs) and request.method == 'GET': if kwargs['data'] =='create': return self.create(request,*args,**kwargs) else: return self.show(request, *args, **kwargs) else: return super().dispatch(request, *args, **kwargs) def get(self,request): all_invoice = Invoice.objects.all() content = {'invoices': all_invoice} return render(request, 'Invoicing/invoice/index.html', context=content) @transaction.atomic def post(self, request): data = json.loads(request.POST.get('data')) inv = Invoice(payment_mode=data['invoice_details']['payment_mode'], total_amount=float( data['invoice_details']['total_amount']), created_by=User.objects.get(pk=1)) inv.customer = Customer.objects.get( pk=data['invoice_details']['customer_id']) inv.full_clean(exclude='id') inv.save() inv_data = data.pop('invoice_details') for key in data: if key in ('sublimation', 'printing'): self.addOrder(inv, data[key], key) elif key in ('designing', 'transfer', 'ink', 'paper', 'part'): self.addItems(inv, data[key][0], key) message = 'Stored successfuly' if inv_data['payment_mode'] == '0': inv.payment_status = 0 inv.save() pmnt = Payment(invoice=inv, amount=inv.total_amount, payment_method=2) pmnt.save() return HttpResponse(json.dumps({ 'message': message, 'link': reverse('invoice'), 'template': render_to_string('Invoicing/invoice/printPreview.html',context=self.extract_invoice_data(inv.id)) …