Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to only allow users of a specific country to access my django website?
I am building a website powered by django to serve a particular country only. Then, how can i redirect traffic from all other countries to an specific error page? -
Django query using ManytoManyField
Using example code: from django.db import models class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() How could I get the name of the last 5 persons and their group's name order by date_joined? Something like: "name1" "group1" "19/02/2019" "name2" "group1" "19/02/2019" "name1" "group2" "19/02/2019" "name3" "group1" "18/02/2019" "name4" "group2" "17/02/2019" I have tried many options but I am not able to do it :S Thanks in advance. -
Django rest framework - Parse key value pair in post()
When user enters in POST API data, they would enter A and B key value pairs. I want to modify the post() to fit my needs. I want to parse the below when user clicks submit or posts API data. Anyway to parse those fields before it's returned on api view(or when user clicks submit)? This is what user is attempting to post using POST API. [ { "A": "1234", "B": "12345", }, ] What I did: class MyModelList(generics.ListCreateAPIView): queryset = MyModel.objects.all() serializer_class = MyModeSerializer permission_classes = (permissions.IsAuthenticated,) def post(self, request, *args, **kwargs): ##parse A values from key value pair so that value == 1234 ##parse B values from key value pair so that value == 12345 return self.create(request, *args, **kwargs) -
How to loop through json object converted to python dictionary
I try to create site which will execute data from api. Api endpoint retrieve data in json format here is example of retrieved data { "api": { "results": 22, "countries": { "1": "Argentina", "2": "Belarus", "3": "Belgium", "4": "Brazil", "5": "Bulgaria", "6": "China", "7": "Costa Rica", "8": "Denmark", "9": "England", "10": "France", "11": "Germany", "12": "Iceland", "13": "Italy", "14": "Japan", "15": "Netherlands", "16": "Norway", "17": "Poland", "18": "Portugal", "19": "Spain", "20": "Sweden", "21": "Wales", "22": "World" } } } I created a Country model for storing this data in database (postgreSql) here is model code class Country(models.Model): name = models.CharField(max_length = 20) country_id = models.IntegerField() than i create custom management command which will execute data from api from django.core.management.base import BaseCommand, CommandError from data.models import Country import requests import json def extracting(): country_req = requests.get("https://api-football-v1.p.rapidapi.com/countries", headers = {"X-RapidAPI-Key": "rRVyARf9ESmshWSiNIjBqkYcTr0jp1nQh2JjsnNGNlcEYXM1XI"}) parsed_string = json.loads(country_req.text) print(type(parsed_string)) return parsed_string class Command(BaseCommand): def handle(self, **options): print(extracting()) than i wrote code which will get executed data from API and store it into a database for this purpose i wrote the following from django.core.management.base import BaseCommand, CommandError from data.models import Country import json from .extract import extracting def store_data(): for key, value in parsed_string: country_id = key … -
Use Multiple Class Based Views on Single Template in Django
I have Class based views one is SubjectCreateView And other is CourseCreateView for adding new subject and course resp. Both these views have same template structure. I want to use same template for both views. Problem is that it works only for SubjectCreateView (which is defined before CourseCreateView). also tell if you have better solution. -
Python FileNotFound Djano test media
I'm creating a django project that will accept user content, and during development I'm trying to create a test case that will test that the model uploads normally. I have a file structure like so: Site |----temp | |----django-test |----app |----test_image.jpg |----test_manual.pdf |----tests.py My test case code is such: from django.test import TestCase, override_settings from django.core.files import File import sys import os from .models import Manual # Create your tests here. class ManualModelTests(TestCase): @override_settings(MEDIA_ROOT='/tmp/django_test') def test_normal_manual_upload(self): in_image = open(os.path.join('manuals','test_image.jpg'), 'r+b') in_pdf = open(os.path.join('manuals','test_manual.pdf'), 'r+b') thumbnail = File(in_image) in_manual = File(in_pdf) new_manual = Manual.objects.create( photo=thumbnail, manual=in_manual, make='yoshimura', model='001', year_min=2007, year_max=2010 ) #uploaded_image = open(os.path.join('temp','django_test','images','test_image.jpg'), 'r+b') #uploaded_pdf = open(os.path.join('temp','django_test','manuals','test_manual.pdf'), 'r+b') #self.assertIs(open(), in_image) #self.assertIs(uploaded_img, in_image) #self.assertIs(uploaded_pdf, in_pdf) Here is the model code: class Manual(models.Model): photo = models.ImageField(upload_to="photos") make = models.CharField(max_length=50) model = models.CharField(max_length=100) manual = models.FileField(upload_to="manuals") year_min = models.PositiveIntegerField(default=0) year_max = models.PositiveIntegerField(default=0) For some reason I'm getting a FileNotFound upon opening 'test_image.jpg'). My questions are Why am I getting this error and how do I rectify it? Does my commented section using self.assertIs look correct? -
Django formsets - join two modelformsets to edit fields in BOTH models
I would like to edit fields in two models as part of one form. I know I can do this with inline_formsets - however I want to edit both the parent and child model, but I cannot work out how to do this with inline_formets. My models.py are: class ResultClass(models.Model): result_id = models.ForeignKey(Result,on_delete=models.CASCADE, db_column='result_id') evidence = models.TextField(null=True, blank=True) classified_by = models.ForeignKey(User, on_delete=models.CASCADE, db_column='classified_by', related_name='classified_by', null=True, blank=True) class Meta: db_table = "result_class" unique_together = (('result_id', 'evidence'),) class ReportedResult(models.Model): sample_id = models.ForeignKey(Sample, on_delete=models.CASCADE, db_column='sample_id') result_class_id = models.ForeignKey(ResultClass, on_delete=models.CASCADE, db_column='result_class_id', related_name='result_class_id', null=True, blank=True) reported = models.BooleanField(default=False) date_reported = models.DateTimeField(auto_now=False, null=True, blank=True) class Meta: db_table = "reported_result" unique_together = (('sample_id', 'result_class_id'),) So in the case that I have 4 outstanding Result objects that have not been classified, I would create empty instances of ResultClass and ReportedResult for each Result object. Then I can make model_formsets for each model: forms.py: class ResultClassForm(forms.ModelForm): evidence = forms.CharField( widget=forms.Textarea(attrs={'rows': 3, 'cols': 60}), label='Evidence:', required=False, ) class Meta: model = ResultClass fields = ( 'id', 'evidence', ) class ReportedResultForm(forms.ModelForm): report = forms.ChoiceField(choices=( PRIMARY_CHOICES ) ) class Meta: model = ReportedResult fields = ( 'id', 'report', ) Now in my views I create empty instances of ResultClass and ReportedResult objects … -
Django manytomany choicebox
I would like to implement a choicebox where the user can select the appropriate options and 'transfer' them to a 'selected box' before saving. Django has this for the admin interface , like in this post, but how to implement it in a normal website? Any links to relevent tutorials or an exampled based on te following would be welcome. Here are my models for managed tables of the many2many relationship. # models.py class Container(models.Model): container_id = models.AutoField(primary_key=True) location_id = models.ForeignKey(Location, db_column='location_id', on_delete = models.PROTECT) icon_desc = models.ForeignKey(Icon, db_column='icon_desc', null=True, blank=True, default='Box',on_delete = models.PROTECT) container_name = models.CharField(max_length=50, blank=True, null=True) class Sample(models.Model): sample_id = models.AutoField(primary_key=True) containers = models.ManyToManyField(Container, through='JoinSampleContainer', through_fields=('sample_id', 'container_id'), related_name='sample') class JoinSampleContainer(models.Model): id = models.AutoField(primary_key=True) sample_number = models.IntegerField() container_id = models.ForeignKey(Container, db_column='container_id', on_delete = models.PROTECT) sample_id = models.ForeignKey(Sample, db_column='sample_id', on_delete = models.PROTECT) In my Views.py I have for a normal form setup: def assignsample(request): if request.method == "POST": form = AssignForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('alldepotsamples') else: form = AssignForm() return render(request, 'depotsample/assignsample.html', {'form': form}) And the form: class AssignForm(forms.ModelForm): class Meta: model = Sample fields = ( 'sample_id', 'containers' ) This is presented in the html using the placeholders: {{ form.sample_id}} {{ form.containers}} -
Django Rest Framework - Upon POST data, run script
I am using Django Rest Framework. I want to run a script upon someone using POST API to enter data into django rest framework. So once someone enters in below data, I want to run myscript.py. However, is my implementation correct? It doesn't seem to run accurately. [ { "A": "1234", "B": "12345", }, ] What I did: class MyModelList(generics.ListCreateAPIView): queryset = MyModel.objects.all() serializer_class = MyModeSerializer permission_classes = (permissions.IsAuthenticated,) def post(self, request, *args, **kwargs): exec(open('myscript.py').read()) return self.list(request, *args, **kwargs) -
How to get dynamic_form data in django view with request object
I have Django Form and Posting data to server Form Post Data is ( from browser network tab output ) is _continue Save+and+continue+editing actionProfile 2 csrfmiddlewaretoken mPssgHvxxP6rfefTd4bYTa0r5DPNQuHk8nQZ69ONlitoWYNjlQqiIrF8oru2Y9b6 descriptions test dynamic_form[0]['name'] variable_name dynamic_form[0]['type'] 1 dynamic_form[0]['values'] variable_default_val git_tag master git_url https://12.20.24.180/root/google.git isHaveCustomField on server_groups 20 status 0 tags BladeLogic version 1.6 Now my Question is - How to get dynamic_form data in django view with request object Note: dynamic_form is list of input text and want this convert into JSON to store in DB. -
3D .obj renderer that can be fit into a canvas in HTML and JS
I'm new at web development, and I'm making a little webapp in Django for my D&D players. There is an "Items" page in the nav that leads to a dynamic item list with contextual buttons. It's looking pretty good! The items follow this structure in the DOM: bootstrap-card boostrap-list-header "Items" bootstrap-ul bootstrap-li-1 bootstrap-row img-of-the-object div-with-info-about-it (name, description, quantity...) contextual-btn bootstrap-li-2 ... bootstrap-li-n Now my question is: How could I replace the "img-of-the-object" with a little 3D renderer to have, for example, little red potions in 3D spinning. Preferably I'd like this engine to be able to render .obj files and overlap a texture on them, as the 3D designer I use (the same one Hypixel uses for their models, I forgot the name) exports that, an .obj and a .png this the skin of the model Thanks you all! -
User model mixin with django
I'm creating a custom User model in Django. I already had a base class for my models, which I now separated using a mixin: from django.db.models import Manager as DjangoModel class ModelMixin(DjangoModel): class Meta: abstract = True objects = Manager() # Not relevant creation_date = DateTimeField(auto_now_add=True, help_text=_('The date in which the database entry was created'), verbose_name=_('Creation date')) last_update = DateTimeField(auto_now=True, help_text=_('The last time that the database entry was updated'), verbose_name=_('Last update')) class Model(ModelMixin): class Meta(ModelMixin.Meta): abstract = True Model is supposed to be a base class of nearly all models I create. In this case, I'm trying to inherit from AbstractBaseUser and ModelMixin: class User(AbstractBaseUser, ModelMixin): objects = UserManager() EMAIL_FIELD = 'email' USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] email = EmailField(unique=True, help_text=_('Email address'), error_messages={ 'unique': _('This email address is already registered.') } ) is_active = BooleanField( default=False, help_text=_('Whether the user is active') ) However, the mixin migrations are not being applied, as I can see be describing the table on the database: CREATE TABLE IF NOT EXISTS "futils_user" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "password" varchar(128) NOT NULL, "last_login" datetime NULL, "email" varchar(254) NOT NULL UNIQUE, "is_active" bool NOT NULL); Notice that the creation_date and last_update fields are not … -
Saving process data on another table in the database
I'm working on a process for my company. Doing this i have found it necesary to store data that is being inserted in the proccess. My process is working fine but instead of saving in my other model, it keeps on saving the data on the table that corresponds to the process and not my other model. models.py from __future__ import unicode_literals from datetime import datetime from django.db import models from viewflow.models import Process from django.contrib.auth.models import User class DeliveryProcess(Process): #### Asignador ### nombre_del_entregable= models.CharField(max_length=150) fecha_inicio=models.DateField(auto_now_add=False, default=datetime.now) fecha_de_terminacion=models.DateField(auto_now=False, default=datetime.now) ejecutor=models.ForeignKey( User,on_delete=models.CASCADE, null=True, related_name='+') observaciones_asignador=models.TextField() ##### Ejecutor ##### fecha_de_ejecucion=models.DateField( auto_now_add=False, default=datetime.now) oberservaciones_ejecutor=models.TextField() finalizado= models.BooleanField(default=False) revisor=models.ForeignKey( User,on_delete=models.CASCADE, null=True, related_name='+') aprobacion_final= models.BooleanField(default=False) anadir_revisor= models.BooleanField(default=False) ##### Revisor ##### # aprobacion_final= models.BooleanField(default=False) # anadir_revisor= models.BooleanField(default=False) # nuevo_revisor= models.ForeignKey( # User,on_delete=models.CASCADE, null=True, related_name='+') # obserservaciones_revisor= models.TextField() class Revisiones(models.Model): id_revision= models.AutoField(primary_key=True) fecha_de_revision=models.DateField(auto_now_add=False, default=datetime.now) revisor=models.ForeignKey(User,on_delete=models.CASCADE, null=True, related_name='+') aprobacion_final= models.BooleanField(default=False) anadir_revisor= models.BooleanField(default=False) observaciones_revisor= models.TextField() flows.py from __future__ import unicode_literals from viewflow import flow from viewflow.base import this, Flow from viewflow.flow.views import CreateProcessView, UpdateProcessView from viewflow.lock import select_for_update_lock from .models import DeliveryProcess from viewflow import frontend from . import views @frontend.register class Delivery_flow(Flow): process_class = DeliveryProcess start = ( flow.Start( CreateProcessView, fields=["nombre_del_entregable", "fecha_inicio", 'fecha_de_terminacion', 'ejecutor','observaciones_asignador'] ).Next(this.ejecutar) ) ejecutar = ( … -
Upon POST request, execute a script
I created a API endpoint using django rest at http://0.0.0.0/v1/api. The contents of http://0.0.0.0/v1/api are as follows [ { "A": "1234", "B": "12345", }, ] What I want to do is when someone sends POST request to that address, run test.py I created below function in the view to run test.py. But, nothing happens when one sends post request. As shown below, someone posted key value pairs using POST API request. What am I missing here? Is it my directory? [ { "A": "1234", "B": "12345", }, { "A": "4567", "B": "45678", } ] Below is my views.py class ListAPISView(generics.ListCreateAPIView): """ Provides a get method handler. """ queryset = APIS.objects.all() serializer_class = APISSerializer def index(request): if request.method == 'POST': exec(open('/home/test.py').read()) return render(request, 'index.html', {}) -
Problems using both pageview counter and cache in django
I'm creating a django app for comics and having a code in my views.py of an app like this: @comic_inc @cache_page(settings.CACHE_S) //CACHE_S = 60 @vary_on_cookie def comic(request, com): try: cobj = Comic.gen_comic(com, request.user.id) if request.GET.get('sort') == '2': chaps = Chapter.objects.filter(published=True, comic = cobj).order_by('num','snum','volume') else: chaps = Chapter.objects.filter(published=True, comic = cobj).order_by('-num','-snum','-volume') return render(request, 'base/comic.html', {'comic': cobj, 'chapters':chaps}) except Exception as e: return render(request, 'base/comic.html', {'error': 'Comic not found'}) the @comic_inc is a decorator I created when I was trying to implement this solution: Counting "page views" or "hits" when using cache the decorator code is as below: def comic_inc(view_func): def _wrapped(*args,**kwargs): Comic.objects.filter(slug=kwargs.get('com')).update(pageviews=F('pageviews')+1) return view_func(*args,**kwargs) return _wrapped I didn't particularly specify any CACHE in django settings since there is already a default cache django.core.cache.backends.locmem.LocMemCache that works perfectly fine for development (shows up properly in debug toolbar). Additionally I did try memcached (downloaded and ran memcached -m 512 -vvv in CMD and it worked perfectly). Either way the result was the same, the pageviews is updated only when cached page times out and only increased by 1. I don't mind that the view value is not changed for every refresh on the cached template page but I atleast want the value to be … -
How to populate a postgresql database using python
I'm new in Python and Django and maybe I'll be crucified because of my code, but I'm consuming an API and using its data to populate a Postgresql database. Here is my code. Please, be gently: insert-city-cinema.py import json import urllib3 import psycopg2 import datetime conn = psycopg2.connect(database="db", user="user", password="pass", host="db", port="port") cur = conn.cursor() http = urllib3.PoolManager() url = "https://api-content.com/" urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) try: response = http.request('GET', url) data = json.loads(response.data.decode('utf-8')) address_id = 0 city_id = 0 for i in data: address_name = i['address'] address_number = i['number'] address_district = i['neighborhood'] address_zipcode = i['districtAuthorization'] address_lat = i['geolocation']['lat'] if 'geolocation' in i else 0.0 address_lng = i['geolocation']['lng'] if 'geolocation' in i else 0.0 city_name = i['cityName'] city_state = i['uf'] query = (""" INSERT INTO address VALUES (%s, %s, %s, %s, %s, %s, %s); """ ) data = (address_id, address_name, address_number, address_district, address_zipcode, address_lat, address_lng) cur.execute(query, data) conn.commit() theather_info_city_id = address_id address_id += 1 query = (""" INSERT INTO city VALUES (%s, %s, %s); """ ) data = (city_id, city_name, city_state) cur.execute(query, data) conn.commit() theather_info_city_id = city_id city_id += 1 cur.close() except IOError as io: print("ERROR!") And here is the command to create the tables: tables.py #!/usr/bin/python import psycopg2 def create_tables(): commands = ( … -
How do I auto update a field in Django
I have a Model: class Development(models.Model): id = models.AutoField(primary_key=True) logno = models.CharField(max_length=13, unique=True) insurer = models.ForeignKey(InsName, on_delete=models.SET_NULL, null=True, blank=False, verbose_name="Client") policy = models.ManyToManyField(Policy, blank=True) platform = models.ManyToManyField(Platform) documents = models.ManyToManyField(Document) active = models.BooleanField(default=True) Within the development detail template I want a button that when clicked changes the active field from True to False. I cannot find a simple way of doing this. I know I need to do something in my VIEWS.PY but I'm not sure what. The button is currently: <form action="" method = "POST"> <input type="submit" name="archive" class="btn btn-primary pull-right" value="Archive" /> </form> -
user to user messaging with django-postman
I'm new using django-postman and django and I just downloaded a copy of the django-postman package to use with my app. I added 'postman' to the INSTALLED_APPS settings.py of my project and url(r'^messages/',include('postman.urls',namespace='postman',app_name='postman')), in urls.py. However, I'm not sure where to put the downloaded package and integrated with my project. I think I added the app to my Python path with pip install django-postman==3.6.2, but when I use url(r'^messages/',include('postman.urls',namespace='postman',app_name='postman')) my django program says that there's not an app called 'postman'. How do I include the django-postman app to my project? Also since the app_name='postman' in urls.py is not longer valid for python 3.6 should I just take it out of the statment? -
Ajax error when searching for records in datatables processed server side in Django
My problem is that i can not search in my search-bar for a specific record(ex snumber) in my datatables. Browser raises the error: DataTables warning: table id=warehouse - Ajax error. For more information about this error, please see http://datatables.net/tn/7 Below is my code. My view class ProductSerialNumbersListJSon(LoginRequiredMixin,BaseDatatableView): # my model model = ProductSerialNumbers columns = ['snumber' , 'order','product','registration_date'] order_columns = ['snumber','order','product','registration_date'] max_display_length = 100 def get_initial_queryset(self): print("FETCHED DATA") #print(ProductSerialNumbers.objects.filter(Q(snumber__isnull=True)|Q(order_id__isnull=True)|Q (order_id__finished=0)).count()) return ProductSerialNumbers.objects.filter(Q(snumber__isnull=True)|Q(order_id__isnull=True)|Q (order_id__finished=0)) def render_column(self, row, column): return super(ProductSerialNumbersListJSon, self).render_column(row, column) My template <script language="javascript"> $(document).ready(function () { /* Here begins the DataTable configuration. */ $('#warehouse').DataTable({ /* Tell the DataTable that we need server-side processing. */ "serverSide": true, "paging": true, "pageLength": 10, "processing": true, "searching": true, /* Set up the data source */ ajax: { url: "{% url "warehouse_list_json" %}" }, "columns": [ {name: "snumber",}, {name: "order",}, {name: "product",}, {name: "registration_date",}, ] }); }); </script> What I am missing here in order to search correctly? -
Update field based on a ManyToManyField in Django model when saving
I have a model Sale defined as follows: from django.db import models class Sale(models.Model): sale_name = models.CharField(max_length = 30) lead_seller = models.ManyToManyField(Employee, related name = "lead") sellers = models.ManyToManyField(Employee, related name = "sellers") lead_share = models.DecimalField(max_digits = 4, decimal_places = 3, null = True, blank = True) sellers_share = models.DecimalField(max_digits = 4, decimal_places = 3, null = True, blank = True) def __str__(self): return self.sale_name And I have created a front-end form where people can register new sales. On saving, I want to compute the "commission" to each seller. E.g. the leads gets 10% and other sellers get 5%. This rate is constant, and thus commission is lower when more sellers are involved in a single sale. I have tried the following: from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=Sale, dispatch_uid="update_shares") def update_shares(sender, instance, **kwargs): no_leads = Sale.lead_seller.through.objects.filter(sale_id = instance.id).count() no_sellers = Sale.sellers.through.objects.filter(sale_id = instance.id).count() instance.lead_share = 0.1/no_leads instance.sellers_share = 0.05/no_sellers However it seems the database query gives 0: the error I get when trying to create a new entry is "Zero Division Error /". Any suggestions on how I can get the number of leads/sellers in a smooth fashion? -
Cannot send an array-type variable from React.js front-end to Django backend
I need to send an array from React.js frontend to the Django backend. I can easily send all variables, except just an array csvData. I see that console.log("csvData", csvData) returns the following data: NUM,COL1,COL2 1,300,500 2,566,VL This is the code of React component called BatchFlights: import React, { Component, Fragment } from 'react'; import TopControls from "./layout/batch/TopControls" import MainContent from "./layout/batch/MainContent" import BottomControls from "./layout/batch/BottomControls" import styles from "./layout/styles/styles"; import { withStyles } from "@material-ui/core/styles"; class BatchFlights extends Component { constructor(props) { super(props); this.state = { csvData: [], temperature: 20, visibility: 5999.66, windIntensity: 8.0, prediction: 0, labelWidth: 0 }; this.handleChange = this.handleChange.bind(this); }; componentDidMount() { this.fetchData(); }; updateDelay(prediction) { this.setState(prevState => ({ prediction: prediction })); }; setCsvData = csvData => { this.setState({ csvData }, () => { console.log("csvData",this.state.csvData) }); } fetchData = () => { const url = "http://localhost:8000/predict?"+ '&temperature='+this.state.temperature+ '&visibility='+this.state.visibility+ '&windIntensity='+this.state.windIntensity+ '&csvData='+this.state.csvData; fetch(url, { method: "GET", dataType: "JSON", headers: { "Content-Type": "application/json; charset=utf-8", } }) .then((resp) => { return resp.json() }) .then((data) => { this.updateDelay(data.prediction) }) .catch((error) => { console.log(error, "catch the hoop") }) }; handleChange = (name, event) => { this.setState({ [name]: event.target.value }, () => { console.log("csvData", csvData) }); }; handleReset = () => { this.setState({ prediction: … -
django-select2-forms works in admin but not in templates. throws Django TypeError
Running the server throws a Django TypeError: render() got an unexpected keyword argument 'renderer' my forms.py class UserUpdateForm(forms.ModelForm): class Meta: model = User fields = ['username', 'first_name', 'last_name'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Counsellee fields = ['twitter_handle', 'categories', 'image', 'dob', 'gender', 'address', 'phone_number', 'bio', 'interests', 'active'] widgets = { 'dob': forms.TextInput(attrs={'type': 'date'}), 'bio': forms.Textarea(attrs={'rows':3}), 'interests': forms.Textarea(attrs={'rows':3}), } my views.py @login_required def profile_update(request): if request.method == "POST": u_form = UserUpdateForm(request.POST, instance = request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance = request.user.counsellee) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your profile details have been updated successfully!') return redirect('counsellee-home') else: u_form = UserUpdateForm(instance = request.user) p_form = ProfileUpdateForm(instance = request.user.counsellee) context = {'u_form': u_form, 'p_form': p_form} return render(request, 'counsellees/profile.html', context) my models.py class Counsellee(Profile): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name = 'counsellee', null=True) categories = select2.fields.ManyToManyField(Category) interests = models.TextField(null=True, blank = True) twitter_handle = models.CharField(max_length=120, null=True) active = models.BooleanField(default=True, null=True) The widget works just fine in the admin panel but not on the actual site. I followed the README which I found here but no work at all -
Getting stuck in view when using Ajax with Django
I'm trying to use Ajax in order to validate if a value of a field already exists in the DB. urls.py: #App Auxiliares_Tipos: path('ajax/validar_tipaux/', validar_tipaux), path('Tipos_de_auxiliares/', tipoAuxi), views.py: def validar_tipaux(request): codigo = request.GET.get('codigo', None) print(codigo) data = { 'is_taken': TipoAux.objects.filter(codigo__iexact=codigo).exists() } return JsonResponse(data) validation.js is included in my html body. validation.js: $("#id_codigo").change(function () { var tipaux = $(this).val(); console.log(tipaux); $.ajax({ url: '/ajax/validar_tipaux/', data: { 'tipaux': tipaux }, dataType: 'json', success: function (data) { if (data.is_taken) { console.log('Existe'); alert("That value is already taken."); } } }); }); id_codigo is the id of the field that I'm checking if exists with Ajax. The error: it works almost at all, the JavaScript detects changes on id_codigo properly (I'm trying to check everything with print/console.log). But it gets stuck in the view validar_tipaux where it prints None as codigo's value. What's wrong? -
Reverse relations with django-gm2m using "through" relation
I don't understand how to follow many-to-many relations in the reverse direction with django-gm2m. Here is an example of an models.py: from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from gm2m import GM2MField class A(models.Model): pass class B(models.Model): pass class X(models.Model): things = GM2MField() class Y(models.Model): things = GM2MField(through='Yrel') class Yrel(models.Model): y = models.ForeignKey(Y) thing = GenericForeignKey(ct_field='thing_ct', fk_field='thing_fk') thing_ct = models.ForeignKey(ContentType) thing_fk = models.CharField(max_length=255) timestamp = models.DateTimeField(auto_now_add=True) X and Y both have "things" which contains several arbitrary objects. It is Y I have problems with, and X is only for comparison. I have a few objects to test with. a1, a2, b1 = A(), A(), B() a1.save() a2.save() b1.save() etc. With the class X I can do x1, x2 = X(), X() x1.save() x2.save() x1.things.add(a1, b1) x2.things.add(a1) and then get the added things back with x1.things.all() etc. To go in the reverse direction I use x_set as in a1.x_set.count(). So far so good. With "Y" that uses "through" I do y1 = Y() y1.save() Yrel(y=y1, thing=a1).save() Yrel(y=y1, thing=a2).save() to add two "things", and then I can get the list back with y1.things.all() again. But how can I do a reverse lookup from a1 to see where … -
PayPal Orders API V2: Example
i am using PayPal Javasript SDK, and i can not seem to find a good code example of the function actions.order.create(). <script> paypal.Buttons({ createOrder: function(data, actions) { return actions.order.create({ * how to populate this function with more parameters*/ purchase_units: [{ / amount: { value: '{{total}}' } }] }); }, onApprove: function(data, actions) { // Capture the funds from the transaction return actions.order.capture().then(function(details) { // Show a success message to your buyer alert('Transaction completed by ' + details.payer.name.given_name); }); } }).render('#paypal-button-container'); </script> PayPal Docs are not very comprehensive. https://developer.paypal.com/docs/api/orders/v2/. **Any suggestions ? **